Multiple User-Defined Functions

조회 수: 4 (최근 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 CenterFile Exchange에서 NaNs에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by