Subscript indices problem with a for loop

2 ビュー (過去 30 日間)
Camran Purewal
Camran Purewal 2017 年 3 月 15 日
編集済み: Jan 2017 年 3 月 15 日
Hello, I am having problems creating a for loop to calculate and store temperatures in the various sections of the atmosphere, with the following code I get the error "Subscript indices must either be real positive integer or logicals":
Altitude = 0:1:100000; Temperature 1 = 288.15; L0 = -0.0065;
for i = 1:11001 Altitude = i -1; Temperature(Altitude) = Temperature1 + (L0*Altitude); end
Thank you.

回答 (2 件)

Jan
Jan 2017 年 3 月 15 日
編集済み: Jan 2017 年 3 月 15 日
With your code in the first iteration tis happens:
Temperature(0) = Temperature1 + (L0 * Altitude);
but 0 is not a valid index. USe this instead:
Temperature1 = 288.15;
L0 = -0.0065;
Temperature = zeros(1, 11001); % Pre-allocate!!!
for k = 1:11001
Temperature(i) = Temperature1 + (L0 * (i-1));
end
Or shorter without the loop:
Temperature = Temperature1 + L0 * (0:11000);

Alexandra Harkai
Alexandra Harkai 2017 年 3 月 15 日
Altitude is 0 in the first loop, which is not a valid index in this case.
It is suspicious though that you assign a numerical array to Altitude, then later it gets overwritten by i-1.
This also doesn't look OK, you should get an error:
Temperature 1 = 288.15;
Overall it seems you are using a loop for something that doesn't require a loop: multiplying a vector with a scalar and then adding another scalar to it. You can just write it like so:
Temperature = Temperature1 + (L0 * 0:11000);

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by