Search code examples
matlabstrcmp

Why doesn't strcmp recognize two seemingly equal strings as the same?


Below is the output from the Matlab's console. Both of the strings are the same: '@TBMA3'. Yet Matlab's strcmp function returns 0 when comparing them. Why?

K>> str='@TBMA3'
str =
@TBMA3

K>> method.fhandle
ans = 
@TBMA3

K>> strcmp(method.fhandle, str)
ans =
     0

Solution

  • The most likely reason is that method.fhandle is not a string, but a function handle. Check if class(method.fhandle) gives

    ans =
    function_handle
    

    In that case, the comparison gives 0 because a string (str) cannot be equal to a function handle (method.fhandle).

    In order to check for equality, you would need to convert method.fhandle to a string, or str to a function handle. The first option is not adequate, because char(function_handle) would give 'TBMS3', without '@'. So use the second option, and compare using isequal:

    isequal(method.fhandle, str2func(str))
    

    should give 1.

    This isequal comparison works because both method.fhandle and str2func(str) point to the same already-defined function TBMA3. Compare with f = @(x)x; g = @(x)x, isequal(f,g), which gives 0. This behaviour is explained in the documentation. Thanks to @knedlsepp for helping clarify this.