Reputation: 255
I’m wondering if there is an easy way to check if two Matlab objects are equal. I got
A = Section(1, Point(0, 0), Point(0, 0));
B = Section(1, Point(0, 0), Point(0, 0));
if(A == B) % I know this is incorrect, but how could I fix it up?
fprintf('Equal\n');
else
fprintf('Not Equal\n');
end
After instantiating two sections, I want to check if they are the same (in the case above they are equal). How could I do that?
Upvotes: 6
Views: 3881
Reputation: 4077
If you want to use ==
shorthand you can overload eq
method in your class. This way you can also easily compare arrays of objects, as long as they have the same dimensions or one is a scalar:
function equal = eq(obj1, obj2)
if isscalar(obj1) && isscalar(obj2) % fast handling for the easy case
equal = isequal(obj1, obj2);
return;
end
assert(isscalar(obj1) || isscalar(obj2) || isequal(size(obj1), size(obj2)), 'Inputs must have the same dimensions unless one is a scalar');
if isscalar(obj1) && ~isscalar(obj2)
obj1 = repmat(obj1, size(obj2));
elseif isscalar(obj2) && ~isscalar(obj1)
obj2 = repmat(obj2, size(obj1));
end
equal = arrayfun(@(o1, o2) isequal(o1, o2), obj1, obj2);
end
Upvotes: 0