for loop indexing per allocating

3 ビュー (過去 30 日間)
Aamna Alshehhi
Aamna Alshehhi 2019 年 11 月 7 日
コメント済み: KALYAN ACHARJYA 2019 年 11 月 7 日
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
  1 件のコメント
KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 11 月 7 日
Well explained Sir!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by