Rollo99
Rollo99

Reputation: 1613

how to take the median every 12 monhts in MATLAB?

I have the following dataframe:

x = randn(216,1)

How I can get the median every 12 months/rows?

I would need to get a 18x1 vector.

Can anyone help me?

Upvotes: 0

Views: 57

Answers (2)

MichaelTr7
MichaelTr7

Reputation: 4767

Using a For-Loop and Incrmeneting By Chunk Size, 12

Grabs a chunk of the array one chunk at a time on each iteration. The partition of the array that is retrieved ranges from the value Median_Index and 11 following indices following it.

x = randn(216,1);
Median_Values = zeros(18,1);

Index = 1;
for Median_Index = 1: +12: 216

    Chunk = x(Median_Index: Median_Index + 11);
    Median_Values(Index) = median(Chunk,'all');
    Index = Index + 1;
end

Note: all can be removed since we are dealing with a vector (specifically since it's 1D) Thanks to @Luis Mendo for the suggestion and compatibility tips.

Ran using MATLAB R2019b

Upvotes: 3

Luis Mendo
Luis Mendo

Reputation: 112729

You only need to reshape your data as a 12-column matrix, and then use median with a second argument to specify that you want it to operate along the first dimension, that is, compute the median of each column:

x = randn(216, 1); % example data
N = 12; % chunk size
result = median(reshape(x, N, []), 1);

Upvotes: 3

Related Questions