Search code examples
matlabloopsmedian

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?


Solution

  • 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