MATLAB: Search a vector in a matrix

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
pos = strfind((a(:))’,b);
pos = round(pos/size(a,1))+1
%—–using strmatch
pos = strmatch(b,(a)’)
%—-using ismember
pos = ismember(a,b);
find(sum(pos) == 3)

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!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s