Sum if multiple conditions satisfied across vectors

1 回表示 (過去 30 日間)
Mario Bernasconi
Mario Bernasconi 2019 年 9 月 2 日
編集済み: Andrei Bobrov 2019 年 9 月 2 日
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

採用された回答

Andrei Bobrov
Andrei Bobrov 2019 年 9 月 2 日
編集済み: Andrei Bobrov 2019 年 9 月 2 日
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 件)

カテゴリ

Help Center および File ExchangeGamma Functions についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by