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 Commento

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).

Accedi per commentare.

 Risposta accettata

Voss
Voss il 3 Apr 2022
Modificato: Voss il 3 Apr 2022
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

Più risposte (0)

Prodotti

Release

R2022a

Richiesto:

il 3 Apr 2022

Modificato:

il 3 Apr 2022

Community Treasure Hunt

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

Start Hunting!

Translated by