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])
homocomputeris
  • 509
  • 5
  • 18
  • What's the shape and datatype of `M`? Do all *sub-arrays* in `M` have the same shapes? – Divakar Sep 21 '17 at 19:16
  • And `dtype` of `M`? Is it a 1d array of objects, or a multidimensional array of numbers? – hpaulj Sep 21 '17 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? – homocomputeris Sep 22 '17 at 08:07

2 Answers2

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]]])
Psidom
  • 209,562
  • 33
  • 339
  • 356
-1

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

Acccumulation
  • 3,491
  • 1
  • 8
  • 12