Why Don't We Use == To Compare Strings In Matlab

最后都变了- 提交于 2019-12-18 07:45:34

问题


I know it's commonly accepted that using strcmp is the proper way to compare strings, but my question is why? According to the help:

A == B does element by element comparisons between A and B and returns a matrix of the same size with elements set to logical 1 where the relation is true and elements set to logical 0 where it is not.

And all the toy examples I can come up with seem to work out.


回答1:


strcmp also checks that the inputs are class char, e.g., strcmp('a',double('a')) returns false, but 'a' == double('a') returns true. strcmp cleanly handles empty inputs and you don't have to worry about the two strings being the same length either. And you can use cell inputs to easily compare multiple strings which is useful.

String comparisons can be a good deal slower - at least in current Matlab. But don't prematurely optimize your code at the cost of readability and maintainability. Only use == (or maybe isequal) in rare cases when you really do need performance and are very very sure about what you're comparing (use ischar and isempty first, for example).




回答2:


== uses character-by-character comparison, so trying to test for equality with == with two strings of different lengths should give you an error.




回答3:


Another small exception is with empty strings.

Using '' == '' in if statement evaluates to false.

strcmp('','') is true.



来源:https://stackoverflow.com/questions/19164217/why-dont-we-use-to-compare-strings-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!