Sum in groups of ones and zeros

1 view (last 30 days)
Gina Torres
Gina Torres on 18 Jul 2018
Answered: Paolo on 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

Answers (1)

Paolo
Paolo on 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)

Categories

Find more on Elementary Math in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!