MATLAB: What other command can I use instead of isempty

findisemptystrfind

If I have A = '1' and B = {'2', '3', '4'} And naturally my strfind(B, A) returns ans =
[] [] []
I try to use this in an if statement with
if ~isempty(strfind(B, A))
condition 1
else
condition 2
end
and hope that this will execute condition 2, however it turns out isempty only returns logical 1 when used with strfind… How can I modify my code? And any suggestions on which command works faster between using strfind() and find()? Thank you as always!

Best Answer

if ~isempty(strfind(B, A))
condition 1
else
condition 2
end
The problem is that, even conceptually, this does not express what you actually want, so it's no wonder it does not work.
You're not asking if A is found in B (in which case, using isempty(strfind(...)) would work). You want to ask either (it's not clear from your question) if A is found in all of the Bs, or in any of the Bs. That's a completely different question, hence the syntax is different.
strfind when given a cell array tells you, for each element of B, this is where I found A. Therefore, you have to ask strfind: for each element of B is the return value empty. And finally, you have to apply the any or all operator (depending on what you want) to that answer. So:
if any(~cellfun(@isempty, strfind(B, A))) %possibly replace any by all
condition1
else
condition2
end