incrementing along a diagonal

David Novakovic david at distip.com.au
Wed Oct 11 19:34:07 EDT 2006


Johannes Loehnert wrote:
>> I'm just wondering if there is a way that i can increment all the values
>> along a diagonal?
>>     
>
> Assume you want to change mat.
>
> # min() only necessary for non-square matrices
> index = arange(min(mat.shape[0], mat.shape[1]))
> # add 1 to each diagonal element
> matrix[index, index] += 1
> # add some other stuff
> matrix[index, index] += some_array_shaped_like_index
>
>
> HTH, Johannes
>
>   
Thank you very much for the prompt reply, I'm just having a problem with
this method:
    This method appears to only work if the matrix is mxm for example:

>>> zeros((5,5))
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
>>> x = zeros((5,5))
>>> index = arange(min(x.shape[0],x.shape[1]))
>>> x[index,index] += 1
>>> x
array([[1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 1, 0],
       [0, 0, 0, 0, 1]])
>>>

This is very nice, exactly what i want, but it doesnt work for mxn
matricies:

>>> x = zeros((5,3))
>>> x
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])
>>> index = arange(min(x.shape[0],x.shape[1]))
>>> x[index,index] += 1
>>> x
array([[1, 0, 0],
       [0, 1, 0],
       [0, 0, 1],
       [0, 0, 0],
       [0, 0, 0]])
>>>

So the min part is right for mxn matrices - but perhaps there is a way
to use the index differently. I'm very new to numpy, so excuse my
noobness :)

Just for reference, this is the line of perl i'm trying to port:


(my $dummy = $ones->diagonal(0,1))++;  # ones is a matrix created with
zeroes()

Yes, i know it is horribly ugly, but in this case, diagonal returns a
list of references to the values in the original matrix, so values can
be changed in place. I much prefer python - hence the port, but it seems
like a hard thing to replicate. Perhaps there could be a function that
returns an iterator over the values in a matrix and returns the index's.

like:

for index in diag_iter(matrix,*axes):
    matrix[index] +=1


Once again, cheers - i hope we can figure something out :)

Dave Novakovic

PS: If anyone would care to link me to the subscription page for the
mailing list so you dont have to CC me all the time :)

-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642




More information about the NumPy-Discussion mailing list