sub2ind out of range error

2 views (last 30 days)
patchaisri periyasamy
patchaisri periyasamy on 16 Feb 2019
Commented: Rik on 18 Feb 2019
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.

Accepted Answer

Rik
Rik on 16 Feb 2019
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 Comment
Rik
Rik on 18 Feb 2019
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.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!