I currently have 2 arrays corresponding to coordinates (X,Y) and a third array corresponding to the value at this point in 2d space. It is coded as such instead of being a matrix, since it is a pretty sparse matrix (not every point possesses a value). Now I want to reconstruct the matrix in order to plot the values with matplotlib.imshow().
So far, the easiest way I have is to do a for loop, like this:
X = [1, 1, 3, 5];
Y = [2, 2, 3, 7];
Z = [0.3, -0.5, 1, 1];
matrix = np.zeros([10,10])
for i in range(len(Z)):
matrix[X[i],Y[i]] = Z[i]
I mean, it is not terrible, but I fear the big arrays. Is there a function that would take the 1st and 2nd inputs as the 1st and 2nd coordinates respectively with the 3rd input as the value at these coordinates? Or would there be something similar?
For what you are doing, you can simply use the lists directly (without) loop. Example -
matrix[X,Y] = Z
Demo -
In [3]: X = [1, 1, 3, 5];
In [4]: Y = [2, 2, 3, 7];
In [5]: Z = [0.3, -0.5, 1, 1];
In [6]: matrix = np.zeros([10,10])
In [7]: matrix[X,Y] = Z
In [8]: matrix
Out[8]:
array([[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[ 0. , 0. , -0.5, 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 1. , 0. , 0. , 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 1. , 0. , 0. ],
[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]])
In [9]: matrix1 = np.zeros([10,10])
In [10]: for i in range(len(Z)):
....: matrix1[X[i],Y[i]] = Z[i]
In [13]: (matrix1 == matrix).all() #Just to show its equal to OP's `for` loop method.
Out[13]: True
Timing tests -
In [24]: X = np.arange(1000)
In [25]: Y = np.arange(1000)
In [26]: Z = np.random.rand(1000)
In [27]: %%timeit
....: matrix = np.zeros([1000,1000])
....: matrix[X,Y] = Z
....:
1000 loops, best of 3: 834 µs per loop
In [28]: %%timeit
....: matrix1 = np.zeros([1000,1000])
....: for i in range(len(Z)):
....: matrix1[X[i],Y[i]] = Z[i]
....:
The slowest run took 6.47 times longer than the fastest. This could mean that an intermediate result is being cached
1000 loops, best of 3: 1.43 ms per loop
The vectorized method would be faster when dealing with large arrays (and Z is large).
If Z is small, then it would be faster to use the for loop method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With