Performing stats on subsections of a matrix
조회 수: 1 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
Sven
2014년 4월 9일
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개)
Image Analyst
2014년 4월 9일
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
댓글 수: 0
참고 항목
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!