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

回答(2 个)

KSSV
KSSV 2018-4-13
Your loop index should be till length(x)-1
for what = 1:length(x)-1
.
.
.
end

Guillaume
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
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 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