Set condition when index exceeds array bounds
14 次查看(过去 30 天)
显示 更早的评论
I was wondering how to set a condition when the index exceeds array bounds. For example what I have written is,
A=[2,0];B=[1,0];C=[1,1];D=[0,1];E=[2,2]; a=[];
P=[A;B;C];
[rows,cols]=size(P);
x=P(:,1);
y=P(:,2);
for what 1:length(x)
if x(what+1)< length(x) && x(what+1)< length(x)
a1=x(what+1)-y(what+1);
else
break
a=[a;a1]
end
It gives me the error, index array bounds. I don't understand why it still gives that error, given the conditions. Anyone know a way around it?
Thanks
0 个评论
回答(2 个)
Guillaume
2018-11-30
I would recommend that you use KSSV's answer to modify your loop so it indeed stops at numel(x)-1.
The alternative is to fix your poorly thought out if test. You don't want to compare the value of x(what+1) to the length of x. You want to compare the index of x(what+1) to the length. Said index is simply what+1, so the test should be:
if what+1 < length(x) %prefer numel to length
%...
else
a = [a;a1]; %statement after a break would never execute since as soon as matlab sees the break it jumps to the end of the loop
%break; %therefore break must be the last statement. However, since the else will only be true at the last step of the loop, the break is pointless
end
Please, do read the comments I've written above, because you made many mistakes with your code.
1 个评论
snehal gaikwad
2020-11-7
y1=0;
for k=1:4
for i=1:4
yin=y(i)*w(i,k);
y1=y1+yin;
end
y1_new=xb(k)+y1;
y1_new(y1_new>=1)=1;
y1_new(y1_new<1)=0;
y=[y1_new y(k+1:4)];
end
showing me error. help please.w 4x4 matrix, y is 1x4 matrix.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!