Borrar filtros
Borrar filtros

How to find pattern in an array?

75 visualizaciones (últimos 30 días)
MathWorks Support Team
MathWorks Support Team el 5 de Dic. de 2017
Comentada: gwoo el 25 de Mayo de 2022
How to find a pattern from a numeric array?
For example, there is a numeric array B and pattern (or mask) A. How to get the pattern location found in B? 
 
>> A = [1 2 3];
>> B = [5,4,3,1,2,3,5,4,1,2,3,4,5];
 
Expected output: 4, 9
 

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 5 de Dic. de 2017
There is no built-in MATLAB function that performs the exact operation described.
However, you can use a single for-loop and the built-in "all" and "find" functions to create a custom function that will output the desired behavior:
>> function output = pattern(B, A)
>> SIZE = length(B) - length(A);
>> match = zeros(1, SIZE);
>> for i=1:SIZE
>> match(i) = all(B(i:i-1+length(A)) == A);
>> end
>> output = find(match == 1);
>> end
  1 comentario
gwoo
gwoo el 25 de Mayo de 2022
As @claudio points out below in More Answers, strfind(B, A) does exactly what is requested.

Iniciar sesión para comentar.

Más respuestas (1)

claudio
claudio el 14 de Mayo de 2020
output = strfind(B,A);
  1 comentario
claudio
claudio el 14 de En. de 2021
No exceptions. if you have a particular request you can submit it to evaluate the specific case
str = sprintf('Special string for \t Karel \t K');
pattern = sprintf('\t');
idxTab = strfind(str,pattern)
idxTab =
20 28

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by