Accessing a cell in a 2D grid
Mostrar comentarios más antiguos
Hi all,
I have a 2D grid as shown below where each cell represents a pair of
and
where
and
. I would like to construct a new index that combines these two indices to run over all of the cells as a one continous number.

Any help would be appreciated.
Thanks.
Respuestas (1)
Cris LaPierre
el 3 de Jul. de 2021
0 votos
6 comentarios
Lama Hamadeh
el 4 de Jul. de 2021
dpb
el 4 de Jul. de 2021
" what I need is a mathematical formula that depends on (i) and (j) that represents a given cell. "
Well, that's pretty easy to derive from the ordering chosen and the size of the array. Look at the pattern in the numbers you've written down--it's a linear expression in N and M.
Why nobody has given it to you is because in MATLAB there's probably a much more efficient way to code whatever it is you're after than by such an expression so we're trying to guide you towards that solution instead.
NB: Your ordering above is reversed from MATLAB storage order in going from LLH corner up rather than ULH corner down.
dpb
el 4 de Jul. de 2021
BTW, the "formula" in MATLAB is
k=ind2sub(size(A),i,j);
which can be written as
k=ind2sub([M,N],i,j);
if you have the dimensions instead.
>> fnNDX=@(SZ,i,j) SZ(1).*(i-1)+j
fnNDX =
function_handle with value:
@(SZ,i,j)SZ(1).*(i-1)+j
>> [X,Y]=meshgrid([1:4].',[1:4].');
>> fnNDX([4,4],X,Y)
ans =
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
>>
Lama Hamadeh
el 4 de Jul. de 2021
dpb
el 4 de Jul. de 2021
Yet again, however, I'd almost wager it isn't the most fruitful approach to the problem...
Categorías
Más información sobre Matrix Indexing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

