How to find the first instance of a pattern in a cell array?
Afficher commentaires plus anciens
I have a sublist of patterns:
pattern = {{1 1 1}, {4 4 4}, {1 1 4}, {1 4 1}};
and a set of data:
data = {0;0;0;0;0;0;1;0;1;1;0;1;4;0;1;1;1;4;0;0;1};
And I want to be able to find the first instance of any one of the possible patterns within the data array. I have thought about converting all instances of 4 to 1 and do something simple like:
count = 0;
indx = {};
for ii = 1:length(data)
if data{ii} == 1
count = count + 1;
indx{count} = ii;
else
count = 0;
end
if count == 3
break
end
end
first_instance = indx{1};
But I was wondering if there was something that was more elegant and didn't require data conversion. Maybe a moving window to match patterns?
Any help would be appreciated.
Réponse acceptée
Plus de réponses (2)
Jos (10584)
le 1 Déc 2017
It would be much easier if you store this as regular arrays, rather then cell arrays of scalar cells. You can use strfind if all the values are integers => 0. Example:
pattern = {[1 1 1], [4 4 4], [1 1 4], [1 4 1]}
data = [0 0 0 0 0 0 1 0 1 1 0 1 4 0 1 1 1 4 0 0 1]
sfix = cellfun(@(x) min([strfind(data, x) Inf]), pattern)
[p, ix] = min(sfix) % p = position in data, ix = which pattern
Joshua Williams
le 1 Déc 2017
0 votes
Catégories
En savoir plus sur Logical 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!