Home > Blockchain >  Get index in matrix using coordinates from linspace
Get index in matrix using coordinates from linspace

Time:09-30

I have a matrix m defined by two linspaces x and y:

x = np.linspace(-1, 1, 100).reshape(1, 100)
y = np.linspace(-1, 1, 100).reshape(100, 1)

m = x   1j * y

# > m.shape
# (100, 100)

What if I want to set a value to a point at coordinates defined in the given linspace, not the array index?

For example, I would want to write something like this:

m[-0.5, 0.123] = val

Is there an elegant way in numpy to convert from a coordinate system to the closest index in the array?

CodePudding user response:

Here are two possible takes. You could use np.searchsorted to find an index based on value provided x and y are increasing. If x and y are evenly spaced (as in your example of linspace), then you can approximate the index of value val by (val - (-1) / (1 - (-1)) * 100 in O(1) time.

import numpy as np

z = np.linspace(-1, 1, 100)
m = z[None,:]   1j * z[:,None]
# using searchsorted
f = lambda v: np.searchsorted(z, v)
# approximate the index using the fact that numbers in z are evenly spaced
g = lambda v: int((v - z[0]) / (z[-1] - z[0]) * z.shape[0])

print(m[f(0.5), f(0.123)])
# (0.1313131313131315 0.5151515151515154j)
print(m[g(0.5), g(0.123)])
# (0.1313131313131315 0.5151515151515154j)
  • Related