Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 961
maxywb Avatar asked Oct 03 '13 16:10

maxywb


People also ask

Can you use == to compare strings in Matlab?

You can compare string arrays for equality with the relational operators == and ~= .

Can we use == for string comparison?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

Can you compare strings in Matlab?

You can compare and sort string arrays with relational operators, just as you can with numeric arrays. Use == to determine which elements of two string arrays are equal.

What happens when you compare two strings with the == operator?

String Comparison With Objects Class The method returns true if two Strings are equal by first comparing them using their address i.e “==”. Consequently, if both arguments are null, it returns true and if exactly one argument is null, it returns false.


2 Answers

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).

like image 131
horchler Avatar answered Sep 24 '22 04:09

horchler


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

like image 39
aquemini Avatar answered Sep 23 '22 04:09

aquemini