This question already has answers here:
Forming a matrix by summing 2 arrays element-array wise using NumPy (2 answers)
Closed 3 years ago.
Given 2 numpy (1D) arrays, I want to compute the 2D array containing all possible sums of elements of those two arrays. For example, like this:
import numpy as np
v = np.array([1, 2, 3])
w = np.array([4, 5, 6])
sum_matrix = np.zeros((3,3))
for i in range(3):
for j in range(3):
sum_matrix[i,j] = v[i] + w[j]
print(sum_matrix)
This returns the correct answer
[[5. 6. 7.]
[6. 7. 8.]
[7. 8. 9.]]
but I want to avoid python loops (and certainly a double one). Is there some nice numpy functionality for this situation?
I can think of one solution that avoids all loops, but it feels kind of like a hack. I noticed that if v is a column matrix and w a row matrix, then the matrix product v @ w returns the matrix of all possible products. I can translate this to sums using log and exp:
v = v[np.newaxis].T # Turn v into a column matrix
w = w[np.newaxis] # Turn w into a row matrix
print(np.log(np.exp(v) @ np.exp(w)))
This prints the same as the above.
Question: Are there other, less hacky, numpy solutions to this problem?
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)