How to fix line that exceeds number of array elements(1)

1 次查看(过去 30 天)
file = readmatrix('CO2.xlsx'); % given file
year = file(:,1);
month = file(:,2);
levelCO2 = file(:,3);
crctCO2 = file(:,4);
i = 1;
for x = [1959:2018] % years to be evaluated
for m = [1:12] % all 12 months
b = year == x & month == m;
avgCO2(i) = mean(file(b(i),4)); % mean CO2 levels from 1959-2018
prct_inc(i+1) = ((avgCO2(i+1)-avgCO2(i))/avgCO2(i))*100; %equation for year-to-year percent increase of CO2 levels
Time2(i) = x + m/12;
i = i + 1;
end
end
Index exceeds the number of array elements (1).
Error in (line 34)
prct_inc(i+1) = ((avgCO2(i+1)-avgCO2(i))/avgCO2(i))*100;
How do I fix this?

采纳的回答

Cris LaPierre
Cris LaPierre 2021-1-10
The error is with avgCO2(i+1). The value at i+1 has not been defined yet, hence the error.
You could try defining a value for avgCO2(1) before your nested for loops (perhaps it's 0), then start your index counter at i=2. Rewrite your formula to look backwards instead of forwards.
prct_inc(i) = ((avgCO2(i)-avgCO2(i-1))/avgCO2(i-1))*100;

更多回答(1 个)

Walter Roberson
Walter Roberson 2021-1-10
You use the average CO2 for the year after the current one, before you have stored anything there.
b = year == x & month == m;
avgCO2(i) = mean(file(b(i),4)); % mean CO2 levels from 1959-2018
What is your intention about what you are taking the mean of? mean over the entire year would require mean(levelC02(year==x)) and should be done before the month loop.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by