我可以从工作区B中清除工作区A中的持久变量吗? [英] Can I clear a persistent variable in workspace A from workspace B?
问题描述
我有一个带有GUI的脚本,该脚本加载一个数据块,然后使用lsqnonlin
对数据的每一行进行非线性拟合.模型函数需要一些辅助计算(权重函数,表查找等),这些计算在迭代之间不会改变,因此我从一开始就对其进行计算,然后将其存储在持久变量中.到目前为止一切顺利.
I have a script with a GUI that loads in a block of data and then performs a nonlinear fit to each row of the data using lsqnonlin
. The model function requires some ancillary calculations (weight functions, table lookups, etc.) that don't change between iterations, so I calculate them at the very beginning and then store them in persistent variables. So far so good.
但是,一旦我将控制权返回给我的GUI并希望适合下一组数据,这些持久变量仍然存在,并且可能不适用于下一个数据集.我尝试将一个标志传递给我的拟合函数,以使其知道是否要清除.我当前的代码如下所示(大大简化了):
However, Once I return control to my GUI and want to fit the next set of data, those persistent variables are still there, and may not be appropriate for the next dataset. I tried passing a flag to my fitting function to let it know whether to clear. My current code looks something like this (greatly simplified):
constants.firstRun = true;
constants.otherStuff = [other stuff I need for fit];
for k = 1:K
data = load(dataFile(k))
[N,M] = size(data);
if k == 1
normalizedIndex = linspace(0,1,N);
end
for m = 1:M
dataToFit = data(:,m)
constants.dataToFit = dataToFit;
if k == 1 && m == 1
Ao = estimateStartingParameters(normalizedIndex,dataToFit);
else
Ao = A;
end
nlFitFun = @(ao) modelFunction(ao,normalizedIndex,constants);
A = lsqnonlin(nlFitFun,Ao);
% do things with A like calculate, plot, save etc.
constants.firstRun = false;
end
end
然后模型函数看起来像
function Y = modelFunction(ao,normalizedIndex,constants)
persistent Z
if constants.firstRun
Z = longCalculation(constants.otherStuff);
end
X = calculation(ao,Z,normalizedIndex);
Y = fullModel(ao,X,constants) - constants.dataToFit;
这里的问题是,对于第一次拟合,constants.firstRun
始终为true,因此它总是 在设置之前计算Z
.
The problem here is that for the first fit, constants.firstRun
is always true, so it always calculates Z
, before being set.
问题是,有没有一种方法可以进入函数以清除主脚本中的持久变量?我想到的另一个选择是将持久性变量添加到constants
结构变量中,但是Z
很大(这被简化了,实际上有多个持久性变量).将大变量传入和传出函数时,是否存在内存或其他开销问题?为此,实际上我是否通过使用持久变量而不是每次都将变量传递给函数来获得任何收益?
The question is, is there a way to reach into the function to clear the persistent variables from the main script? The other option I thought of was to just add the persistent variables to the constants
structure variable, but Z
is large (and this is simplified, there are actually multiple persistent variables). Are there memory or other overhead issues when passing a large variable into and out of a function? For that matter, do I actually gain anything by using persistent variables rather than passing the variables into the function each time?
推荐答案
Take a look at clear
. If you pass it the name of a function, it will reinitialize all persistent variables within the function.
这篇关于我可以从工作区B中清除工作区A中的持久变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!