MATLAB Answers

How to sum the values when they are bigger than 25, 50, 75, (conditional) and they are from the same group?

조회 수: 1(최근 30일)
DulceEien
DulceEien 2021년 8월 31일
댓글: DulceEien 2021년 8월 31일
ID = ['1_A' ; '1_A'; '1_A'; '2_B'; '2_B'; '3_C'; '3_C'; '3_C'; '3_C'] ;
pct = [6.3875; 5.8813; 25.5219; 54.5052; 5.3287; 7.7387; 6.9002; 24.0538; 29.8939]
I want to sum up the values that are under 25, and then the values greater than 50 but only from the same "group"
for example:
'1_A' > 25 = 12.2688
'1_A' > 50 = 25.5913
I was thinking in a conditional like this
uID = unique(ID)
B = ID;
for i=1:length(uA)
idx = find(strcmp(ID, uID(i)));
for j=1:length(idx)
if ID <= 25
SUM
elseif ID >25 && ID <= 50
SUM
end
end
end

채택된 답변

Wan Ji
Wan Ji 2021년 8월 31일
That's quite simple, you don't need to compare them
clc;clear
ID = ['1_A' ; '1_A'; '1_A'; '2_B'; '2_B'; '3_C'; '3_C'; '3_C'; '3_C'] ;
[uID, ia, ic] = unique(ID,'rows');
pct = [6.3875; 5.8813; 25.5219; 54.5052; 5.3287; 7.7387; 6.9002; 24.0538; 29.8939];
sum_below_25 = accumarray(ic, pct.*(pct<=25));
sum_gt_25_below_50 = accumarray(ic, pct.*(pct>25&pct<=50));
sum_gt_50 = accumarray(ic, pct.*(pct>50));

추가 답변(1개)

Chunru
Chunru 2021년 8월 31일
ID = {'1_A' ; '1_A'; '1_A'; '2_B'; '2_B'; '3_C'; '3_C'; '3_C'; '3_C'};
pct = [6.3875; 5.8813; 25.5219; 54.5052; 5.3287; 7.7387; 6.9002; 24.0538; 29.8939];
%'1_A' <= 25 = 12.2688
x = sum(pct(strcmp(ID, '1_A') & pct<=25 ))
x = 12.2688
%'1_A' 25-50 = 25.5913
x = sum(pct(strcmp(ID, '1_A') & pct>25 & pct<=50))
x = 25.5219

Community Treasure Hunt

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

Start Hunting!

Translated by