Dynamic/global function definition

3 ビュー (過去 30 日間)
Stephen Hall
Stephen Hall 2019 年 11 月 7 日
コメント済み: Steven Lord 2019 年 11 月 7 日
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
Guillaume 2019 年 11 月 7 日
You've done it already!
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
Then in your calling code:
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.
  2 件のコメント
Stephen Hall
Stephen Hall 2019 年 11 月 7 日
I've been using Matlab for decades now, and somehow never knew you could return a function! Thanks!
Steven Lord
Steven Lord 2019 年 11 月 7 日
For more information, see the documentation for function handles. An anonymous function, like the ones you created as the setfunc variables in dynfunc, is one type of function handle.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeVariables についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by