How to call a class-specified overloaded version of a function without using an object instance as an argument

1 回表示 (過去 30 日間)
I have a class:
classdef fast_calc < handle
properties
value
end
methods
function obj = fast_calc(x)
obj.value = x;
end
function y = sin(obj)
if isa(obj,'fast_calc')
x = obj.value;
else
x = obj;
end
% Fast calculation of sin using a Taylor expansion:
y = x - x.^3 / 6;
end
end
end
the function sin works fine on a fast_calc object:
>> myNum = fast_calc(pi/6);
>> sin(myNum)
ans =
0.4997
However, I would like also to be to call it directly on a standard numeric variable, something like:
>> fast_calc.sin(pi/6)
but this returns an error
The class fast_calc has no Constant property or Static method named 'sin'.
I don't want to define 'sin' as a static method because then sin(myNum) will not automatically invoke the overloaded function.
Is there a solution which allows calling an overloaded method both automatically on an instance, and on other object types when explicitly requesitng it?

採用された回答

per isakson
per isakson 2021 年 8 月 21 日
編集済み: per isakson 2021 年 8 月 21 日
"I don't want to define 'sin' as a static method because then sin(myNum) will not automatically invoke the overloaded function"
I have defined sin() as a Static method (attached) and here (R2018b) both ways of calling works
fast_calc.sin(pi/6)
ans = 0.4997
fc = fast_calc(pi/6);
fast_calc.sin( fc )
ans = 0.4997
Ok, that's not what you asked, but AFAIK it's what Matlab offers.

その他の回答 (1 件)

royk
royk 2021 年 8 月 21 日
thnaks.
indeed really what i wanted cause you cannot use the simple notation sin(fc) .
but thanks for clarifying that this is it as far as what Matlab offers

カテゴリ

Help Center および File ExchangeConstruct and Work with Object Arrays についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by