for loop indexing per allocating

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

采纳的回答

KALYAN ACHARJYA
KALYAN ACHARJYA 2019-11-7
编辑:KALYAN ACHARJYA 2019-11-7
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

更多回答(1 个)

Steven Lord
Steven Lord 2019-11-7
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

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by