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