我有一个带有一组变量(例如var1
、var2
、var3
、var4
、var5
和)var6
的工作区。var7
有一个 .m 函数(使用包含toassignin('base',...)
的默认值。用户将打开 Matlab 并运行此函数,以便将变量及其默认值添加到工作区。之后用户可能会更改某些变量的值甚至删除一些变量。var1
var7
现在,如果用户更改了变量值并且他再次运行该函数,我不希望默认值覆盖用户输入的新值。
这是我到目前为止所拥有的:
S = evalin('base','whos');
listWorkspaceVar = {S.name};
compareCellArrayList = ismember(listWorkspaceVar, listParam); % logical vector, listParam is the list of variables in the function assigning the default values, so here listParam would be = {'var1' 'var2' 'var3' 'var4' 'var5' 'var6' 'var7'})
if any(compareCellArrayList) % check if there is at least one declared variable in the base workspace
tempWorkspaceVarVal = cell(sum(compareCellArrayList),2); % Pre-allocating, 1 column for the variable name and 1 column for the variable value
jj = 1;
for ii = 1:size(S,1)
if compareCellArrayList(1, ii)
tempWorkspaceVarVal(jj,:) = {listWorkspaceVar{1, ii}, ...
evalin('base',listWorkspaceVar{1, ii})};
jj = jj + 1;
end
end
theDefaultValueFunction() % The function that assignin the default values
cellfun(@(x,y) assignin('base', x, y), ...
tempWorkspaceVarVal(:,1), tempWorkspaceVarVal(:,2)) % Overwrite with the temp values in order to keep the new entered values
end
如果我不想更改默认值中的函数分配,我的方法是保留新修改的变量值的最佳方法吗?