Find common data between two vectors

14 Ansichten (letzte 30 Tage)
hegel
hegel am 12 Apr. 2018
Kommentiert: hegel am 13 Apr. 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 Kommentare
Walter Roberson
Walter Roberson am 12 Apr. 2018
Are you looking for the beginning and ending indices of the largest consecutive common sequence ?
hegel
hegel am 12 Apr. 2018
yes

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

John D'Errico
John D'Errico am 12 Apr. 2018
Bearbeitet: John D'Errico am 12 Apr. 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

Weitere Antworten (2)

Birdman
Birdman am 12 Apr. 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 am 12 Apr. 2018

Kategorien

Mehr zu Cell Arrays finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by