How Do I compare classes without having an error

조회 수: 5 (최근 30일)
Daniel Chan
Daniel Chan 2021년 10월 1일
답변: Steven Lord 2021년 10월 1일
>> 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
Daniel Chan
Daniel Chan 2021년 10월 1일
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

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

답변 (1개)

Steven Lord
Steven Lord 2021년 10월 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.

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by