Borrar filtros
Borrar filtros

Error "Subscript indices must either be real positive integers or logicals." At random index

1 visualización (últimos 30 días)
I'm having some trouble with a for loop. For some reason, it works properly until the first of the 3 loops gets to the number 4.8 (when j=4.8) where it stops the program and shows the error "Subscript indices must either be real positive integers or logicals."
This is the code:
syms s;
s=tf('s');
X=zeros(25,25,25);
for i=2:0.2:7
for a=2:0.2:7
for j=2:0.2:7
L=(s+i)*(s+j)*(s+a)/s/(s+10000)^2;
Y=step(L/(1+L),t);
if max(Y)<1.11
X(i*5-9,5*j-9,a*5-9)=1;
else
X(i*5-9,5*j-9,a*5-9)=0;
end
end
end
end
(Edited)
Anyone knows what is going on?

Respuesta aceptada

Adam Danz
Adam Danz el 9 de Ag. de 2019
Editada: Adam Danz el 9 de Ag. de 2019
Indexing requires positive integer values just as the error message indicates. At lease one of the three indices of X is not a positive integer.
X(i*5-9, 5*j-9, a*5-9)
[Update]
The 2nd index (5*j-9) is producing what appears to be an integer (15) but, in fact, is not an integer.
sprintf('%.20f',5*j-9)
ans =
'15.00000000000000355271'
That's because "j" is not really 4.8
sprintf('%.20f',j)
ans =
'4.80000000000000071054'
The reason is due to round-off error associated with floating point number representation when you create this sequence 2:0.2:7. A great article was written by a cofounder of MathWorks, Cleve Moler, that explains this problem.
Instead, use integers to control your loops.
X=zeros(25,25,25);
iSeq = 2:0.2:7;
aSeq = 2:0.2:7;
jSeq = 2:0.2:7;
for i=1:numel(iSeq)
for a=1:numel(aSeq)
for j=1:numel(jSeq)
L=(s+iSeq(i))*(s+jSeq(j))*(s+aSeq(a))/s/(s+10000)^2;
Y=step(L/(1+L),t);
if max(Y)<1.11
X(i,j,a)=1; % <-- double check that this is correct
else
X(i,j,a)=0; % <-- double check that this is correct
end
end
end
end
Also, this will surely result in an error
L=*(s+i)*(s+j)*(s+a)/s/(s+10000)^2;
% ^
  2 comentarios
Andibadia
Andibadia el 9 de Ag. de 2019
Thank you! The last part was a mistake copying the code from MATLAB. But yes, I used the function round() before each number and now it works great!
Adam Danz
Adam Danz el 9 de Ag. de 2019
OK! I updated my answer to suggest an alternative but if round() works, then that would be OK, too.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

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

Productos


Versión

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by