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

1 vue (au cours des 30 derniers jours)
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

Réponse acceptée

Wan Ji
Wan Ji le 31 Août 2021
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));

Plus de réponses (1)

Chunru
Chunru le 31 Août 2021
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

Catégories

En savoir plus sur Symbolic Math Toolbox dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by