Multiple User-Defined Functions

9 ビュー (過去 30 日間)
RealA
RealA 2019 年 5 月 7 日
回答済み: Walter Roberson 2019 年 5 月 7 日
How would I create multiple user-defined functions in one script. For example I want one script containing conversion formulas with metric to imperial and the other script containg functions with imperial to metric. Essentialy I want one script containing functions such inches to centimetres and fahrenheit to celsius.
Thanks

採用された回答

Walter Roberson
Walter Roberson 2019 年 5 月 7 日
You can do that, but you can only invoke them from inside the script, with one exception:
In order to invoke those functions from outside the script, the code of the script would have to take handles of the functions and save the handles in some known location. For example,
%this is my script
H{1} = @fun1;
H{2} = @fun2;
set(0, 'UserData', H);
function y = fun1(x)
y = x.^2 - 3;
end
function y = fun2(x)
y = sin(x) ./ exp(x);
end
Then in this example, you could call upon those functions from outside the script by using
H = get(0, 'UserData');
H{1}(3.81)
See also packages and static methods of classes.
If you were defining a function instead of a script, you would also have the option of using a "switchyard" design, such as:
function h = get_fun(funname)
switch funname
case 'f2m'
h = @f2m;
case 'm2f'
h = @m2f;
otherwise
h = @(varargin) error('unknown function name "%s"', funname);
end
end
function m = f2m(f)
m = f*whatever;
end
function f = f2m(m)
f = m/whatever;
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMathematics and Optimization についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by