Set condition when index exceeds array bounds
14 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (2)
Guillaume
le 30 Nov 2018
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 commentaire
snehal gaikwad
le 7 Nov 2020
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.
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!