Sum if multiple conditions satisfied across vectors
1 view (last 30 days)
Show older comments
Mario Bernasconi
on 2 Sep 2019
Edited: Andrei Bobrov
on 2 Sep 2019
Hi all,
I have three vector that represent in which market a product is, to which group of product it belongs within the market, and the share of market. Let's say I have 2 markets with 3 products in each market and 2 group of products per market:
MKT = [1 ; 1 ; 1 ; 2 ; 2 ; 2]
GROUP = [1 ; 1 ; 2 ; 1 ; 2 ; 2]
SHARE = [0.2 ; 0.3 ; 0.5 ; 0.6 ; 0.1 ; 0.3]
I want to create a new vector that tells me for each product the share of the group to which it belongs within its market. The result should be:
SHARE_GROUP = [0.5 ; 0.5 ; 0.5 ; 0.6 ; 0.4 ; 0.4]
I've tried using accumarray but wasn't able to solve this.
Thanks
0 Comments
Accepted Answer
Andrei Bobrov
on 2 Sep 2019
Edited: Andrei Bobrov
on 2 Sep 2019
MKT = [1 ; 1 ; 1 ; 2 ; 2 ; 2];
GROUP = [1 ; 1 ; 2 ; 1 ; 2 ; 2];
SHARE = [0.2 ; 0.3 ; 0.5 ; 0.6 ; 0.1 ; 0.3];
T = table(MKT,GROUP,SHARE);
Share_group = varfun(@sum,T,'GroupingVariables',{'MKT','GROUP'});
[~,ii] = ismember(T(:,{'MKT','GROUP'}),Share_group(:,{'MKT','GROUP'}),'rows');
T.SHARE_GROUP = Share_group.sum_SHARE(ii);
or
[~,~,c] = unique([MKT,GROUP],'rows');
group_share = accumarray(c,SHARE,[],@sum);
SHARE_GROUP = group_share(c);
0 Comments
More Answers (0)
See Also
Categories
Find more on Gamma Functions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!