简体   繁体   English

如何在 MATLAB 中找出两个不同向量中的连续数字序列?

[英]How to find out consecutive sequence of numbers in two different vectors in MATLAB?

Suppose one vector is x= [-2 -2 -1 -1 -1 -2 -1 0 5 -1 0 5 -1 0] and other vector is y=[ 2 3 4 5 -1 0 5 -1 0 5 -1].假设一个向量是 x= [-2 -2 -1 -1 -1 -2 -1 0 5 -1 0 5 -1 0] 而另一个向量是 y=[ 2 3 4 5 -1 0 5 -1 0 5 -1]。 The two vectors need not to be of same length.这两个向量不必具有相同的长度。 I want to find out the similar sequence/pattern of longest consecutive numbers in two vectors using MATLAB?我想使用 MATLAB 找出两个向量中最长连续数字的相似序列/模式? The result should be starting and ending indices of matched pattern in both vectors.结果应该是两个向量中匹配模式的开始和结束索引。 For this example: ix=[7 12] and iy=[5 10].对于此示例:ix=[7 12] 和 iy=[5 10]。

This requires the Image Processing Toolbox and the Statistics Toolbox.这需要图像处理工具箱和统计工具箱。 It uses a loop over chunk size:它使用块大小的循环:

x = [-2 -2 -1 -1 -1 -2 -1 0 5 -1 0 5 -1 0];
y = [ 2 3 4 5 -1 0 5 -1 0 5 -1];
for n = min(numel(x), numel(y)):-1:1; % try sizes in decreasing order
    x_sliding = reshape(im2col(x,[1 n],'sliding'),n,[]).'; % reshape needed for n=1
    y_sliding = reshape(im2col(y,[1 n],'sliding'),n,[]).'; % reshape needed for n=1
    [ind_x, ind_y] = find(pdist2(x_sliding, y_sliding) == 0);
    if ~isempty(ind_x)
        ix_start = ind_x;
        iy_start = ind_y;
        ix_end = ind_x+n-1;
        iy_end = ind_y+n-1;
        break
    end
end

The solutions, if they exist, are given in ix_start , ix_end , iy_start , iy_end .解决方案(如果存在)在ix_startix_endiy_startiy_end中给出。 If there are several solutions of the maximal possible size, the indices of all of them are produced.如果存在最大可能大小的多个解,则生成所有解的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM