How to count continuous non zero elements whilst keeping the date of the first non-zero value
조회 수: 1 (최근 30일)
이전 댓글 표시
I a have a set of data in a matrix whereby the first 5 columns represent: year month day hour minute The 6th column represents a magnitude value and I want to know how can I continuously count the size of the non zero values enclosed by two zeros and return it in a 7th column in the same row as where the first non zero value is located.
In other words, I have this:
2010 1 1 0 5 0
2010 1 1 0 10 6
2010 1 1 0 15 16
2010 1 1 0 20 0
2010 1 1 0 25 12
2010 1 1 0 30 19
2010 1 1 0 35 11
2010 1 1 0 40 0
and I want this:
2010 1 1 0 5 0
2010 1 1 0 10 6 2
2010 1 1 0 15 16
2010 1 1 0 20 0
2010 1 1 0 25 12 3
2010 1 1 0 30 19
2010 1 1 0 35 11
2010 1 1 0 40 0
Many thanks!
댓글 수: 0
채택된 답변
Sergey Kasyanov
2018년 4월 6일
Hi.
It's the simplest but not the shortest code for this problem.
k=A(1,6)~=0;
for i=1:size(A,1)
if A(i,6)~=0&k==0
k=i;
elseif A(i,6)==0&k~=0
A(k,7)=i-k;
k=0;
end
end
if k~=0
A(end,7)=i-k+1;
end
댓글 수: 4
Sergey Kasyanov
2018년 4월 6일
Of course.
k=A(1,6)~=0;
for i=1:size(A,1)
if A(i,6)~=0&k==0
k=i;
elseif A(i,6)==0&k~=0
A(k,7)=i-k;
A(k,8)=max(A(k:i,6));
k=0;
end
end
if k~=0
A(k,7)=i-k+1;
A(k,8)=max(A(k:i,6))
end
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!