简体   繁体   中英

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]. 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? The result should be starting and ending indices of matched pattern in both vectors. For this example: ix=[7 12] and 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 . If there are several solutions of the maximal possible size, the indices of all of them are produced.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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