How to subset an array using a logical mask?

Hey friends,

Lets say i have a grid of cells and a array called ‘cell’ that, for example, cell(4) = 1 and cell(8)=1, that means that the particle 4 and particle 8 are in cell number 1, so, i need a way to know that these two particles are in these cell, for example, in a loop passing through all the cells and i’m in c=1 so i need that an array particles_in_cell = (4,8). The particle 4 have an x coordinate x(4) and particle 8 x(8), x is an array that have the coordinates of all N particles, but i want x_c to be just the coordinates of the particles that are in that cell c. In python thats is easy to be x_c = x[particles_in_cell] that makes me the array of the coordinates of just the two particles but in fortran i have no idea on how to make that.

edit1: i was thinking in something like x_c = x(cell == c) but cell==c it’s a logical array so… yeah idk

Would the intrinsic pack work?

x_c = pack(x, cell == c)

You could also do it with the standard library’s trueloc:

x_c = x(trueloc(cell == c))
1 Like

i think it is perfect! thank you i didn’t know this pack function

1 Like

Should you need it: It is accompanied by the unpack function that expands the array.

1 Like