有没有一种方法可以将MATLAB工作区推入堆栈? [英] Is there a way to push a MATLAB workspace onto a stack?

查看:122
本文介绍了有没有一种方法可以将MATLAB工作区推入堆栈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道MATLAB中是否可以有一个工作区堆栈吗?至少可以这样说,这将非常方便.

Does anyone know if it's possible to have a stack of workspaces in MATLAB? It would be very convenient, to say the least.

我需要这个来进行研究.我们有几个脚本以有趣的方式进行交互.函数具有局部变量,但没有脚本...

I need this for research. We have several scripts which interact in interesting ways. Functions have local variables, but not scripts...

推荐答案

常规Matlab函数调用堆栈本身就是工作区的堆栈.仅使用函数是使用函数的最简单方法,而Matlab的写时复制功能则使这种方法相当有效.但这可能不是您要问的.

The regular Matlab function call stack is itself a stack of workspaces. Just using functions is the easiest way to use one, and Matlab's copy-on-write makes this reasonably efficient. But that's probably not what you're asking.

在工作空间和结构之间存在自然的对应关系,因为相同的标识符对于变量名和结构字段有效.它们本质上都是标识符=> Mxarray映射.

There's a natural correspondence between workspaces and structs, since the same identifiers are valid for variable names and struct fields. They're both essentially identifier => Mxarray mappings.

您可以使用whosevalin将工作空间状态捕获到结构中.使用单元向量实现它们的堆栈. (一个struct数组将不起作用,因为它需要同质的字段名称.)可以将堆栈存储在appdata中,以防止其出现在工作空间中.

You can use whos and evalin to capture workspace state to a struct. Use a cell vector to implement a stack of them. (A struct array won't work because it requires homogeneous field names.) The stack could be stored in appdata to prevent it from appearing in a workspace itself.

这是这项技术的推入式和弹出式功能.

Here are push and pop functions for this technique.

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

这篇关于有没有一种方法可以将MATLAB工作区推入堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆