0

To simplify my question, let's say I have these arrays:

a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[2, 2, 2], [3, 3, 3]])
c = np.array([[1, 1, 3], [4, 1, 6]])

I would like to use element-wise multiplication on them so the result will be:

array([[  2,   4,  18],
       [ 48,  15, 108]])

I know I can do a*b*c, but that won't work if I have many 2d arrays or if I don't know the number of arrays. I am also aware of numpy.multiply but that works for only 2 arrays.

Gulzar
  • 23,452
  • 27
  • 113
  • 201
user88484
  • 1,249
  • 1
  • 13
  • 34

1 Answers1

1

Use stack and prod.

stack will create an array which can be reduced by prod along an axis.

import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[2, 2, 2], [3, 3, 3]])
c = np.array([[1, 1, 3], [4, 1, 6]])

unknown_length_list_of_arrays = [a, b, c]

d1 = a * b * c
stacked = np.stack(unknown_length_list_of_arrays)
d2 = np.prod(stacked, axis=0)

np.testing.assert_equal(d1, d2)
Gulzar
  • 23,452
  • 27
  • 113
  • 201
  • I'm curious, is there an advantage to using `np.stack([a, b, c])` instead of `np.array([a, b, c])`? – Mark May 03 '21 at 07:27
  • 1
    @Mark I don't know. But even if they are the same, `stack` is more readable, as one expects the reason to use it to be something like the above. This isn't *really* a *new* array, but just a stack of existing ones. But again, I am not sure they are the same. – Gulzar May 03 '21 at 07:30
  • Interesting @Gulzar, I agree about the readability. I *don't* agree about the stack of existing arrays, unless I misunderstood. The new stack makes copies. Modifying an element in the original has no effect on the stacked arrays and the ids are different. This makes sense since numpy wants contiguous memory. – Mark May 03 '21 at 07:37
  • 1
    @Mark Yes, that is what I meant. The meaning of the stacked variable is a stack of arrays, in the "functional programming" sense of a pipe of instructions on immutable data structures. Behind the scenes it *is* a new array, but the user doesn't really care IMO. We understand each other. – Gulzar May 03 '21 at 07:47