Find common data between two vectors

13 views (last 30 days)
hegel
hegel on 12 Apr 2018
Commented: hegel on 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 Comments
Walter Roberson
Walter Roberson on 12 Apr 2018
Are you looking for the beginning and ending indices of the largest consecutive common sequence ?

Sign in to comment.

Accepted Answer

John D'Errico
John D'Errico on 12 Apr 2018
Edited: John D'Errico on 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

More Answers (2)

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

Categories

Find more on Cell Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!