Getting linear indices from two vectors containing x and y components of Cartesian coordinates (sub2ind versus LinearIndices())

I have some matlab code that uses the old sub2ind way of getting the linear indices (this is a simplified version that gets at the essence of it):

row = [1, 2, 3]; # x-component of cartesian index
column = [1, 2, 3]; # y-component of cartesian index
sz = [3 3];  # size of the matrix
ind = sub2ind(sz, row, column);

This spits out ind = [1, 5, 9]

Using the LinearIndices() and CartesianIndex() functions that Julia moved to I can implement it like this:

inds = LinearIndices((3, 3))[CartesianIndex.(row, col)]

But this somehow seems clunky. According to Pluto it is also slower that the deprecated sub2ind function:

Is there a better way to implement this?

1 Like

A long discussion about this:

where the upshot (as I read it) is: If you really need linear indices, you can get them with:

ind2subv(shape, indices) = Tuple.(CartesianIndices(shape)[indices])
sub2indv(shape, indices) = LinearIndices(shape)[CartesianIndex.(indices)]

One question is, though, why do you need linear indices?

1 Like

Thanks, I had seen that thread. I see that the implementation is the same as what I ended up with.

I’m using linear indices since in the optical simulation I’m running, the physical pixel locations of lenses are being calculated using cartesian coordinates (essentially creating a square grid of points once combined into a meshgrid).

It seems the most convenient way to then index into the new matrix and set the corresponding pixel coordinates to a certain value is to convert into linear indices. Maybe there’s a more Julianic way to achieve the same result, but it works pretty well as it stands.

I don’t quite follow your description. The only question I was wondering about was: why not directly iterate over the CartesianIndices((row, col))? As in:

A = rand(4,3);
for idx in CartesianIndices((1:3, 1:2))
  println(A[idx]); 
end

But if your solution works, it’s probably not worth worrying about it.