Why when comparing the class of a variable, the logical array output size differs?
Mostrar comentarios más antiguos
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]
Respuestas (2)
James Tursa
el 6 de Oct. de 2017
Editada: James Tursa
el 6 de Oct. de 2017
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'.
1 comentario
rajat maheshwari
el 6 de Oct. de 2017
Steven Lord
el 6 de Oct. de 2017
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].
Categorías
Más información sobre Entering Commands en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!