Index exceeds number of array elements

here's my code - when i run it i get "index exceeds number of array elements" at line 7 but there's 7 elements in temp so im not sure why im getting the error?
altitude = 0.0; 11.0; 20.0; 32.0; 47.0; 51.0; 71.0;
lapse_rate = -6.5; 0.0; 1.0; 2.8; 0.0; -2.8; -2.0;
temp = 288; 0; 0; 0; 0; 0; 0;
% t(n+1) = t(n) + altitude*lapse rate
for i = 1:7
j = i+1;
temp(j) = temp(i)+altitude(j)*lapse_rate(j);
end
temp

1 个评论

if i = 7, j is 8. The arrays you defined have only 7 elements. So the index exceeds the number of array elements for j=8 (8 is greater than 7).

请先登录,再进行评论。

 采纳的回答

Actually those variables are scalars (only one element each):
% after "altitude = 0.0;" the rest of the line has no effect:
altitude = 0.0; 11.0; 20.0; 32.0; 47.0; 51.0; 71.0;
% similarly here:
lapse_rate = -6.5; 0.0; 1.0; 2.8; 0.0; -2.8; -2.0;
% and here:
temp = 288; 0; 0; 0; 0; 0; 0;
whos
Name Size Bytes Class Attributes altitude 1x1 8 double ans 1x1 8 double lapse_rate 1x1 8 double temp 1x1 8 double
Put brackets around the expressions to make the variables have 7 elements each:
altitude = [0.0; 11.0; 20.0; 32.0; 47.0; 51.0; 71.0];
lapse_rate = [-6.5; 0.0; 1.0; 2.8; 0.0; -2.8; -2.0];
temp = [288; 0; 0; 0; 0; 0; 0];
whos
Name Size Bytes Class Attributes altitude 7x1 56 double ans 1x1 8 double lapse_rate 7x1 56 double temp 7x1 56 double
Now you will still get the error because you're indexing altitude and lapse_rate with j, which is one more than i, so j goes to 8 (the error is not because of indexing temp):
% t(n+1) = t(n) + altitude*lapse rate
for i = 1:7
j = i+1;
% when i is 7, j is 8
% trying to get altitude(8) and lapse_rate(8) gives you the error:
temp(j) = temp(i)+altitude(j)*lapse_rate(j);
end
Index exceeds the number of array elements. Index must not exceed 7.
temp
Maybe you mean to do this:
% t(n+1) = t(n) + altitude*lapse rate
for i = 1:7
j = i+1;
temp(j) = temp(i)+altitude(i)*lapse_rate(i);
end

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Logical 的更多信息

产品

版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by