[Numpy-discussion] General Array -> Into Index Array + Value Array of Nonzero Elements
Keith Goodman
kwgoodman@gmail....
Wed Dec 9 14:20:06 CST 2009
On Wed, Dec 9, 2009 at 12:02 PM, Keith Goodman <kwgoodman@gmail.com> wrote:
> On Wed, Dec 9, 2009 at 11:29 AM, Benjamin Kern <benjamin@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]
This is a little less hackish:
>> x = np.tri(3, 3)
>> idx = x.flat == 1
>> y = A.flat[idx]
>> A_pos = np.where(y != 0)[0]
>> A_val = y[A_pos]
More information about the NumPy-Discussion
mailing list