sub2ind out of range error

조회 수: 1 (최근 30일)
patchaisri periyasamy
patchaisri periyasamy 2019년 2월 16일
댓글: Rik 2019년 2월 18일
a=trainclass{1,1};//dimension of trainclass is (200x103double)
[r c dim]=size(a);
[x,y]=ndgrid(1:r,1:2:c);
ind=sub2ind(size(a),x,y);
indshift=sub2ind(size(a),x,y+1); //when i run this script, i got out of range error in this line.

채택된 답변

Rik
Rik 2019년 2월 16일
Because you generate y to be size of a (if the size is odd), you can't add 1 to it, because then it will be out of range.
a=[1 2 3; 4 5 6];
[r c dim]=size(a);
[x,y]=ndgrid(1:r,1:2:c);
indshift=sub2ind(size(a),x,y+1);%returns error
Now y will contain values 1 and 3, so y+1 will be 2 and 4, which is out of range.
a=[1 2; 4 5];
[r c dim]=size(a);
[x,y]=ndgrid(1:r,1:2:c);
indshift=sub2ind(size(a),x,y+1);%doesn't return an error
You should have a method to prevent values in y to become bigger than c. How you should do that (removing or setting to c), depends on your context, so that is a choice you need to make yourself.
(note that this is a Matlab forum, not Octave, so you should make sure your issue exists in Matlab as well)
  댓글 수: 1
Rik
Rik 2019년 2월 18일
Did this suggestion solve your problem? If so, please consider marking it as accepted answer. It will make it easier for other people with the same question to find an answer. If this didn't solve your question, please comment with what problems you are still having.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by