[Numpy-discussion] General Array -> Into Index Array + Value Array of Nonzero Elements

Keith Goodman kwgoodman at gmail.com
Wed Dec 9 15:02:16 EST 2009


On Wed, Dec 9, 2009 at 11:29 AM, Benjamin Kern <benjamin at kerns.de> wrote:
> Hello everyone,
>
> at the moment i like to create a numpy interface to a library for numerical optimization. This library uses a special format to include symmetric matrices, basically if you have
>
> A = np.array([ [1.0, 0.0, 2.0]
>                         [0.0, 3.0, 0.0]
>                         [2.0, 0.0, 5.0] ] )
>
> you would have to create 2 arrays which specify the position as well as the the non-zero elements
> of the lower triangular part of the matrix. So in this example you would need the following arrays to specify the matrix completely
>
> A_pos = np.array([0, 2, 3, 5], dtype=int )
> A_val = np.array([1.0, 3.0, 2.0, 5.0])
>
> So now to my question. Is there a clever way to extract these two arrays A_pos and A_val from an arbirtrary A (where A.ndim=2)
> Another question would be if there is the possibility to do something similiar if you are using sparse matrices (from scipy.sparse).
>
> Best
> Benjamin

I don't know of a clever way. But it is always possible to hack
something together:

>> x = np.tri(3, 3, k=0)
>> x[x==0] = np.nan
>> y = (A*x).reshape(-1)
>> y = y[np.isfinite(y)]
>> A_pos = np.where(y != 0)[0]
>> A_val = y[A_pos]



More information about the NumPy-Discussion mailing list