how to overcome error: Index in position 1 is invalid. Array indices must be positive integers or logical values.
82 次查看(过去 30 天)
显示 更早的评论
Putri Basenda Tarigan
2020-11-26
评论: Pier Giorgio Petrolini
2020-11-26
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
0 个评论
采纳的回答
Pier Giorgio Petrolini
2020-11-26
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
2 个评论
更多回答(1 个)
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 个评论
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 Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!