Sum in groups of ones and zeros
조회 수: 1 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (1개)
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)
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!