Linear indices from colon operator

조회 수: 2 (최근 30일)
Radek
Radek 2024년 11월 14일
편집: Stephen23 2024년 11월 15일
Any array (let's consider only 2D here) can be indexed using colon operator such
array(p1:p2,p3:p4)
How can one generate list of linear indices (for that particular array) from parameters [p1, p2, p3, p4]?

채택된 답변

Matt J
Matt J 2024년 11월 14일
[I,J]=ndgrid(p1:p2,p3:p4);
linear=sub2ind(size(array) , I,J);

추가 답변 (2개)

Steven Lord
Steven Lord 2024년 11월 14일
See sub2ind.
  댓글 수: 2
Stephen23
Stephen23 2024년 11월 14일
편집: Stephen23 2024년 11월 15일
Note that in general p1:p2 and p3:p4 when used a indices like that will refer to a rectangular block of that array. So in order to get the linear indices of the entire block you will need to provide SUB2IND with subscript indices for the entire block. One way to achieve this is using NDGRID:
array = randi(9,9,9);
p1 = 3;
p2 = 5;
p3 = 2;
p4 = 5;
[X,Y] = ndgrid(p1:p2,p3:p4);
Z = sub2ind(size(array),X,Y);
array(Z)
ans = 3×4
4 7 2 6 9 9 6 7 1 2 4 8
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
array(p1:p2,p3:p4)
ans = 3×4
4 7 2 6 9 9 6 7 1 2 4 8
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Walter Roberson
Walter Roberson 2024년 11월 14일
sub2ind() processes the indexes in parallel. All of the indices must be the same size (or else scalars)
sub2ind([4 5],1:2,1:3)
Error using sub2ind (line 61)
Subscript arguments must be scalars or arrays of the same size.

댓글을 달려면 로그인하십시오.


Catalytic
Catalytic 2024년 11월 14일
편집: Catalytic 2024년 11월 14일
K=createArray(size(array),Fill=sparse(0));
K(p1:p2,p3:p4)=1;
out=find(K); %linear indices
  댓글 수: 1
Matt J
Matt J 2024년 11월 14일
I would probably do instead,
K=createArray(size(array),Fill=sparse(false));
or maybe just use,
K=false(size(array))
depending on the expected size of the output.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by