MATLAB: Performing stats on subsections of a matrix

MATLABmatrix manipulation; mean

I have a two row matrix and I want to be able to extract some metrics (i.e. mean, median std) from numbers in the 2nd row based on associated values in the first row. So if I had:
a=[1 1 1 2 2 4;
3 5 4 7 2 5]
I'd like to compute the mean of row 2 associated with different values in row 1, so I'd want the mean of 3 5 and 4, mean of 7 and 2, and mean of 5. These metrics would then be output to a new 2 row matrix:
i.e. [1 2 4; 4 4.5 5]
Any pointers would be appreciated

Best Answer

Hi Swisslog,
Try this:
a = [1 1 1 2 2 4; 3 5 4 7 2 5];
% Pack your matrix contents into a cell array
[unqA,~,grps] = unique(a(1,:))
aCell = cell(size(unqA));
for i = 1:max(grps)
mask = grps==i;
aCell{i} = a(2,mask);
end
% Calculate statistics
cellfun(@mean, aCell)
cellfun(@median, aCell)
cellfun(@std, aCell)
What I've done above is to put your matrix into a cell array. Each element of the cell contains the values associated with that "lookup" (the contents of unqA). This then allows you to use the cellfun function which, as you can see, gets you exactly what you were looking for as a final output.
Did that help you out? There's a one-line way to make the aCell variable (using accumarray()), but the loop I've shown is a little easier to grasp.
Thanks, Sven.