PinkPanther
PinkPanther

Reputation: 29

Average in Matlab

I have a large data set, 730 values all in a single column (i.e. 730 rows). I want to split the data into groups of 24, except for the last group which will only have 10 values (since 730 is not divisible by 24).

I want to find the average of each set of 24 values, is there an easy way to do this in Matlab?

Upvotes: 2

Views: 1444

Answers (3)

Pursuit
Pursuit

Reputation: 12345

Given a vector x, for example:

>> x = [11 4 3 3 4 22 4 5 32 3 53 23 5 4 6 4 452 ]';

And some batch size (24 in your case, 5 for this toy example)

>> batchSize = 5;

Start by preallocating a matrix of NaNs. (This makes handling the odd size case at the end easier)

>> preAverage = nan(batchSize,ceil(length(x)/batchSize))
preAverage =
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN

Then place your values from x into the new matrix. (This is set up to use the column-first indexing)

>> preAverage(1:length(x)) = x;
preAverage =
    11    22    53     4
     4     4    23   452
     3     5     5   NaN
     3    32     4   NaN
     4     3     6   NaN

Then use nanmean to take the average, ignoring NaN values;

>> batchedAvgValues = nanmean(preAverage)
batchedAvgValues =
        5         13.2         18.2          228

Upvotes: 2

ymihere
ymihere

Reputation: 381

If you are looking for a moving average of every 24 rows you should use filter:

y = filter(ones(24,1), 24, x)

or

y = filter(ones(24,1)./24, 1, x)

Upvotes: 1

mushroom
mushroom

Reputation: 6281

I'm not sure exactly what you are trying to do.

Matlab has a built in mean function that can take the average of your column.

You can select different parts of a column using array splicing notation.

For example, if your column is named xs:

mean(xs(1:24))

will get the mean (average) of the first 24 values of xs.

Upvotes: 0

Related Questions