I have a MATLAB code (see below) that employs 'fsolve' from the optimization toolbox for a root finding problem.
The bottleneck is that, within the objective function calculation, there is a computationally expensive function (denoted as 'expensive_function' in the below code, and is located in the matlabpath). The variable 'x_sol' holds solution returned by 'fsolve'.
The issue is that, within the main code, I need access to the 'other_results' struct computed by the expensive function for further calculations. It is wasteful to recompute the 'other_results' struct using the solution value (such as by using the following line of code within 'main' )
other_results = expensive_function(x_sol,param);
Is there a way to get access to this struct without re-evaluating the expensive_function?
PS: I have been cautioned throughout my career against using global/persistent variables, and I have thus far stayed clear of them. I don't know if this is the only recourse to solving this issue, or there exists a better/clever way ?
%% main code
x_sol = fsolve(@(x) compute_residual(x,param) , x0);
% code below needs to use various values from the "other_results" struct computed in the obj_fun function
line with some computation on 'other_results' result
line with some other computation using 'other_results' struct
....
...
and so on.
________________________________________________________
function residual = compute_residual(x, param)
other_results = expensive_function(x,param); % other_results is a struct returned by a very computationally expensive function
residual = abs(other_results.a * other_results.b - x) % the abs(diff)
end
compute_residual
may be called several times with different values for eachfsolve
iteration. This behavior may depend on the algorithm used and the objective function. Your answer may be close, but it might not be identical. The best method is to recomputeother_results
afterwards. You could also possibly use theOutputFcn
option as it is called at the end of every iteration. $\endgroup$