Reputation: 21
In MATLAB 's classdef, can you define a method that executes any_function that has called it?
For example, say I have defined this custom class type in MATLAB:
classdef custfloat
properties
value = double(0); % Double value
end
methods
function obj = custfloat(v, ex, mant)
obj.value = ........blah blah blah;
end
function v = any_function(arg1,arg2)
v = any_function(arg1.value, arg2.value);
end
end
end
So as long as any_function
is defined for two doubles, it will work, no matter what any_function
actually is.
Does this makes sense?
Upvotes: 2
Views: 195
Reputation: 24127
I'm not sure what your question means exactly, but I think you can get what you're looking for my just subclassing double
.
For example, here's a simple class that extends double
to create something that's like double
, but has a unit as well (for example metres or seconds).
classdef custDouble < double
properties
unit
end
methods
function obj = custDouble(v, u)
% Do something with exponents and mantissas instead if you like,
% I can't remember floating point stuff well enough for this
% example
obj = obj@double(v);
obj.unit = u;
end
function val = myExtraMethod(obj)
val = custDouble(obj*2, obj.unit);
end
end
end
You can now create a custDouble
like this:
>>a = custDouble(2, 'm')
a =
custDouble with properties:
unit: 'm'
double data:
2
You can call your extra methods:
>> b=a.myExtraMethod
b =
custDouble with properties:
unit: 'm'
double data:
4
and you can call any regular function that applies to doubles:
>> sqrt(a)
ans =
1.4142
Note, though, that sqrt
here will return a double
, not a custDouble
- it's just acting on the underlying double
. If you wanted regular functions like sqrt
to return a custDouble
, you'd need to overload them with a method on custDouble
that would behave in the appropriate way (such as, for example, calling builtin('sqrt',...)
on the underlying double
, then constructing the right unit, then putting them together into a custDouble
- in the way that myExtraMethod
above does).
Search the documentation for "Subclassing MATLAB Built-In Types" for more information.
Upvotes: 1