MATLAB Answers

Sum elements of corresponding equal elements

1 ビュー (過去 30 日間)
tandemuse
tandemuse 2020 年 10 月 17 日
編集済み: tandemuse 2020 年 10 月 18 日
for i=1:length(C)-1
for j=i+1:length(C)
if C(i,1)==C(j,1)
C(i,3)=C(i,2)+C(j,2);
end
end
end
C is a 36x2 matrix and I want to do the following: I want to check the 1st column for equal values. Let's say we find the (5,1), the (18,1) and the (21,1) elements in the column to be equal. Then I would like to sum the corresponding (5,2)+(18,2)+(21,2) elements in the second column and make each sum appear in the corresponding 3rd column, i.e. in the positiions (5,3), (18,3) and (21,3).
The above seems to almost work. I think it is because after it has searched and found an equality, it gives up on a 2nd potential equality and that's my problem!

  0 件のコメント

サインインしてコメントする。

採用された回答

Akira Agata
Akira Agata 2020 年 10 月 17 日
How about the following solution?
% Create sample 36-by-3 array C
rng('default'); % for reproducability
C = [randi(10,36,1),rand(36,1),nan(36,1)]; % Sample array C
% Apply findgroups and splitapply functions to calcurate sum for each group
[group,ID] = findgroups(C(:,1));
val = splitapply(@sum,C(:,2),group);
% Arrange the result to the 3rd column of C
[~,loc] = ismember(C(:,1),ID);
C(:,3) = val(loc);

  4 件のコメント

表示 1 件の古いコメント
tandemuse
tandemuse 2020 年 10 月 18 日
I can't really tell why it doesn't work for this particular case.
I've noticed however that if the values are integers instead of decimals it does work.
I mean that instead of having 0.1 0.2 etc you have 1 2 etc.
Maybe there is some problem with findgroups and decimals?
Walter Roberson
Walter Roberson 2020 年 10 月 18 日
Reminder that findgroups() uses exact comparisons .
>> [C(4),C(14),C(4)-C(14)]
ans =
0.3 0.3 -5.55111512312578e-17
You will need to use something like
[ID, ~, group] = uniquetol(C(:,1));
tandemuse
tandemuse 2020 年 10 月 18 日
YES! Thank you!
That is EXACTLY it. For future reference to others who might face the same problem, what is happening is that the command findgroups views the two "0.3" as distinct elements and doesn't put them in the same group.
The way I solved it is that I simply rounded the 1st column of C before the operation.
Here is the code:
C(:,1)=round(C(:,1),2);
groups = findgroups(C(:,1));
groups_sum = splitapply(@sum,C(:,2),groups);
pz=[unique(C(:,1)) groups_sum]

サインインしてコメントする。

その他の回答 (0 件)

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by