Performing stats on subsections of a matrix

2 views (last 30 days)
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

Accepted Answer

Sven
Sven on 9 Apr 2014
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.
  1 Comment
Swisslog
Swisslog on 9 Apr 2014
Edited: Swisslog on 9 Apr 2014
This is great, thanks for taking the time to look at this :-)

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 9 Apr 2014
If you have the Image Processing Toolbox , this is a trivial 2 line piece of code:
measurements = regionprops(a(1,:), a(2,:), 'MeanIntensity');
theMeans = [measurements.MeanIntensity] % Extract from structure into array.
This assumes the numbers are integers in the first row, like you have shown. The first line of code assumes the first row of "a" are labels that identify the individual regions. It passes that into regionprops() and tells it to measure the mean intensity of each region where the region values are given in the second row, which is the second argument to regionprops. If the first row is not integers , then you're in trouble and you'll need to look over the FAQ: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!