I often encounter situations that require doing a vector search in a matrix. Finding discrete matrix elements is quite simple using the find command, but what about finding a vector?

Am aware of 3 of the possibly many options, namely: ismember, strmatch and strfind. But which of these to use for optimal speed? Turns out, strfind is the fastest of the three. Try the following code and be amazed at the order of magnitude difference in its search capability!

%—–define matrix a and vector b———%

a = [1 2 3;4 5 6;7 8 9;10 11 12;13 14 15]’; b = [7 8 9];

%—–using strfind

tic;

pos = strfind((a(:))’,b);

pos = round(pos/size(a,1))+1

disp(toc);

%—–using strmatch

tic;

pos = strmatch(b,(a)’)

disp(toc);

%—-using ismember

tic;

pos = ismember(a,b);

find(sum(pos) == 3)

disp(toc);

Simulation of the above (even such a small matrix) results in average time as 1.91e-4 sec, 6.3e-4 sec and 0.0019 sec respectively! Moral of the story: avoid ismember!