3

I need to create a matrix with values from a numpy array. The values should be distributed over the matrix lines according to an array of indices.

Like this:

>>> values
array([ 0.73620381,  0.61843002,  0.33604769,  0.72344274,  0.48943796])
>>> inds
array([0, 1, 2, 3, 2])
>>> m = np.zeros((4, 5))
>>> for i, (index, value) in enumerate(zip(inds, values)):
        m[index, i] = value
>>> m
array([[ 0.73620381,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.61843002,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.33604769,  0.        ,  0.48943796],
       [ 0.        ,  0.        ,  0.        ,  0.72344274,  0.        ]])

I'd like to know if there is a vectorized way to do it, i.e., without a loop. Any suggestions?

2 Answers 2

4

Here's how you could do it with fancy indexing:

>>> values
array([ 0.73620381,  0.61843002,  0.33604769,  0.72344274,  0.48943796])
>>> inds
array([0, 1, 2, 3, 2])
>>> mshape = (4,5)
>>> m = np.zeros(mshape)
>>> m[inds,np.arange(mshape[1])] = values
>>> m
array([[ 0.73620381,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.61843002,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.33604769,  0.        ,  0.48943796],
       [ 0.        ,  0.        ,  0.        ,  0.72344274,  0.        ]])
Sign up to request clarification or add additional context in comments.

2 Comments

[Looks in his command history to see why this didn't work for him, given that it was the first thing he tried.. realizes that he's an idiot.. deletes his answer and upvotes this. IOW, a typical afternoon.]
@DSM, we've all been there. FWIW, your numpy/scipy answers are always stellar.
2

Your values and inds arrays can be used as input to a scipy.sparse constructor (similar to sparse in Matlab).

from scipy import sparse
values = np.array([ 0.73620381,  0.61843002,  0.33604769,  0.72344274,  0.48943796])
inds=np.array([0,1,2,3,2])
index = np.arange(5)
m=sparse.csc_matrix((values,(inds,index)),shape=(4,5))
m.todense()  # produces a matrix or
m.toarray()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.