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

errorexceedsindex

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?

Best Answer

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;