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

1 回表示 (過去 30 日間)
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

カテゴリ

Help Center および File ExchangeSymbolic Math Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by