Find common data between two vectors

3 visualizaciones (últimos 30 días)
hegel
hegel el 12 de Abr. de 2018
Comentada: hegel el 13 de Abr. de 2018
I have two vectors A and B they both are different length, but a good portion of the values are common to both.
A = [3 4 6 1 7 2 5 6 7 9 0 3 2 8];
B = [4 5 6 6 1 7 2 5 6 7 9 0 3 2 0 5 8 7];
I need to find the indices where [6 1 7 2 5 6 7 9 0 3 2] begin and end
ia = [3 13];
ib = [4 14]
  2 comentarios
Walter Roberson
Walter Roberson el 12 de Abr. de 2018
Are you looking for the beginning and ending indices of the largest consecutive common sequence ?
hegel
hegel el 12 de Abr. de 2018
yes

Iniciar sesión para comentar.

Respuesta aceptada

John D'Errico
John D'Errico el 12 de Abr. de 2018
Editada: John D'Errico el 12 de Abr. de 2018
If you are looking for the longest common substring?
Assuming the elements of A and B are integers, then use of my commonsubstring utility works:
A = [3 4 6 1 7 2 5 6 7 9 0 3 2 8];
B = [4 5 6 6 1 7 2 5 6 7 9 0 3 2 0 5 8 7];
[S,ind1,ind2] = commonsubstring(char(A),char(B))
S =
' '
ind1 =
1×1 cell array
{[3]}
ind2 =
1×1 cell array
{[4]}
+S
ans =
6 1 7 2 5 6 7 9 0 3 2
So the common substring begins at element 3 of A, element 4 of B.
The length of the string is
numel(S)
ans =
11
So that gives you the end points in each string.
A = randi(9,1,10000);
B = randi(9,1,2000);
[S,ind1,ind2] = commonsubstring(char(A),char(B))
S =
' '
ind1 =
1×1 cell array
{[691]}
ind2 =
1×1 cell array
{[756]}
+S
ans =
5 4 4 2 3 1 9 6
It can be found here:
https://www.mathworks.com/matlabcentral/fileexchange/27460-string-subsequence-tools

Más respuestas (2)

Birdman
Birdman el 12 de Abr. de 2018
One approach:
A = [3 4 6 1 7 2 5 6 7 9 0 3 2 8];
B = [4 5 6 6 1 7 2 5 6 7 9 0 3 2 0 5 8 7];
pattern = [6 1 7 2 5 6 7 9 0 3 2];
[ia1,ia2]=regexp(reshape(char(string(A)),1,[]),reshape(char(string(pattern)),1,[]));
[ib1,ib2]=regexp(reshape(char(string(B)),1,[]),reshape(char(string(pattern)),1,[]));
ia=[ia1 ia2]
ib=[ib1 ib2]

Walter Roberson
Walter Roberson el 12 de Abr. de 2018

Categorías

Más información sobre Cell Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by