Sum matrix with repeating indices
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi! I have one matrix, A, that has one column of identifier values (with repeats and some missing numbers) and a column of values. I'd like to produce a column of all of the unique values and then another column of their sum. For example, if A is as follows, i want to produce B.
A = [1 2
1 -3
2 0
3 3
5 6
2 -4
4 0.5
7 9
7 2]
% I want to produce B
B = [1 -1
2 -4
3 3
4 0.5
5 6
7 11]
댓글 수: 0
채택된 답변
Stephen23
2022년 3월 20일
편집: Stephen23
2022년 3월 21일
A simple MATLAB approach:
A = [1,2;1,-3;2,0;3,3;5,6;2,-4;4,0.5;7,9;7,2]
[G,U] = findgroups(A(:,1));
M = [U,accumarray(G,A(:,2))]
댓글 수: 2
Stephen23
2022년 3월 20일
편집: Stephen23
2022년 3월 20일
"What is your definition of simple?"
Hmmm... off the top of my head, something like this: simple code uses functions and syntax whose intent is clear, making understanding the code intent easier to understand when it is read through by regular users of that language, and generally making the code more efficient. Simple code utilizes existing routines effectively (i.e. does not reinvent the wheel), and only specializes sufficiently to solve the task at hand.
"Where can I find a reference to this?"
When I search for "simple code" using a major internet search engine it returned 2690000 results. I read a few of them just now, this one I think gives a reasonable summary (it also happens to match very closely with my own definition of "simple" given above):
The concept of abstraction seems to be very commonly associated with simple code:
I.e. understanding the underlying model and knowing how that can be best represented in code.
"How is it measured?"
I can think of several ways to measure it:
- syntax metrics (e.g. cyclomatic complexity, number of operations, etc)
- use of existing routines and paradigms as much as reasonable (related to abstraction)
- use of methods that are generalized as much as reasonable, e.g. type/data agnostic
- metrics related to maintainability, readability, etc.
Note that simpler does not mean shorter.
Steven Lord
2022년 3월 21일
Instead of using findgroups and accumarray I would probably use groupsummary.
A = [1,2;1,-3;2,0;3,3;5,6;2,-4;4,0.5;7,9;7,2];
[values, groups] = groupsummary(A(:, 2), A(:, 1), @sum);
results = [groups, values]
추가 답변 (1개)
Voss
2022년 3월 20일
편집: Voss
2022년 3월 20일
One perfectly valid MATLAB approach:
A = [1 2
1 -3
2 0
3 3
5 6
2 -4
4 0.5
7 9
7 2];
[uA,~,jj] = unique(A(:,1));
n_uA = numel(uA);
B = [uA zeros(n_uA,1)];
for ii = 1:n_uA
B(ii,2) = sum(A(jj == ii,2));
end
disp(B)
% % I want to produce B
% B = [1 -1
% 2 -4
% 3 3
% 4 0.5
% 5 6
% 7 11];
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!