MATLAB: Sub2ind out of range error

out of range error

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.

Best Answer

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)