Helper function to "unroll" a array

Gael Varoquaux gael.varoquaux at normalesup.org
Fri Oct 20 06:28:52 CDT 2006


Hi,

There is an operation I do a lot, I would call it "unrolling" a array.
The best way to describe it is probably to give the code:

def unroll(M):
    """ Flattens the array M and returns a 2D array with the first columns 
	being the indices of M, and the last column the flatten M.
    """
    return hstack((indices(M.shape).reshape(-1,M.ndim),M.reshape(-1,1)))

Example:

>>> M
array([[ 0.73530097,  0.3553424 ,  0.3719772 ],
       [ 0.83353373,  0.74622133,  0.14748905],
       [ 0.72023762,  0.32306969,  0.19142366]])

>>> unroll(M)
array([[ 0.        ,  0.        ,  0.73530097],
       [ 0.        ,  1.        ,  0.3553424 ],
       [ 1.        ,  1.        ,  0.3719772 ],
       [ 2.        ,  2.        ,  0.83353373],
       [ 2.        ,  0.        ,  0.74622133],
       [ 1.        ,  2.        ,  0.14748905],
       [ 0.        ,  1.        ,  0.72023762],
       [ 2.        ,  0.        ,  0.32306969],
       [ 1.        ,  2.        ,  0.19142366]])


The docstring sucks. The function is trivial (when you know numpy a bit).
Maybe this function already exists in numpy, if so I couldn't find it.
Elsewhere I propose it for inclusion.

Cheers,

Gaël

-------------------------------------------------------------------------
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