## Sum if multiple conditions satisfied across vectors

### Mario Bernasconi (view profile)

on 2 Sep 2019
Latest activity Edited by Andrei Bobrov

on 2 Sep 2019

### Andrei Bobrov (view profile)

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

R2018a

### Andrei Bobrov (view profile)

on 2 Sep 2019
Edited by Andrei Bobrov

### Andrei Bobrov (view profile)

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);