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
0 个评论
采纳的回答
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
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 ))
%'1_A' 25-50 = 25.5913
x = sum(pct(strcmp(ID, '1_A') & pct>25 & pct<=50))
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!