Change accumarray mean to median

I've cobbled together an loop statement that calculates the mean value for each column in an array based on the cluster ID tag in the last column of the array. It works great but I need to calculate the median, not the mean, and I can not for the life of me figure problem out. The code I'm using is:
%Produce the mean value for each cluster
[d1,d2] = size(ClusteredData);
[unique_val,~,ind_unique] = unique(ClusteredData(:,d2));
sz = [size(unique_val,1),1];
N = accumarray(ind_unique,1,sz); % number of measurements
%set the sizes for the array
ClustMeans = zeros(Nu,1); %array = number of cells by 1 column
mean_a = zeros(1,d2);
for n = 1:d2
mean_a = accumarray(ind_unique,ClusteredData(:,n),sz)./ N; % average
ClustMeans = horzcat(ClustMeans, mean_a);
end
ClusteredData is the output from a pdist function.
Thanks :)

 Accepted Answer

You can specify the accumulating function in accumarray. If you do that for mean, you don't even need to calculate your N:
mean_a = accumarray(ind_unique, ClusteredData(:, n), sz, @mean); %no need for N
It is trivial to replace mean by median:
median_a = accumarray(ind_unique, ClusteredData(:, n), sz, @median);

2 Comments

Hi Guillaume,
I knew it would be simple. Thanks for the help!!!
By the way you can eliminate the loop entirely with:
subs = [repmat(ind_unique, d2, 1), repelem(1:d2, numel(ind_unique))'];
clustMeans = accumarray(subs, ClusteredData(:), [], @mean); %or @median

Sign in to comment.

More Answers (0)

Categories

Asked:

on 13 Apr 2016

Commented:

on 13 Apr 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!