for loop indexing per allocating

3 visualizaciones (últimos 30 días)
Aamna Alshehhi
Aamna Alshehhi el 7 de Nov. de 2019
Comentada: KALYAN ACHARJYA el 7 de Nov. de 2019
how can I write the following loop for all t values from 0 to 10, I tried this but I got an error saying
"Index in position 1 is invalid. Array indices must be positive integers or logical values."
for t=0:0.1:10
LA(t/0.1 +1) = 1.15-(5*t);
end

Respuesta aceptada

KALYAN ACHARJYA
KALYAN ACHARJYA el 7 de Nov. de 2019
Editada: KALYAN ACHARJYA el 7 de Nov. de 2019
LA(t/0.1+1)=1.15-(5*t);
%.....^ indexing value must be positive integer
Just an examples :
LA(0.02)>> Not allow
LA(1)>> Allow
LA(0)>> Not allow
May this one?
t=0:0.1:10
for i=1:length(t)
LA(i)=1.15-(5*t(i));
end

Más respuestas (1)

Steven Lord
Steven Lord el 7 de Nov. de 2019
As KALYAN ACHARJYA stated you're not allowed to use either 0 or a non-integer value as an index into a numeric array in MATLAB. [Before you object, this is one of the cases where 0 and false are not treated as the same in MATLAB.]
You should realize that there's no guarantee that t/0.1 is going to be an integer value even if t "looks like" it should be an integer multiple of 0.1.
x = 0:0.1:1;
t = x./0.1;
r = round(10*x);
t == r % Not all values are true
And no, that is not a bug. You can't exactly represent one-tenth as a double precision value and (for example) 0.3 is not exactly three-tenths, in much the same way if you were to compute 1/3 with pencil and paper it's not exactly 0.333333333. [I've left off an infinite number of 3's from the end of that decimal.]
Instead, start off with integer values, use those as indices (if necessary!), and create the non-integer values in your expression. In this case, you don't even need to use those values as indices as you don't need to use a for loop.
tenT = 0:100; % (Essentially) ten times your original T vector
LA = 1.15 - (5*tenT./10); % tenT./10 is essentially your original T vector

Categorías

Más información sobre Matrix Indexing 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