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
2021년 7월 3일
0 개 추천
댓글 수: 6
Lama Hamadeh
2021년 7월 4일
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
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
2021년 7월 4일
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에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

