Find common data between two vectors

5 ビュー (過去 30 日間)
hegel
hegel 2018 年 4 月 12 日
コメント済み: hegel 2018 年 4 月 13 日
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 ?
hegel
hegel 2018 年 4 月 12 日
yes

サインインしてコメントする。

採用された回答

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
  1 件のコメント
hegel
hegel 2018 年 4 月 13 日
Thank you!

サインインしてコメントする。

その他の回答 (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]
  1 件のコメント
hegel
hegel 2018 年 4 月 13 日
Thank you!

サインインしてコメントする。


Walter Roberson
Walter Roberson 2018 年 4 月 12 日
  1 件のコメント
hegel
hegel 2018 年 4 月 13 日
Thank you!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by