How do I make a section of a function runs only one time?

5 views (last 30 days)
Yifan Zhang
Yifan Zhang on 28 Apr 2022
Edited: Stephen23 on 28 Apr 2022
I am running a fimincon algorithm to minimize this function. But the marked part takes a long time to run, and when apply to fmincon, the code takes forever to run. Is there a way to make this section run only once?

Answers (2)

DGM on 28 Apr 2022
Edited: DGM on 28 Apr 2022
One way might be to use persistent variables.
function out = myfunction(a,b,c)
persistent S data_mdl
if isempty(S) | isempty(data_mdl)
% do code to get S and data_mdl
% do other code
There are probably better ways.
You're also doing combine_sess(S) twice, once in the setup, and once in the squared distance line. I don't see why you can't replace the second instance with data. In that case, you wouldn't need to keep S anymore. You'd only need data and data_mdl.
DGM on 28 Apr 2022
Ah sorry. If you make that substitution, you'll have to set data and data_mdl as persistent instead of S and data_mdl. Whichever variables you need to persist between function calls are the ones that need to be specified.
persistent data data_mdl
if isempty(data) | isempty(data_mdl)

Sign in to comment.

Stephen23 on 28 Apr 2022
Edited: Stephen23 on 28 Apr 2022
The MATLAB approach is to move that code outside of the function and parameterize the function call:
The simplest is to use an anonymous function, something like this:
data = slow importing and other call-once code here
fnh = @(x) objfun(x,data); % <- you need this!
out = fmincon(fnh,..)
This is much easler than using persistent variables (which require clearing before running).




Community Treasure Hunt

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

Start Hunting!