2

I have a numpy array 'arr' of shape (100000,). I need to create a numpy matrix 'res_matrix' of shape 100000X100000 such that

for i in range(res_matrix.shape[0]):
    for j in range(res_matrix.shape[1]):
        res_matrix[i][j]= arr[i]*arr[j]

Sample input/output


arr=[1 2 4]


Output:
res_matrix:

[[1 2 4]
 [2 4 18]
 [4 8 16]]

Is there way to do vectorize this operation, to reduce the computation time of calculating 00000X100000 in loop?

2
  • 3
    np.multiply.outer(arr, arr) Commented Jan 6, 2021 at 16:03
  • You could also use broadcasting Commented Jan 6, 2021 at 16:08

1 Answer 1

2

There are a few ways you can get an outer multiplication.

arr = np.array([1,2,4])

#Using Multiply outer
print(np.multiply.outer(arr, arr)) #As suggested by Warren

#Using broadcasting
print(arr[:,None] * arr[None,:]) #(3,1) * (1,3)
[[ 1  2  4]
 [ 2  4  8]
 [ 4  8 16]]

[[ 1  2  4]
 [ 2  4  8]
 [ 4  8 16]]

​ Note, the output is still a very large matrix for storing in memory. Depending on what you need it for, I would advise considering something like a generator function. Let me know how you are going to use this matrix and I could suggest more memory efficient methods.

Sign up to request clarification or add additional context in comments.

Comments

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.