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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With