count repeated sequence in an array
조회 수: 4 (최근 30일)
이전 댓글 표시
data=[0 0 0 1 1 0 0 0 0 0 0 1 1 1 1]
L = length(data)
result0 = sum (data == 0)
result1 = sum (data == 1)
ctr1 = 0;
ctr2 = 0;
for i= 1:length(data)
if data(i) == 0
ctr1 = ctr1 + 1
elseif data(i) == 1
ctr2 = ctr2 + 1
end
end
str = [ctr1 ctr2]
end
I'm struck here
I'm expecting the output as [3 4 2 6] and separate the output as low [3 6] and high [2 4]
Please use only basic commands (use only loop)
no runlength and other complicated commands
댓글 수: 0
답변 (1개)
Awais Saeed
2021년 12월 14일
편집: Awais Saeed
2021년 12월 14일
Not so neat, but will do the work
data=[0 0 0 1 1 0 0 0 0 0 0 1 1 1 1];
zero_count = 0;
one_count = 0;
ctr1 = [];
ctr0 = [];
% loop through data
for col = 1:1:size(data,2)
% if its a 0, do the following
if(data(col) == 0)
zero_count = zero_count + 1;
% check for index out of bound
if(col+1 <= size(data,2))
% if next element is 1, stop incrementing zero_count
if(data(col+1) == 1)
ctr0 = [ctr0 zero_count]
zero_count = 0; % reset count
end
else
% if index is out of bound, inspect last element
if(data(end) == 0), ctr0 = [ctr0 zero_count],end
if(data(end) == 1), one_count = one_count + 1; ctr1 = [ctr1 one_count],end
end
else
% if its a 1, do the following
one_count = one_count + 1;
if(col+1 <= size(data,2))
if(data(col+1) == 0)
ctr1 = [ctr1 one_count]
one_count = 0; % reset count
end
else
if(data(end) == 0), zero_count = zero_count+1; ctr0 = [ctr0 zero_count],end
if(data(end) == 1), ctr1 = [ctr1 one_count],end
end
end
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!