3

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

Krus
  • 83
  • 2
  • 10

3 Answers3

2
 find(a(1:end-1) == b(1) & a(2:end) == b(2) == 1)
pangyuteng
  • 1,749
  • 14
  • 29
2

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.

chappjc
  • 30,359
  • 6
  • 75
  • 132
2

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.'));
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147