How do I make a section of a function runs only one time?
5 views (last 30 days)
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.
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).