Difference Between ismember() and contains()

268 次查看(过去 30 天)
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.

采纳的回答

Stephen23
Stephen23 2018-7-18
编辑:Stephen23 2018-7-18
They are not the same at all, they do quite different things!
  • 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.
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
  1 个评论
Luke Perry
Luke Perry 2018-7-18
Hey Stephen. I edited my question with an example to make your answer more clear. Thanks for the reponse!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2017b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by