sophie
sophie

Reputation: 115

how to get a single column vector from 2 consecutive for loop in matlab?

I m trying to get a single column vector that is the monthly averages of my X values for each year (10 years). I am using 2 consecutive for loop - and perhaps a simpler code will get me the monthly average for each year...?

Ok - so here is my matlab code:

   X = values;
   t = time values;
   timevec = datevec(t);
   years = timevec(:,1) ;
   yy = unique(years);
   month = timevec(:,2);
   mm = unique(month);

   for iyear = 1:length(yy);
         fy = find(years==yy(iyear));
         ym = month(fy);

        for imonth = 1:length(mm);
                fm = find(ym==mm(imonth));
                Xmean(imonth,iyear) = mean(X(fm));
         end
    end

However, I would like to get a single column vector and not a matrix of size (length(imonth),length(iyear)) - so something like:

     Xmean(:) of size ((length(imonth*iyear)), 1)

does this make sense? I would be grateful if you could help me in this problem.

Cheers, S.

Upvotes: 0

Views: 89

Answers (1)

Shai
Shai

Reputation: 114876

You should use accumarray with custom function @mean.

[~,~,yi] = unique( timevec(:,1) ); % year index, using unique to start with one.
mi = timevec(:,2); % month index
subs = 12*(yi-1) + mi; % month-year into a single vector index
Xmean = accumarray( subs(:), X(:), [], @mean );
Xmean(isnan(Xmean)) = 0; % remove mean([]) results.

Upvotes: 1

Related Questions