How do I eliminate index error in sum function.

I have imported a csv file into matlab and want to take the sum of every 48 lines. I have the following lines. When I sum the values I get an error "Index exceeds matrix dimensions". I tried increasing the size of the matrix which alleviated the problem, but I no longer was able to get the correct sum. I also have not define sum or nan sum as a variable in previous lines
clear i j nansum sum
if for i = 1:48:length(dtkp)
h2o_daily(j) = nansum(h2o_mm(i:i+47)); %refer to something outside of matrix?
co2_daily(j) = nansum(co2_mgm2(i:i+47));
h2o_daily_mn(j) = nanmean(h2o_mm(i:i+47)); %mean ignoring nan values
co2_daily_mn(j) = nanmean(co2_mgm2(i:i+47));
dt_daily(j) = min(dtkp(i:i+1));
tallydaily_nanh2o(j) = sum(isnan(h2o_mm(i:i+47)));%count number of nan vales
tallydaily_nanco2(j) = sum(isnan(co2_mgm2(i:i+47)));
j = j+1;
end

 Accepted Answer

clear i j nansum sum
if for i = 1:48:length(dtkp)
h2o_daily(j) = nansum(h2o_...
You've cleared j but reference it before defining it...
j=0;
if for i = 1:48:length(dtkp)
j=j+1;
h2o_daily(j) = nansum(h2o_...
If I understand your wish, using Matlab internal storage order allows for such sums or other functions to be computed more easily--
nAvg=48; % number of which to average, etc., ...
nVar=2; % number of variables (columns) in data array
data=[h2o_mm(:) co2_mgm2(:)]; % put data into one array by column
data=reshape(data,nAvg,[]); % break at 48-line intervals
stat=nanmean(data); % compute by column (over nAvg values)
stat=reshape(stat,length(stat)/nVar),[]); % reshape back to the nVar columns
Adjust for the other desired statistics...

4 Comments

Thanks, this solved the issue.
However, in the data files - I do not always have a number of rows divisible by 48. What would I add to take each window of 48 and the last window be a remainder?
Use modulo arithmetic on the computation of number of rows...
fix(length(data)/nAvg)
is the number of full segments;
mod(length(data),nAvg)
is size of the remainder.
How to treat is your call...average over that size, ignore, ...
bikefan
bikefan on 19 Feb 2015
Edited: bikefan on 20 Feb 2015
Thanks again - How do I set the average of each parameter as a variable similar to the previous code?
I recommend against making a proliferation of variables in Matlab; build an array that holds the statistics and simply reference into it.
Or, if you're adamant you must have a name, look at the dataset or structures with dynamic names. This is much more programming-friendly than keep a bunch of separate variables.
You've already seen one advantage of the use of arrays--you can get the same computation for all of them "free" for the cost of one. This is a feature not to be underestimated in its importance as you begin with Matlab.

Sign in to comment.

More Answers (0)

Asked:

on 19 Feb 2015

Commented:

dpb
on 20 Feb 2015

Community Treasure Hunt

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

Start Hunting!