Filter löschen
Filter löschen

overloading elementary operations on custom classes

1 Ansicht (letzte 30 Tage)
J. Alex Lee
J. Alex Lee am 23 Jul. 2018
I want to encapsulate numbers within a class to hold some meta-information about the number, e.g.
classdef myClass
properties
Value
Meta1
Meta2
end
methods obj = myClass(Value,Meta1,Meta2)
myClass.Value = Value;
myClass.Meta1 = Meta1;
myClass.Meta2 = Meta2;
end
end
and I would like to be able to operate on this class using functions defined for numbers (reals, complex, integers, etc), which the Value property would contain, e.g.:
>> var = myClass(5.2,'Info1','Info2')
>> var+5
ans =
10.2
I understand the following mechanism to intercept specific functions:
methods
function out = plus(A,B)
if isa(A,'myClass')
A = A.Value;
end
if isa(B,'myClass')
B = B.Value;
end
out = builtin('plus',A,B);
end
end
but I wonder if there is a way to intercept all operators so that any time an attempt is made to operate on an object of class 'myClass', it will know to operate only on the Value property of the class? In other words, I don't want to replicate the code above for all functions I would want to be able to use directly on the myClass object, e.g., minus, cos, sign, mldivide.
I also don't want to have to specify the Value property every time, e.g., "cos(var.Value)"

Antworten (0)

Kategorien

Mehr zu Historical Contests finden Sie in Help Center und File Exchange

Produkte


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by