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:
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.