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일

0 개 추천

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일

2 개 추천

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

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by