how to average precipitation for each month (i.e. average all data from january for the entire data set) in matlab

Suppose you have a dataset with precipitation data in a vector precipitation, and a corresponding vector months indicating the month of each data point. You can compute the average precipitation for each month using the accumarray function. Here's how you can do it:

main.m
% Example precipitation data
precipitation = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50];
% Example month data
months = [1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12];

% Compute the average precipitation for each month
monthly_averages = accumarray(months', precipitation', [], @mean)

% monthly_averages should be:
%    22    23    24    25    26    27    28    29    30    31    32    33
580 chars
11 lines

In this code, accumarray takes three inputs:

  1. months' (note the transpose) is the vector of subscripts that accumarray uses to group the precipitation data by month.
  2. precipitation' (note the transpose again) is the vector of values to be averaged.
  3. [] tells accumarray to create a new output array, one element for each month.
  4. @mean is a function handle that tells accumarray to compute the mean of each group.

The resulting monthly_averages variable should be a row vector with 12 elements, one for each month. The first element will be the average precipitation for January, the second element will be the average precipitation for February, and so on.

related categories

gistlibby LogSnag