pythonpython-3.xnumpyarray-broadcasting

Can array broadcasting treat larger dimensions as smaller numbers?


I am trying to avoid a for loop by using array broadcasting in order to save time.

My setup is as follows: I have a column array of length n where each element is a mxm array (which I'll call A)

enter image description here

and nxm array (which I'll call E)

enter image description here

My end goal is

enter image description here

where each row of this new array is a result of array broadcasting between A_i (a mxm array) and its corresponding row in E (row with t_i).

It seems like the normal array broadcasting rules wouldn't let this happen because technically A is a nmxm array which, I don't believe, can be broadcast with the E since E is nxm. But you could also think of A as a nx1 column where each element of the column is a mxm array, then the dimensions would be within the array broadcasting rules. Is there a way to force this to happen?

Additionally, in my actual code every A_i is the same. Maybe that would make things easier.


Solution

  • To avoid a for loop, reshape E to (n, 1, m) using np.expand_dims(E, axis=1). This allows broadcasting with A, which has the shape (n, m, m). Since every A_i is the same, you can use a single matrix from A for the operation.