On 03/09/06, Charles R Harris <[EMAIL PROTECTED]> wrote:
Travis has introduced the function diagflat for creating diagonal arrays. It
flattens whatever array is supplied and returns its values as the diagonal
of a 2-D array or matrix. As the function is currently undocumented I
thought now might be a good time to discuss other possible choices for the
name. Here is a quick list that comes to mind

diagflat (current name)
asdiagonal
todiagonal
asdiag
todiag
...

I was wishing for that just the other day... I think my vote is for
"diagflat", to emphasize the initial flattening.

In particular, there's another function I could wish for: given an
array, pick an axis, treat the array like an array of vectors along
that axis, and replace each vector with the diagonal matrix. So,
supposing that it was called todiagonal:
A = todiagonal(ones(2,3,4),axis=1)
shape(A)
(2,3,3,4)
A[1,:,:,2]
array([[1, 0, 0],
          [0, 1, 0],
          [0, 0, 1]])

Specifically I find the forcible flattening a bit monstrous. And you
can always just do todiagonal(A.flat).

No such function seems to exist at the moment, so I'm attaching one;
probably not as efficient as it could be with appropriate fancy
indexing wizardry.

A. M. Archibald
from numpy import zeros, shape, newaxis, repeat, where, indices, asarray
import sys
 
def todiagonal(A,axis=-1):
    A = asarray(A)
    s = shape(A)
    if axis<0:
	axis += len(s)
    if not 0<=axis<len(s):
	raise IndexError, "Axis out of range"

    # Concoct an index object like [:,:,newaxis,:,:]
    new_indices = [slice(0, sys.maxint, None) for i in s]
    new_indices.insert(axis,newaxis)

    # repeat along the new axis
    D = repeat(A[new_indices], repeats=s[axis], axis=axis)

    # zero everything but the diagonals
    return where(indices(D.shape)[axis]==indices(D.shape)[axis+1], D, 0)


if __name__=='__main__':
    import numpy
    print todiagonal(numpy.array([1,2,3]),axis=0)
    print todiagonal(numpy.ones([3,2],int),axis=1)
    print todiagonal(numpy.ones([3,2],numpy.uint8),axis=0)
    print todiagonal([1,2,3])
    
-------------------------------------------------------------------------
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
_______________________________________________
Numpy-discussion mailing list
Numpy-discussion@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/numpy-discussion

Reply via email to