Sum in groups of ones and zeros

1 次查看(过去 30 天)
Gina Torres
Gina Torres 2018-7-18
回答: Paolo 2018-7-18
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

回答(1 个)

Paolo
Paolo 2018-7-18
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)

类别

Help CenterFile Exchange 中查找有关 Elementary Math 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by