3

I created a class xyz which results in a matrix comprising only integers. If I try to add two instances of that class, I do receive the error message:

"Undefined operator '+' for input arguments of type 'xyz'."

What am I supposed to do to make the in-built + operator compatible with instances of my class?

1 Answer 1

6

You have to use the plus method to override the behavior of +

classdef MyObject

    properties
        value
    end

    methods
        function this = MyObject(v)
            this.value = v;
        end

        function result = plus(this, that)
            % Create a new object by adding the value property of the two objects
            result = MyObject(this.value + that.value);
        end
    end
end

Then use it like:

one = MyObject(1)
%  MyObject with properties:
%
%   value: 1


two = MyObject(2)
%  MyObject with properties:
%
%   value: 2

three = one + two
%  MyObject with properties:
%
%   value: 3

For other common operators, there is an extensive list here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.