MATLAB: Multiple User-Defined Functions

function user

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

Best Answer

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