Find common data between two vectors

4 次查看(过去 30 天)
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 个评论
Walter Roberson
Walter Roberson 2018-4-12
Are you looking for the beginning and ending indices of the largest consecutive common sequence ?

请先登录,再进行评论。

采纳的回答

John D'Errico
John D'Errico 2018-4-12
编辑:John D'Errico 2018-4-12
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

更多回答(2 个)

Birdman
Birdman 2018-4-12
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 2018-4-12

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by