How Do I compare classes without having an error
Afficher commentaires plus anciens
>> Array_1 = [1 inf -inf]; Array_2 = [1 2 inf]; Class_double = [0] ; Class_string = 'hi'; Class_boolean = [true];
if class(Array_1) == class(Class_string) & class(Array_2) == class(Class_string)
[Array_1 ' ' Array_2]
elseif class(Array_1) == class(Class_double) & class(Array_2) == class(Class_double)
positive_1 = Array_1 == inf; negative_1 = Array_1 == -inf; positive_2 = Array_2 == inf; negative_2 = Array_2 == -inf;
if sum(positive_1(:)) > 0 & sum(negative_1(:)) > 0
disp 'there is an infinity and negative infinity in Array 1'
elseif sum(positive_1(:)) > 0
disp 'there is an infinity in Array 1'
elseif sum(negative_1(:)) > 0
disp 'there is a negative infinity in Array 1'
else
disp 'there is no infinity or negative infinity in Array 1'
end
if sum(positive_2(:)) > 0 & sum(negative_2(:)) > 0
disp 'there is an infinity and negative infinity in Array 2'
elseif sum(positive_2(:)) > 0
disp 'there is an infinity in Array 2'
elseif sum(negative_2(:)) > 0
disp 'there is a negative infinity in Array 2'
else
disp 'there is no infinity or negative infinity in Array 2'
end
elseif class(Array_1) == class(Class_boolean) & class(Array_2) == class(Class_boolean)
Message = Array_1 & Array_2
disp (message)
else
disp ('they are not of the same class')
end
1 commentaire
Daniel Chan
le 1 Oct 2021
Réponses (1)
Either use isequal or (especially if class hierarchies are involved) use isa.
x = 5;
y = int8(3);
z = 42;
f = figure;
isequal(class(x), class(y)) % false, 'double' is not equal to 'int8'
isa(x, class(z)) % true, x isa 'double'
isa(f, 'handle') % true, f is a Figure, but the Figure class inherits from the handle class
% Since 'double' and 'int8' have different numbers of characters you can't
% compare them using ==
class(x) == class(y) % error
Catégories
En savoir plus sur Structures dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!