Index exceeds the number of array elements error

1 visualización (últimos 30 días)
Daniel Lee
Daniel Lee el 2 de Nov. de 2020
Comentada: Daniel Lee el 2 de Nov. de 2020
When I run below code, I get error: Index exceeds the number of array elements (5).
Can someone please help me understand why I'm getting this error? As for loop is processed 5 times (in below example), shouldnt I get matrix size of 1x5 of 'n' values? like n= [1 0 1 2 3]?
Thank you
>> r=exprnd(1/8, 1,5);
>> at=cumsum(r);
>> st=exprnd(1/8, 1, 5);
>> n = 0;
>> ord=2:1:6;
>> n=0;
>> for x=1:5; %x defines # of sims
if at(ord-1) + cumsum(st(ord-1)) ==at(ord)
n=n
elseif at(ord-1) + cumsum(st(ord-1)) < at(ord)
n=n-1
else
n=n+1
plot(n)
end
end

Respuesta aceptada

VBBV
VBBV el 2 de Nov. de 2020
Editada: VBBV el 2 de Nov. de 2020
Use for loop index to access the vector as below
%if true
% code
% end
>> r=exprnd(1/8, 1,5);
>> at=cumsum(r);
>> st=exprnd(1/8, 1, 5);
>> n = 0;
>> ord=2:1:6;
>> n=0;
>> for x=1:5; %x defines # of sims
if at(ord(x)-1) + cumsum(st(ord(x)-1)) ==at(ord(x))
n=n
elseif at(ord(x)-1) + cumsum(st(ord(x)-1)) < at(ord(x))
n=n-1
else
n=n+1
plot(n)
end
end
  2 comentarios
Daniel Lee
Daniel Lee el 2 de Nov. de 2020
Thanks Vasishta,
I got 4 results by running your version, but at the end, I'm still getting the same index exceeds the nubmer of array elements (5)...
Daniel Lee
Daniel Lee el 2 de Nov. de 2020
Ah, nevermind. I know why. When x=5, ord = 6 which doesnt exist. thanks

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

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

Etiquetas

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by