有谁知道在MATLAB中是否可以拥有一堆工作空间?至少可以这样说非常方便。
我需要这个用于研究。我们有几个脚本以有趣的方式进行交互。函数有局部变量,但没有脚本......
答案 0 :(得分:25)
常规的Matlab函数调用堆栈本身就是一堆工作空间。只使用函数是使用函数的最简单方法,而Matlab的copy-on-write使其效率相当高。但那可能不是你要问的。
工作空间和结构之间存在自然对应关系,因为相同的标识符对变量名和结构域有效。它们本质上都是标识符=> Mxarray映射。
您可以使用whos
和evalin
将工作区状态捕获到结构中。使用单元格向量来实现它们的堆栈。 (结构数组不起作用,因为它需要同类字段名。)堆栈可以存储在appdata中,以防止它出现在工作区本身。
这是此技术的推送和弹出功能。
function push_workspace()
c = getappdata(0, 'WORKSPACE_STACK');
if isempty(c)
c = {};
end
% Grab workspace
w = evalin('caller', 'whos');
names = {w.name};
s = struct;
for i = 1:numel(w)
s.(names{i}) = evalin('caller', names{i});
end
% Push it on the stack
c{end+1} = s;
setappdata(0, 'WORKSPACE_STACK', c);
function pop_workspace()
% Pop last workspace off stack
c = getappdata(0, 'WORKSPACE_STACK');
if isempty(c)
warning('Nothing on workspace stack');
return;
end
s = c{end};
c(end) = [];
setappdata(0, 'WORKSPACE_STACK', c);
% Do this if you want a blank slate for your workspace
evalin('caller', 'clear');
% Stick vars back in caller's workspace
names = fieldnames(s);
for i = 1:numel(names)
assignin('caller', names{i}, s.(names{i}));
end
答案 1 :(得分:7)
听起来你想在变量的工作空间之间来回切换。我能想到的最佳方法是使用SAVE,CLEAR和LOAD命令在MAT文件和工作区之间来回移动变量集:
save workspace_1.mat %# Save all variables in the current workspace
%# to a .mat file
clear %# Clear all variables in the current workspace
load workspace_2.mat %# Load all variables from a .mat file into the
%# current workspace
答案 2 :(得分:0)
奇妙。 (Haven发现使用0和getappdata记录在任何地方......所以这可能会在将来消失。)添加推送& pop到我的util库,还有以下内容:
pop_workspace(keep_current)
% keep_current: bool: if true, current vars retained after pop
. . .
if (~keep_current)
evalin('caller','clear');
end
一点创造力,一个人只能保留选定的变量,并避免覆盖流行音乐。我发现我的工作中还需要以下功能:
function pull_workspace(names)
% pulls variablesin cell array names{} into workspace from stack without
% popping the workspace stack
%
% pulled variable will be a local copy of the stack's variable,
% so modifying it will leave the stack's variable untouched.
%
if (~exist('names','var') || isempty(names))
pull_all = true;
else
pull_all = false;
% if names is not a cell array, then user gave us
% just 1 var name as a string. make it a cell array.
if (~iscell(names))
names = {names};
end
end
% Peek at last workspace on stack
c = getappdata(0, 'WORKSPACE_STACK');
if isempty(c)
warning('Nothing on workspace stack');
return;
end
s = c{end};
% Stick vars back in caller's workspace
if (pull_all)
names = fieldnames(s);
end
for i = 1:numel(names)
assignin('caller', names{i}, s.(names{i}));
end
end