using while-end block to find pattern in an array
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Write code using a while loop that will assign to the variable numOccursSep the number of times a certain pattern of 0's and 1's occurs separately in V. The variable pattern gives the certain pattern to look for. For this problem overlap is not allowed, i.e. if pattern = [0, 1, 0] then the last 0 of an occurrence of [0, 1, 0] cannot be the rst 0 of the next occurrence. For example, if V = [0, 1, 0, 1, 0] then only one instance of [0, 1, 0] should be counted and numOccursSep should equal 1.
V = [0, 1, 0, 1, 0];
pattern = [0, 1, 0];
count = 0;
while strfind(V,pattern) == 1
count = count+1;
end
numOccursSep = count;
Normally I would use strfind(V,pattern) and then numel(strfind(V,pattern)) but I do not know how to account for the fact that overlap is not allowed. How can I do this?
9 comentarios
dpb
el 23 de Jun. de 2014
Editada: dpb
el 23 de Jun. de 2014
Closer, and "sorta'" :) Note in my implementation there are two position indicators, not just one and the loop control is over the second. These two are the start:end locations for the next part of the string to search; hence the loop runs until the new end position runs past the length(searchstring). You've recast it to only one and keep searching from the beginning instead of moving the starting point along...the rest of my implementation is
count = count+1; % found a match, increment by L
i1=i2+1;i2=i2+L;
else % no match, no count, increment by 1
i1=i1+1;i2=i2+1;
end
end
Respuestas (2)
dpb
el 23 de Jun. de 2014
Putting comments together since did put in the effort to try...
L=length(pattern); % keep the constant
i1=1;i2=L; % start w/ beginning of string length of pattern
count=0;
while i2<length(V)
if strfind(V(i1:i2),pattern) % found, so
count = count+1; % increment count
i1=i2+1;i2=i2+L; % next start is previous end+1, length L
else % not found, so
i1=i1+1;i2=i2+1; % look in next position
end
end
I'll still note one can use the raw output of strfind on the whole vector and post-process the found locations with diff to discover which are not disparate subsections to remove the overlapped cases.
0 comentarios
Andrei Bobrov
el 23 de Jun. de 2014
Editada: Andrei Bobrov
el 23 de Jun. de 2014
m = numel(pattern);
ii = strfind(V(:)',pattern(:)');
k = ii(1);
f = ii(2:end);
count = 1;
while numel(f) >= 1
count = count + 1;
f = f((k + m - 1) < f);
k = f(1);
f = f(2:end);
end
other variant witout while loop
m = numel(pattern);
x = zeros(1,numel(V));
x(bsxfun(@plus,strfind(V(:)',pattern(:)'),(0:m-1)')) = 1;
t = sum(floor((strfind([x 0],[1 0])...
- strfind([0 x],[0 1]) + 1)/m));
0 comentarios
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!