I have a matrix of integers, phase_space
of shape (n,n)
, where each entry represents the number of points in that location in space. I also have two update matrices u_x, u_y
also of shape (n,n)
, with integers in the range 0,...,n
specifying where my dynamical system takes each corresponding point in space.
I want to "apply" the update matrices to the phase space iteratively.
For example, if
>>>u_x
array([[1, 2, 1],
[0, 1, 2],
[0, 0, 0]])
>>>u_y
array([[2, 1, 2],
[1, 0, 1],
[2, 2, 0]])
>>>phase_space
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
I want
>>>new_phase_space
array([[1., 1., 2.],
[1., 0., 2.],
[0., 2., 0.]])
My current (working) solution is to loop as follows
for i in range(n):
for j in range(n):
new_phase_space[u_x[i, j], u_y[i, j]] += phase_space[i,j]
Is there any way to vectorize this?
We can use
np.bincount
-Sample run on a more generic setup -
We could also make use of sparse matrices, especially if memory is a concern -
Output would be a sparse matrix. To convert to a dense one, use
out.toarray()
.You can use
pandas.DataFrame.groupby()
to accumulate all moves with same coordinates inphase_space
:Output: