Cumulative sum with conditions
14 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
yp78
am 3 Okt. 2018
Bearbeitet: Bruno Luong
am 4 Okt. 2018
I am counting a number of 1's in an array.
But I want to count the cumulative sums only when the number of 1's are followed by a sequence of zeros.
% For instance,
h1=[1 0 0]
h2=[1 1 0]
h3=[1 1 1]
h4=[0 0 1]
h5=[0 1 0].
I want to count the cumulative sums (S) of those arrays as follows.
% The ideal outputs are:
S1= 1
S2= 2
S3= 0
S4= 0
S5= 0
since h2: h4 do not meet the condition of 1's followed by 0's.
I would truly appreciate if any one could advise me an effective way of programming the conditional sums.
1 Kommentar
Rik
am 3 Okt. 2018
So you have these as numbered variables? Then you should really have them in a single array. Also, I don't understand the rules here. Are we meant to look row by row? If so, doesn't the 5th row count as well (as there is a 0 after the 1)?
Akzeptierte Antwort
Bruno Luong
am 4 Okt. 2018
Bearbeitet: Bruno Luong
am 4 Okt. 2018
Change the last line to make it can handle with single row:
m = size(h,1);
d = diff(h,1,2);
[r,c] = find(d==-1);
b = sum(abs(d),2)==1;
s = accumarray(r(:),c(:),[m 1]).*double(b)
This because find() rotates the result for row input array.
1 Kommentar
Weitere Antworten (4)
Sean de Wolski
am 3 Okt. 2018
h = [1 0 0;
1 1 0;
0 0 1;
1 1 1;
0 1 0];
s = sum(h, 2).*~h(:,end)
requiring the last element to be zero. This wouldn't work for [1 0 1] but I don't know what you'd want for that.
0 Kommentare
yp78
am 3 Okt. 2018
Bearbeitet: yp78
am 3 Okt. 2018
2 Kommentare
Sean de Wolski
am 3 Okt. 2018
In that case what I have above should work. It returns the sum and requires that the last element be a zero. If the last element is non-zero, it returns a zero.
With [1 0 1] it would say zero because the last element is not a zero.
Bruno Luong
am 4 Okt. 2018
Bearbeitet: Bruno Luong
am 4 Okt. 2018
h = [1 0 0;
1 1 0;
0 0 1;
1 1 1;
0 1 0];
[a,c] = max(1-h,[],2);
s = (c-1).*a.*h(:,1)
3 Kommentare
Bruno Luong
am 4 Okt. 2018
Bearbeitet: Bruno Luong
am 4 Okt. 2018
Can you explain why it returns 0? Still not clear the rule...
Do you only count only if the row is composing a sequence of 1s followed by a sequence of 0s (of at least one 0)?
Bruno Luong
am 4 Okt. 2018
Bearbeitet: Bruno Luong
am 4 Okt. 2018
m = size(h,1);
d = diff(h,1,2);
[r,c] = find(d==-1);
b = sum(abs(d),2)==1;
s = accumarray(r(:),c(:),[m 1]).*double(b)
4 Kommentare
Siehe auch
Kategorien
Mehr zu Hypothesis Tests finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!