Why when comparing the class of a variable, the logical array output size differs?
显示 更早的评论
for e.g-
a=5;
class(a)=='double'
% output comes 1x6 logical array [1 1 1 1 1 1]
and if we use
a='a'
class(a)=='char'
% output is 1x4 logical array [1 1 1 1]
回答(2 个)
James Tursa
2017-10-6
编辑:James Tursa
2017-10-6
Use this instead
isequal(class(a),'double')
or
strcmp(class(a),'double')
What you are doing with class(a)=='double' is comparing each character of class(a) with each character of 'double', thus yielding a 6 element result. E.g.
>> a = single(5)
a =
5
>> class(a)=='double'
ans =
0 0 0 0 1 1
The first four 0's are because 'sing' did not match 'doub'. The last two 1's are because 'le' matches 'le'.
Steven Lord
2017-10-6
I suspect that your mental model for == on char vectors is that it should return a scalar true or false value depending on whether the char vectors are equal. That is not the correct model for char vectors. It is the correct mental model for the newer string data type.
>> "double" == "double"
ans =
logical
1
>> "double" == "char"
ans =
logical
0
But char vectors are treated like numeric vectors by ==.
>> [11 22 33 44 5 6] == [2 3 4 1 5 6]
ans =
1×6 logical array
0 0 0 0 1 1
>> 'double' == 'single'
ans =
1×6 logical array
0 0 0 0 1 1
'd' is not equal to 's', so the first element of the output is false. The same holds for 'o' and 'i', 'u' and 'n', and 'b' and 'g'. But 'l' does equal 'l' and 'e' equals 'e' so the last two elements of the output are true.
As James said you should use isequal. [If user-defined objects and class inheritance may be involved, use isa instead.] One reason is that if you use == to compare two char vectors that are NOT the same length, you will receive an error:
>> 'double' == 'char'
Matrix dimensions must agree.
That's the same error you would get from [1 2] == [1 2 3].
类别
在 帮助中心 和 File Exchange 中查找有关 Entering Commands 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!