how to overcome error: Index in position 1 is invalid. Array indices must be positive integers or logical values.

148 visualizaciones (últimos 30 días)
Hello everyone
Seems I can't fix my problem
I have code like this:
alpha=0.1:0.1:1;
a=[1 2 3 4 5 6];
u=[1 3 3 3 2 1];
op=[3 3 3 3 3 3];
act=numel(a);
d=cumsum(u);
n=length(alpha)*d(act);
o=3;
B=zeros(n,(3+(o*max(op)))); % I want to store all my result in this matrix
then I have calculation like:
for z=alpha
for i=1:act
for j=1:u(i)
options=zeros(1,o*(op(i))); % I want to store the result of my calculation for each iteration in this matrix
for k=1:op(i)
r=a(i)-(u(i)-j+1)*op(i)+k;
t=1;
c=2;
q=3; % t,c,q is my calculation. actually it was so long, so I just simplify it here
options(1,((o*(k-1)+1):(o*k)))=[t c q];
end
e=z*10
e=e*d(act)-d(act)+d(i)-u(i)+j;
B(e,1)=z;
B(e,2)=i;
B(e,3)=j;
B(e,4:end)=options;
end
end
end
B
I want to get matrix B.
but for this code, I got error for
Index in position 1 is invalid. Array indices must be positive integers or logical values.
Error in (line 27)
B(e,1)=z;
it stops when the alpha is 0.3
Please help.
Thank you

Respuesta aceptada

Pier Giorgio Petrolini
Pier Giorgio Petrolini el 26 de Nov. de 2020
Hello, the problem is basically that the variable "e" after calculations has some decimals (zeros), and you can't use it as it is for indexing because index should be integers.
Try to rewrite the code by adding the command "int64" as follow:
....
e=z*10
e=int64(e*d(act)-d(act)+d(i)-u(i)+j);
B(e,1)=z;
....
I hope it helps, let me know!
Kind regards,
PGP

Más respuestas (1)

Walter Roberson
Walter Roberson el 26 de Nov. de 2020
alpha=0.1:0.1:1;
When you multiply by 10 you do not always get integers. 0.1 does not have an exact representation in finite binary, and the error adds up.
You can round(e) but there are better ways.
  2 comentarios
Putri Basenda Tarigan
Putri Basenda Tarigan el 26 de Nov. de 2020
Thankyou so much for the answer Sir.
But, how can I round e Sir?
I multiply it by 10 Because I want to get the row number for each iteration Sir.
Walter Roberson
Walter Roberson el 26 de Nov. de 2020
for zidx = 1 : numel(alpha)
z = alpha(zidx);
for i=1:act
for j=1:u(i)
options=zeros(1,o*(op(i))); % I want to store the result of my calculation for each iteration in this matrix
for k=1:op(i)
r=a(i)-(u(i)-j+1)*op(i)+k;
t=1;
c=2;
q=3; % t,c,q is my calculation. actually it was so long, so I just simplify it here
options(1,((o*(k-1)+1):(o*k)))=[t c q];
end
e = zidx;
e=e*d(act)-d(act)+d(i)-u(i)+j;
B(e,1)=z;
B(e,2)=i;
B(e,3)=j;
B(e,4:end)=options;
end
end
end
B

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by