Accessing a cell in a 2D grid

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
Cris LaPierre el 3 de Jul. de 2021

0 votos

Consider using linear indexing. You can find an explanation towards the middle of this page. It is also explained here. If you need to go back and forth between a linear index and row/column indexing, you can use the functions ind2sub and sub2ind.

6 comentarios

dpb
dpb el 3 de Jul. de 2021
Editada: dpb el 3 de Jul. de 2021
You should also consider whether you actually need to address the individual cells directly by index or whether couldn't use vectorized expressions.
We don't know the perceived need/use for this so can't give specifics...
Lama Hamadeh
Lama Hamadeh el 4 de Jul. de 2021
Many thanks for your reply. However, I still don't have an answer for my question. Probably it's my fault I didn't explain better, but what I need is a mathematical formula that depends on (i) and (j) that represents a given cell. Hopefully the below sketch can describe what I have in mind:
dpb
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
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
Lama Hamadeh el 4 de Jul. de 2021
That is amazing! Many thanks for that!
dpb
dpb el 4 de Jul. de 2021
Yet again, however, I'd almost wager it isn't the most fruitful approach to the problem...

Iniciar sesión para comentar.

Categorías

Preguntada:

el 3 de Jul. de 2021

Comentada:

dpb
el 4 de Jul. de 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by