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

82 次查看(过去 30 天)
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

采纳的回答

Pier Giorgio Petrolini
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

更多回答(1 个)

Walter Roberson
Walter Roberson 2020-11-26
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 个评论
Putri Basenda Tarigan
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 2020-11-26
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by