In MATLAB, I often use this to check if a variable contains a certain single character:
if ischar(x) && x == 'b'
to reduce clutter I'm thinking of changing it to this:
if strcmp(x, 'b')
because if x isn't a character or isn't equivalent to 'b', the comparison returns false as you would expect. Are these statements equivalent in this case or are there gotchas?
More info: x == 'b' isn't enough because this returns true when x == 98, but in certain cases (like validating user input), 98 may be invalid input while b is valid input. Also, the first one fails if x isn't a standard data type (if it's an object for example). Take this (stupid) example:
x = table();
x == 'b'
This throws an error because eq isn't defined for tables, but strcmp(x, 'b') returns 0 because it appears that strcmp also performs a type check. Whether or not this exception handling is desirable probably depends on the circumstances though.
strcmp is the way to go. The == operator is element-wise. If x is not a single character, then the test returns a logical array instead of one:
>> x = 'abc';
>> x == 'b'
ans =
0 1 0
>> x = 'bbb';
>> x == 'b'
ans =
1 1 1
Neither are equal, the second one satisfies the if statement.
Also note that while == (eq) is element-wise, isequal tests for object equality. The caveat is that isequal does not consider data type in the test. That is:
>> isequal('abc',[97 98 99])
ans =
1
>> strcmp('abc',[97 98 99])
ans =
0
>> eq('abc',[97 98 99])
ans =
1 1 1
If you care about data type, use strcmp, if not, use isequal.
Consider also using strcmpi to ignore case or strncmp to compare the first N elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With