我有一个 MATLAB 代码(见下文),它使用优化工具箱中的“fsolve”来解决求根问题。
瓶颈在于,在目标函数计算中,有一个计算量很大的函数(在下面的代码中表示为“expensive_function”,位于 matlabpath 中)。变量“x_sol”保存“fsolve”返回的解。
问题是,在主代码中,我需要访问由昂贵函数计算的“other_results”结构以进行进一步计算。使用解值重新计算 'other_results' 结构是很浪费的(例如在 'main' 中使用以下代码行)
other_results = expensive_function(x_sol,param);
有没有办法在不重新评估昂贵函数的情况下访问这个结构?
PS:在我的整个职业生涯中,我一直被警告不要使用全局/持久变量,到目前为止我一直远离它们。我不知道这是否是解决此问题的唯一方法,还是存在更好/更聪明的方法?
%% 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