Krus
Krus

Reputation: 83

Find part of vector in another vector matlab

I would like to know if there is an easy way to find the indices of a vector in another vector in matlab:

a = [1 2 3 5 7 10 2 3 6 8 7 5 2 4 7 2 3]
b = [2 3]

So how to get the indices of a when comparing it with b (index of first element is needed)

In this case:

ans = [2 7 16]

Thanks in advance

Upvotes: 3

Views: 1252

Answers (3)

Luis Mendo
Luis Mendo

Reputation: 112659

General approach with length of b arbitrary (not necessarily 2 as in the example), and avoiding the use of strings:

match1 = bsxfun(@eq, a(:), b(:).'); %'// now we just need to make the diagonals
%// horizontal (in order to apply "all" row-wise). For that we'll use indices
%// ind, ind1, ind2
ind = reshape(1:numel(match1), numel(a), numel(b));
ind1 = nonzeros(tril(ind)); %// source indices
ind2 = sort(nonzeros(tril(flipud(ind)))); %// destination indices
match2 = zeros(size(match1));
match2(ind2) = match1(ind1); %// diagonals have become horizontal
result = find(all(match2.'));

Upvotes: 2

chappjc
chappjc

Reputation: 30579

You can re-purpose strfind by converting the elements of both vectors to byte arrays (uint8) with typecast:

bytesPerEl = numel(typecast(a(1),'uint8'));
byteLocs = strfind(char(typecast(a,'uint8')),char(typecast(b,'uint8')));
locsb = (byteLocs-1)/bytesPerEl + 1

locsb =

     2     7    16

Just make sure a and b are of the same type. Also note that this works for 1D vectors, not matrixes or higher dimensional arrays.

Upvotes: 2

pangyuteng
pangyuteng

Reputation: 1839

 find(a(1:end-1) == b(1) & a(2:end) == b(2) == 1)

Upvotes: 2

Related Questions