Function similar to MS Excel "subtotal"?

조회 수: 13 (최근 30일)
George
George 2011년 11월 2일
I have a 150x2 matrix in which the first column contains numbers that can be considered 'grouping variables' and the second column contains values associated with those grouping variables. So a small 5x2 version would look like this
1 23
1 29
1 43
2 38
2 22
I'd like to average the values associated with each grouping variable. So the above example would yield an average of 31.67 (for variable 1) and 30 (for variable 2). In Excel this can be achieved using Data --> "Subtotals". Does anybody know of a similar function or method to achieve this in Matlab?
Thanks

답변 (3개)

Titus Edelhofer
Titus Edelhofer 2011년 11월 2일
Hi George,
I don't know a single function, but the functionality is not difficult to achieve:
x = [1 23; 1 29; 1 43; 2 38; 2 22]
% find the different indices:
id = unique(x(:,1));
subTotals = zeros(size(id));
for i=1:numel(id)
subTotals(i) = mean(x(id==id(i), 2));
end
Titus

George
George 2011년 11월 2일
Hi Titus, Thanks for the quick reply. The code doesn't quite work because 'id' needs to be the indices of the unique values. Your code got me 95% there though, so with slight modification I've got it working.
x = [1 23; 1 29; 1 43; 2 38; 2 22]
% find the different indices:
[vals vec id] = unique(x(:,1));
subTotals = zeros(size(vals));
for i=1:numel(id)
subTotals(i) = mean(x(id==id(i), 2));
end
Thanks again!
  댓글 수: 1
Titus Edelhofer
Titus Edelhofer 2011년 11월 3일
Hi George,
yes of course! My code accidently worked because for the example vals and id are the same ...
Titus

댓글을 달려면 로그인하십시오.


Kelly Kearney
Kelly Kearney 2011년 11월 2일
If your grouping variable includes only integers, then
x = [...
1 23
1 29
1 43
2 38
2 22];
subtot = accumarray(x(:,1), x(:,2), [], @mean);

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by