group sum with matrix

With below matrix, I would like to have a sum of the third column and a sum of the fourth column by groups that are the combination of the first and second column.
1 1 1 0.5
1 1 2 0.5
1 1 3 0.5
1 1 4 0.5
1 1 5 0.5
1 2 6 0.5
1 2 7 0.5
1 2 8 0.5
1 2 8 0.5
1 2 9 0.5
2 1 0.1 2
2 1 0.2 2
2 1 0.3 2
2 1 0.4 2
2 1 0.5 2
2 2 0.6 2
2 2 0.7 2
2 2 0.8 2
2 2 0.8 2
2 2 0.9 2
So, here is what I am desiring for
1 1 15 2.5
1 2 38 2.5
2 1 1.5 10
2 2 3.8 10

1 Comment

This is very similar to the question you asked yesterday. The same method can be used for both, so please read and learn from the answers you're given as otherwise people will start ignoring your questions.

Sign in to comment.

Answers (1)

The following code will summarise the table as described in question
groups = findgroups(A(:, 1), A(:, 2));
[~, uniqueGroupsIndex] = unique(groups);
uniqueGroups = A(uniqueGroupsIndex, 1:2);
s1 = splitapply(@(x) sum(x), A(:, 3:end), findgroups(A(:, 1), A(:, 2)) );
final = [uniqueGroups s1];

4 Comments

You can simplify the whole
groups = findgroups(A(:, 1), A(:, 2));
[~, uniqueGroupsIndex] = unique(groups);
uniqueGroups = A(uniqueGroupsIndex, 1:2);
with
[uniqeGroups, ~, groups] = unique(A(:, [1 2]), 'rows')
and there's no need to call findgroups in the splitapply call. You've already calculated the result as group, so:
s1 = splitapply(@(x) sum(x), A(:, 3:end), groups);
Note: In my answer to the near identical question, I use accumarray instead of splitapply. The two are more or less equivalent, with splitapply being newer and slightly more versatile (needed here but not in the other question) but generally a lot slower than accumarray.
@Guillaume Thanks for further elaborating. Properly using unique() can really make code simple sometimes.
@Guillaume Thank you. I was trying to use accumarray for this but it did not work. I did not know the slpitapply. Btw, for S1, If I want to have the output with same number row with original data A. How I should do it? When I tried
s1(groups)
It does not work. Thank you in advance.
I got it. It was pretty simple. Thank you.

Sign in to comment.

Categories

Asked:

on 1 May 2018

Commented:

on 1 May 2018

Community Treasure Hunt

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

Start Hunting!