# Dynamic/global function definition

2 views (last 30 days)
Stephen Hall on 7 Nov 2019
Commented: Steven Lord on 7 Nov 2019
Is there a way to create something like a global variable, but its a function? I would like to be able to define a function, which we'll call "dynfunc", in one function, and then be able to use it in others. The reason for this is that I have several different complicated models for calculating a particular value Y, but I am only going to use one of those models at any given time and don't want to have to continuously pass and process all the variables needed in setting up the chosen model. So I would like to use something like:
function Y=dynfunc(X,Model,varargin)
% Here there would be some way to process the varargin's into variables A, B, C, and D
switch lower(Model)
case 'model1'
setfunc = @(x) A.*x.^2+B.*x+C;
case 'model2'
setfunc = @(x) A.*sin(D.*x);
end
Y = setfunc(X);
end
But (and here's the challenge) I want to be able to call setfunc directly after this from a different function entirely! So the first time, I call dynfunc, but it's primary job is not to calculate Y but really to create setfunc, which then lives it's own life outside of dynfunc. So is there a way to do this? That way instead of having to pass all the varargin's each time and go through the process to create setfunc, I just call setfunc because it's already set up! Call dynfunc the first time and then just call setfunc.

Guillaume on 7 Nov 2019
Instead of using setfunc in dynfunc to apply it to X, simply return it out of dynfunc, so it can be used and passed by the calling function:
%dynfunc function:
function setfunc = dynfunc(Model, varargin)
switch lower(Model)
case 'model1'
setfunc = @(x) A.*x.^2+B.*x+C;
case 'model2'
setfunc = @(x) A.*sin(D.*x);
end
end
func = dynfunc('model1', something, something, something)
%...
x = 1:10
result = func(x);
the function returned by dynfunc can be passed around to as many functions as you want.