# Find whether a vector occurs exactly in another vector

59 views (last 30 days)
Mark on 29 Jan 2015
Commented: Guillaume on 29 Jan 2015
Hi,
I try to compare two vectors (waveforms from wav files). One is the original sound file and the other is a manipulated sound file. I try to find the indices in the original sound file that match with the manipulated sound file. In the end, I would like to plot the original sound file and highlight the parts that were manipulated.
Loading the files into Matlab is no problem, but finding a way to compare/match the files is difficult. I tried the "ismember" function, but I think this function will try to find a match for each datapoint whereas I need something that matches a complete vector with original sound files.
Any suggestion on how to find whether a small vector occurs exactly in another longer vector?
Best, Mark

Guillaume on 29 Jan 2015
Surprisingly enough, strfind works on numerical arrays as well and does exactly what you need:
x = [4 3 1 7 36 4 2 3 1 2 58 8 4 6 99 4 3 2 1 5 7 6 4 1 8 4 6 99 4 3 2 1 3 9 7 7 4 3 5];
y = [8 4 6 99 4 3 2 1]; %occurs at position 12 and 25 in x
pos = strfind(x, y)
##### 2 CommentsShowHide 1 older comment
Guillaume on 29 Jan 2015
I think that's indeed on Loren's blog that I first came across it.

### More Answers (2)

Eric G. on 29 Jan 2015
This may be a brute force way but MATLAB should be able to handle it with no problem.
Just scan the shorter vector across the longer one and compare for equality.
x= [4 3 1 7 36 4 2 3 1 2 58 8 4 6 99 4 3 2 1 5 7 6 4 1 3 9 7 7 4 3 5];
y = [8 4 6 99 4 3 2 1];
ny = length(y);
for k = 1:(length(x)-ny+1)
check = x(k:k+ny-1)== y;
if sum(check) == ny
fprintf('Found a match at k = %2.0i \n',k)
end
end

Andrei Bobrov on 29 Jan 2015
Edited: Andrei Bobrov on 29 Jan 2015
other variant
n = numel(y);
pos = find(all(bsxfun(@eq,y(:),hankel(x(1:n),x(n:end)))));