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.
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 Exchange에서 Matrix 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