1

So I want to create the sparse matrix as below from the numpy array matrix as usual:

from scipy import sparse
I = np.array([0,1,2, 0,1,2, 0,1,2])
J = np.array([0,0,0,1,1,1,2,2,2])
DataElement = np.array([2,1,2,1,0,1,2,1,2])
A = sparse.coo_matrix((DataElement,(I,J)),shape=(3,3))
print(A.toarray()) ## This is what I expect to see.

enter image description here

My attempt with numpy is:

import numpy as np

U = np.empty((3,3,), order = "F")
U[:] = np.nan

## Initialize 
U[0,0] = 2
U[2,0] = 2
U[0,2] = 2
U[2,2] = 2

for j in range(0,3):
    ## Slice columns first: 
    if (j !=0 and j!= 2):
        for i in range(0,3):
            ## slice rows: 
            if (i != 0 and i != 2):
                  U[i,j] = 0
            else: 
                U[i,j] = 1

enter image description here

2 Answers 2

2

One way using numpy.add.at:

arr = np.zeros((3,3), int)
np.add.at(arr, (I, J), DataElement)
print(arr)

Output:

array([[2, 1, 2],
       [1, 0, 1],
       [2, 1, 2]])
Sign up to request clarification or add additional context in comments.

Comments

0

There are several ways of manual filling of the arrays.

First, you can explicitly define each entry:

U = np.array([[2,1,2],[1,0,1],[2,1,2]],order='F')

Or you can initialize an array with nans and then define each element by subscribing them:

U = np.empty((3,3,), order = "F")
U[:] = np.nan
U[0,0],U[0,1],U[0,2]=2,1,2
U[1,0],U[1,1],U[1,2]=1,0,1
U[2,0],U[2,1],U[2,2]=2,1,2

Finally, if there is a pattern, one can slice and define multiple values at once:

U[:,0]=[2,1,2]
U[:,1]=U[:,0]-1
U[:,2]=U[:,0]

In your attempt, you simply miss some of the entries, and they remain nans.

1 Comment

Thank you!! I just figured it out with the for-loop one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.