Set condition when index exceeds array bounds

조회 수: 14 (최근 30일)
Ashy Ander
Ashy Ander 2018년 4월 13일
댓글: snehal gaikwad 2020년 11월 7일
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