Why does strcmp take numerical arguments?

조회 수: 7 (최근 30일)
per isakson
per isakson 2013년 7월 29일
I found an old bug in my code. I pass by mistake a numerical value to strcmp. Now, I made a little test with R2013a
num = double('A');
is1 = strcmp( num, {'A','B','C'} );
is2 = strcmp( num, {'A','B','C',num} );
is3 = strcmp( num, {'A','B','C',num2str(num)} );
[any(is1),any(is2),any(is3)]
returns
ans =
0 0 0
strcmp accepts the numerical argument, but doesn't find anything. I would have appreciated an error together with a message.
On the other hand, I use a similar behavior of strfind. It takes numerical inputs.
n1 = (65:67);
n2 = (61:70);
strfind( n2, n1 ) % us' trick
returns
ans =
5
That is an efficient way to search for sub-sequences in row vectors of flints (whole numbers). Last millennium the difference in speed mattered.

채택된 답변

Mike Hosea
Mike Hosea 2013년 7월 29일
I think the intent was that the semantics of strcmp be
ischar(a) && ischar(b) && strcmp(a,b)
where in that expression it obviously doesn't matter what strcmp does if either a or b is not a string. That way, when processing inputs to a function you can just write
if strcmp(opt,'high road')
and be done with it. I know that this is pretty much what I have wanted strcmp to do, and been glad that it did, on a number of occasions. Anyway, once this was the behavior, it certainly became a backward compatibility issue to change it. It is inconsistent with strfind, unfortunately, but I think strfind's behavior is also a backward compatibility thing. The help text and doc don't mention supporting non-string input.
  댓글 수: 2
Jan
Jan 2013년 7월 29일
+1. Then the only problem is the incomplete documentation.
Daniel Shub
Daniel Shub 2013년 7월 30일
For r2013a the documentation for STRCMP, under tips, says "The strcmp function is intended for comparison of character data. When used to compare numeric data, it returns logical 0." Not where I would expect the warning to be, but it is there.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2013년 7월 29일
편집: Jan 2013년 7월 29일
Another example:
strcmp(1, 1) % FALSE
strcmp(pi, pi) % FALSE
This behavior can be observed in 2011b, 2009a and version 6.5 also. Therefore it looks like a backward compatibility feature.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by