Taking medians from within a column vector using MATLAB

I have two column vectors.

The first column vector is several thousand data points long, and I need to take the median from the first forty items, and then the median from the next forty, and so on.

The second column vector contains a group ID (from 1 to 3).

My goal is to end up with a bunch of median calculations and to have them sorted by group. I am very unsure of how to go about this in MATLAB.

Upvotes: 0

Views: 122

Answers (3)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

Here's a bit of code to get you started.

If you have both vectors in one named variable, and the number of columns is exactly divisible by 40, do this:

% column 1 = data, column 2 = groupID
test = rand(400,2);

% compute medians of data
medians = median( reshape(test(:,1), 40,[]) );

% make each entry correspond to the correct groupID
medians = repmat(medians, 40,1);
medians = medians(:);

If your data is NOT exactly divisible by 40, use a simple loop:

N = 40;

test = rand(10*N+4,2);

n = 1;
medians = zeros( ceil(size(test,1)/N), 1 );
for ii = 1:numel(medians)
    if n+N-1 > size(test,1)
        medians(ii) = median(test(n:end,1));
    else
        medians(ii) = median(test(n:n+N-1,1));
    end
    n = n+N;
end

and replicate as before if necessary.

Adjustments to this code for if you have the groupID in a separate variable, or how to sort these things according to groupID, are pretty straightforward.

Upvotes: 2

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

Getting the group is fairly easy:

groupIDvec = groupID(1:40:end);% A vector with group numbers

Finding the median of each group can be done as @Oli described, by using reshape

medianmat = reshape(datavector,40,[]); 
medianvec = median(medianmat); 

Now you just need to sort them:

[groupIdvec,idx] = sort(groupIDvec)

And here is your sorted result, where groupIDvec indicates in which group each value is:

result = medianvec(idx);

I do not have Matlab at hand so it may contain errors, but it should be about ok.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272517

reshape your vector into a 40xN matrix, and then use median to take the median of each column.

Upvotes: 3

Related Questions