Skip to content
Advertisement

How to broadcast from 3-dimensional matrix using indices from 2-D matrix?

I have a specific matrix with dimensions (nz,ny,nx) and another matrix with dimensions (ny,nx). In this other matrix are specific values and for instance I want to sum all the points in this first 3-dimensional matrix at locations where the second matrix has a specific value.

I am doing the following:

JavaScript

which has (2,X) elements and when I now try to do:

JavaScript

I end with something that is completely wrong or even uses a lot of memory and gets killed in the end.

What is the correct way to broadcast/sum the values in the original matrix using another matrix for mask and a specific mask value to make this sum?

Here is the small example of the problem:

JavaScript

So, in the end I would expect dataout to have 3 elements, but it has dimensions (3,20). Clearly, I am not doing the broadcasting correctly.

Advertisement

Answer

Your sample arrays:

JavaScript

Indices where mask is 5:

JavaScript

I haven’t seen squeeze applied to this, but all it’s doing is converting the tuple of arrays to a (2,52) array. np.argwhere applies np.transpose, producing a (52,2) array.

JavaScript

The where tuple is easier to use when indexing.

JavaScript

Applied to mask itself we get all the 5 values:

JavaScript

Applied to the 3d array:

JavaScript

datain[:,kkw] produces a (3,2,52,10) array. It’s applying the (2,52) array to index just the size 20 dimension. Converting the where tuple to a 2d array does not help with this indexing. When indexing, the distinction between tuples, lists, and arrays is very important.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement