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

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)

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
end
% do other code
end
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.

2 Comments

Hi, so i did the persistent command. But as I ran fmincon, it shows 'Unrecognized function or variable 'data'.' Not sure what's going wrong.
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.

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).

Products

Release

R2021b

Asked:

on 28 Apr 2022

Edited:

on 28 Apr 2022

Community Treasure Hunt

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

Start Hunting!