Cumulative Sum for Column of Ones and Zeros

조회 수: 3 (최근 30일)
Kevin Zhang
Kevin Zhang 2017년 12월 5일
댓글: Ronni Isham 2019년 1월 2일
I have a column of ones and zeros, and I want to create a second column that takes a cumulative sum of the ones. When a 0 is encountered, the cumulative sum should go to zero, and repeat. For example,
A = [1 1 1 1 1 0 0 1 1]
B = [1 2 3 4 5 0 0 1 2]
Basically, I would like to count the number of consecutive zeros in the first column vector until a zero is reached, and then restart at the next group of ones. I need to output this as a column vector. I have tried using a for loop, but it takes minutes to calculate only a few rows and begins to return zeros after a few rows. Code is below (please excuse the inefficient way I have initialized the vectors):
T1 = [1:43801]'
Tdecl = zeros(size(T1));
UM = randi([0 1],43801,1)
for i = 1:43801
if UM(i)==1
Tdecl(i) = Tdecl(i)+1
else
Tdecl(i) = 0
end
end
  댓글 수: 1
Jos (10584)
Jos (10584) 2017년 12월 5일
You also need to take the previous element into account
if UM(1) == 1, Tdecl(1) = 1 ; end
for i=2:43801
if UM(i)==1,
Tdecl(i) = Tdecl(i-1) + 1 ;
end
end
but note that runindex (see my answer below) is much faster.

댓글을 달려면 로그인하십시오.

채택된 답변

Jos (10584)
Jos (10584) 2017년 12월 5일
A perfect job for runindex:
A = [0 1 1 1 0 0 1 1 1 1 0 0 0 1 1 1 1 1 1 0]
B = runindex(A)
B(A==0) = 0
My function RUNINDEX can be downloaded from the File Exhchange:
The code is short and very fast, using a nice index trick and cumsum.
  댓글 수: 2
Kevin Zhang
Kevin Zhang 2017년 12월 7일
Hi Jos,
Thanks for the reply, I managed to figure this out myself - I neglected to use semicolons in my loop and it was causing huge issues.
Ronni Isham
Ronni Isham 2019년 1월 2일
Could you please upload your final solution?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by