为什么strcmp不能识别两个看似相同的字符串呢?

cer*_*rou 3 matlab strcmp

下面是Matlab控制台的输出.两个字符串都是相同的:'@TBMA3'.然而Matlab的strcmp函数0在比较时会返回.为什么?

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

K>> method.fhandle
ans = 
@TBMA3

K>> strcmp(method.fhandle, str)
ans =
     0
Run Code Online (Sandbox Code Playgroud)

Lui*_*ndo 8

最可能的原因是它method.fhandle不是字符串,而是函数句柄.检查是否class(method.fhandle)给出

ans =
function_handle
Run Code Online (Sandbox Code Playgroud)

在这种情况下,比较给出0因为string(str)不能等于函数handle(method.fhandle).

为了检查是否相等,您需要转换method.fhandle为字符串或str函数句柄.第一个选项是不够的,因为char(function_handle)会给'TBMS3',没有'@'.所以使用第二个选项,并使用isequal:

isequal(method.fhandle, str2func(str))
Run Code Online (Sandbox Code Playgroud)

应该给1.

isequal比较适用,因为两者method.fhandlestr2func(str)指向同一个已定义的函数TBMA3.比较f = @(x)x; g = @(x)x, isequal(f,g),给出0.文档中说明了此行为.感谢@knedlsepp帮助澄清这一点.