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

조회 수: 175 (최근 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
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

추가 답변 (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
Putri Basenda Tarigan 2020년 11월 26일
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