MATLAB: Change accumarray mean to median

accumarrayarraymeanmedian

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 🙂

Best 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);