user3535716
user3535716

Reputation: 255

Matlab oop - how to check if two objects are equal

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

Answers (2)

nirvana-msu
nirvana-msu

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

horchler
horchler

Reputation: 18484

isequal is probably what you want, but this page has further information on comparing and sorting handle objects. eq (==) tests if two objects have the same handle, i.e., handle equality, whereas isequal tests if two objects have equal property values.

Upvotes: 5

Related Questions