How Do I compare classes without having an error

>> 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

trying to compare the classes and execute the command if it is true but it says arrays have incompatible sizes for this operation if it has a class different from the first if statement

Connectez-vous pour commenter.

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'
ans = logical
0
isa(x, class(z)) % true, x isa 'double'
ans = logical
1
isa(f, 'handle') % true, f is a Figure, but the Figure class inherits from the handle class
ans = logical
1
% Since 'double' and 'int8' have different numbers of characters you can't
% compare them using ==
class(x) == class(y) % error
Arrays have incompatible sizes for this operation.

Catégories

Produits

Version

R2021a

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by