count repeated sequence in an array

2 views (last 30 days)
Harshitha Eshwar
Harshitha Eshwar on 14 Dec 2021
Edited: Awais Saeed on 14 Dec 2021
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

Answers (1)

Awais Saeed
Awais Saeed on 14 Dec 2021
Edited: Awais Saeed on 14 Dec 2021
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
ctr0 = 3
ctr1 = 2
ctr0 = 1×2
3 6
ctr1 = 1×2
2 4

Community Treasure Hunt

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

Start Hunting!

Translated by