MATLAB: Index exceeds matrix dimensions.

matrix dimensions

*Y=2;
g=[20,10];
w=40 : -2 : 3;
for x=1:length(w)
if w(x)<=5 "why get I problem here, its says 'Index exceeds matrix dimensions'"
break
else
w=setdiff(w(w>(5)),g);
A= x*3;
w1=A.*Y;
end
end*

Best Answer

Because at the following line
w=setdiff(w(w>(5)),g)
your w vector becomes a 16 element array when x=1 and when x=17, you try to reach 17th element of your w array, which is not possible.
If you put a counter to your loop named cnt as follows, you will see the reason actually:
Y=2;
g=[20,10];
w=40 : -2 : 3;
cnt=0;
for x=1:length(w)
cnt=cnt+1;
if w(x)<=5 "why get I problem here, its says 'Index exceeds matrix dimensions'"
break
else
w=setdiff(w(w>(5)),g);
A= x*3;
w1=A.*Y;
end
end
When the loop is broken, the value of cnt is 17.