Why isn't strfind written to return a value in all cases?
7 views (last 30 days)
Show older comments
A very common programming question (e.g. logical expression failure ) occurs because strfind's behavior when no match is found is to return "[]" . Since anytime strfind reports success, the output is 1 or more positive integers, why doesn't strfind return zero (equivalent to logical false) on failure? That seems much more intuitive (at least to me), and it saves the pain of writing " if length(strfind()) " .
0 Comments
Answers (1)
Stephen23
on 8 Jan 2016
Edited: Stephen23
on 9 Jan 2016
What you are proposing breaks a basic property of strfind (and find, etc): the number of elements in the output is equal to the number of detected patterns. If a user only needs to know how many times that pattern exists:
numel(strfind(str,pat))
will no longer work following your proposal. It would then require a special case for the length of the output, i.e. one that would need to be dealt with separately in all code. Consider looping over the found indices:
for k = strfind(str,pat)
fun(k);
end
This loop iterates as many times as there are output indices. So if pat is not matched, then the loop (correctly) iterates zero times. And if the output instead would be zero it requires an uncomfortable special-case handling (either if inside the loop, or some ugly zero-removal in the loop variable definition).
To be consistent your proposal would also have to applied to find as well, as well as every other function that returns indices. Can you imagine the confusion?
Why is 0 as an output better than []? The only difference would be those students would get some different error messages (something about indices being non-zero) and get equally confused. The required test (if no pattern found):
idx>0
is hardly simpler than the one required now:
~isempty(idx)
Usually I write my "no-string-found" case first, to make it obvious:
idx = strfind(..);
if isempty(idx)
...
else
...
end
2 Comments
Walter Roberson
on 8 Jan 2016
The function is not unsuccessful. The function returns a list of all of the matches. 1 entry for 1 match, 2 entries for 2 matches, 0 entries for 0 matches...
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!