Sum in groups of ones and zeros

1 Ansicht (letzte 30 Tage)
Gina Torres
Gina Torres am 18 Jul. 2018
Beantwortet: Paolo am 18 Jul. 2018
Hello all,
I have two vectors. In the form:
idx=[1;1;1;1;0;0;0;1;0;1;1;0;0]
p=[0.2;0.3;1;0.89;0.35;0.25;0.74;0.98;0.25;0.24;0.15;0.75;0.125].
I want to sum the numbers corresponding to the different groups of ones and zeros. The result would be:
ans1=[2.39;0.98;0.39]
ans2=[1.34;0.25;0.875]
Thank you

Antworten (1)

Paolo
Paolo am 18 Jul. 2018
A possible solution:
For ones:
[sindx,endindx] = regexp(char(idx+'0')','1*')
indx = arrayfun(@(x,y) x:y,sindx,endindx,'un',0)
ans1 = cellfun(@(x) sum(p(x)),indx)
For zeros:
[sindx,endindx] = regexp(char(idx+'0')','0*')
indx = arrayfun(@(x,y) x:y,sindx,endindx,'un',0)
ans2 = cellfun(@(x) sum(p(x)),indx)

Kategorien

Mehr zu Elementary Math finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by