- ismember checks which complete elements of A are in B. The input arrays can be numeric, char, string, datetime, categorical, table, etc.
- contains checks if the pattern occurs anywhere within any the elements of str. The input arrays are string array.
Difference Between ismember() and contains()
255 views (last 30 days)
Show older comments
I've been using contains() for quite a while when comparing strings, but recently have started using ismember() instead. I'm not really sure what the "proper" way of doing things is. Is one more efficient than the other or is contains() simply a "special case" of ismember() that only works for strings and cell arays? I've run through a few iterations of both with the same cell arrays and string comparisons, but they take about the same amount of time to execute. I didn't use a large data set to analyze both.
Does anyone know why contains() exists if ismember() can do the same functionality? Is one an older function that has yet to be removed in a later release?
For my purposes, I'm using ismember() or contains() when parsing varargin for variable input functions. So something like the following:
function DoSomething(varargin)
mycells={struct('figurehandles','somefigures'),'authentication','configuration'}
mykeywords=mycells(2:end)
if ismember('authentication',mykeywords)
%Do Something
end
The difference, as Stephen points out can be illustrated by the following code:
mycells={struct('figurehandles','somefigures'),'authentication password','configuration'};
mykeywords=mycells(2:end);
ismember(mykeywords,'authentication')
contains(mykeywords,'authentication')
ismember() returns [0, 0] while contains() returns [1, 0]. This is due to contains looking for any instance of the patterned string. So not only does it search whole entries of strings, but for substrings within those strings. This results in contains() recognizing "authentication" within "authentication password" while ismember() does not.
0 Comments
Accepted Answer
Stephen23
on 18 Jul 2018
Edited: Stephen23
on 18 Jul 2018
They are not the same at all, they do quite different things!
Have a look at the contains example:
>> str = ["Mary Ann Jones","Paul Jay Burns","John Paul Smith"];
>> pattern = "Paul";
>> TF = contains(str,pattern)
TF = 1x3 logical array
0 1 1
Note that the pattern is not same as any complete element of str (it is only part of some of them). If you try the same with ismember it only matches the complete element:
>> TF = ismember(pattern,str)
TF = 1x3 logical array
0 0 0
>> TF = ismember("John Paul Smith",str)
TF = 1x3 logical array
1 0 0
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!