Sum if multiple conditions satisfied across vectors

1 visualización (últimos 30 días)
Mario Bernasconi
Mario Bernasconi el 2 de Sept. de 2019
Editada: Andrei Bobrov el 2 de Sept. de 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

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 2 de Sept. de 2019
Editada: Andrei Bobrov el 2 de Sept. de 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);

Más respuestas (0)

Categorías

Más información sobre Gamma Functions en Help Center y File Exchange.

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by