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.

回答 (1 件)

Cris LaPierre
Cris LaPierre 2021 年 7 月 3 日

0 投票

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 件のコメント

dpb
dpb 2021 年 7 月 3 日
編集済み: dpb 2021 年 7 月 3 日
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 2021 年 7 月 4 日
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 2021 年 7 月 4 日
" 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 2021 年 7 月 4 日
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 2021 年 7 月 4 日
That is amazing! Many thanks for that!
dpb
dpb 2021 年 7 月 4 日
Yet again, however, I'd almost wager it isn't the most fruitful approach to the problem...

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

質問済み:

2021 年 7 月 3 日

コメント済み:

dpb
2021 年 7 月 4 日

Community Treasure Hunt

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

Start Hunting!

Translated by