Set condition when index exceeds array bounds

14 visualizaciones (últimos 30 días)
Ashy Ander
Ashy Ander el 13 de Abr. de 2018
Comentada: snehal gaikwad el 7 de Nov. de 2020
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

Respuestas (2)

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

Guillaume
Guillaume el 30 de Nov. de 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 comentario
snehal gaikwad
snehal gaikwad el 7 de Nov. de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by