When comparing characters, is ischar(x) && x == 'b' equivalent to strcmp(x, 'b')?

Viewed 658

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.

3 Answers
Related