MATLAB Answers

Why isn't strfind written to return a value in all cases?

13 ビュー (過去 30 日間)
Carl Witthoft
Carl Witthoft 2016 年 1 月 8 日
編集済み: Stephen Cobeldick 2016 年 1 月 9 日
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 件のコメント


回答 (1 件)

Stephen Cobeldick
Stephen Cobeldick 2016 年 1 月 8 日
編集済み: Stephen Cobeldick 2016 年 1 月 9 日
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:
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)
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):
is hardly simpler than the one required now:
Usually I write my "no-string-found" case first, to make it obvious:
idx = strfind(..);
if isempty(idx)

  2 件のコメント

Carl Witthoft
Carl Witthoft 2016 年 1 月 8 日
I suppose there's no universally optimal answer. My preference is that functions return an error message or error value(s) when they're unsuccessful; clearly other folks prefer a "null" or "empty" special value to be returned.
Walter Roberson
Walter Roberson 2016 年 1 月 8 日
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...


Community Treasure Hunt

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

Start Hunting!

Translated by