How to find the number of repeating sequence in an array?
Afficher commentaires plus anciens
A sequence is
011011011001111011111001001011001011011001101001011011001111111.
I'm looking for a sequence of 111 from the above. But the scanning can be done by considering the first three elements(011) and then next three elements(011) and so on.
That is
011,011,011,001,111,011,111,001,001,011,001,011,011,001,101,001,011,011,001,111,111.
Thus four occurrences. Similarly for 1111. Appreciate help.
Réponse acceptée
Plus de réponses (1)
Image Analyst
le 5 Mar 2017
You could use histogram():
% Define data.
s = '011011011001111011111001001011001011011001101001011011001111111';
% Figure out how many times each 3 character string shows up.
s3 = reshape(s, 3, [])'
n3 = arrayfun(@str2double, s3)
numbers = n3(:,1)*100 + n3(:, 2)*10 + n3(:, 3) % Convert to numbers.
h = histogram(numbers, 'BinEdges', 0:112) % Count how many times each number occurs.
grid on;
% DONE!
% Just to check, let's print it out to the command window.
for bin = 1 : length(h.Values)
if h.Values(bin) > 0
fprintf('%3.3d shows up %d times.\n', h.BinEdges(bin), h.Values(bin));
end
end
It prints out:
001 shows up 7 times.
011 shows up 9 times.
101 shows up 1 times.
111 shows up 4 times.
4 commentaires
kowshik Thopalli
le 5 Mar 2017
This is good but OP also wants to find for 1111. If the length of the required sequence changes this code doesn't take that into account.
Sunil Kunjachan
le 5 Mar 2017
Image Analyst
le 5 Mar 2017
kowshik, I thought that was a typo, because like you said, the sequence doesn't make sense if you take things in groups of 3 when you're searching for something 4 characters long. The sequence is not a multiple of 4. He didn't say to take them in groups of 4, or 5, or whatever. He said groups of 3. But whatever...
kowshik Thopalli
le 5 Mar 2017
Image Analyst, Thanks for all of your answers. I have immensely benefited through them over years. I know this isnt the right place but can you answer one of my questions regarding the Image datastores. I wish to join two image datastores.
Catégories
En savoir plus sur Function Creation dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!