0

What is the most concise way to carry out multiplication like this?

# c's are scalars (or arrays like A's in general)
x = np.array([c1, c2, c3])
# A's are NumPy arrays
M = np.array([A1, A2, A3])

to get

x*M = [c1*A1, c2*A2, c3*A3]

c's are scalars, A's are NumPy numerical multidim arrays (let's say, matrices).


Example code:

x = np.array([1,2,3])
A = np.random.rand(2,2)
M = np.array([A,A,A])
3
  • What's the shape and datatype of M? Do all sub-arrays in M have the same shapes? Commented Sep 21, 2017 at 19:16
  • And dtype of M? Is it a 1d array of objects, or a multidimensional array of numbers? Commented Sep 21, 2017 at 19:22
  • @hpaulj Let's suppose they are multidimensional arrays of numbers - for simplicity - 2D matrices stored as np.array. Why does it matter? Scalar can be multiplied by almost anything, can't it? Commented Sep 22, 2017 at 8:07

2 Answers 2

2

If M is a numpy array of primitive numeric types, (i.e. not objects), to take advantage of the numpy broadcasting, you can add dimensions to x so it has the same number of dimensions as M, and then the element-wise multiplication should work:

x.reshape((-1,) + (1,)*(M.ndim - 1)) * M

x = np.array([1,2,3])

2D case:

M = np.arange(12).reshape(3,4)    
x.reshape((-1,) + (1,)*(M.ndim - 1)) * M
#array([[ 0,  1,  2,  3],
#       [ 8, 10, 12, 14],
#       [24, 27, 30, 33]])

3D case:

M = np.arange(12).reshape(3,2,2)
x.reshape((-1,) + (1,)*(M.ndim - 1)) * M
#array([[[ 0,  1],
#        [ 2,  3]],

#       [[ 8, 10],
#        [12, 14]],

#       [[24, 27],
#        [30, 33]]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this one works. But the readability... It took me a while to understand what's happening :)
-1

product = [x[i]*M[i] for i in range(len(x))]

1 Comment

Or like this: [A*c for (A,c) in zip(M,x)]. Anyway, I believe that comprehensions are slower.

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.