假设a
定义为以下结构。我试图找到与 R 的 dput 等效的命令,但犯了 here 。例如,我知道下面的形式必须是 struct('const',1,'terms',{{struct(),struct()}})
但我不知道结构内存储了什么内容,而无需使用 here 等命令进行检查,耗时。
那么通过哪个命令我可以看到在Matlab中生成结构体的原始命令?
>> a
a =
const: 1
terms: {[1x1 struct] [1x1 struct]}
最佳答案
评论
Is it possible for you to switch from using a structure to a class? If so you could make one that mimics the struct, and each time it is modified call stack = dbstack to get the stack - then store the stack along with the change. The command that made the change could then be retrieved automatically later from the line numbers in the stack.
作为评论中对此的后续请求,这里是一个提供结构功能并保留其分配记录的类的示例:
classdef utstruct
properties (SetAccess = private)
modifications
end
properties (Dependent, SetAccess = private)
myStruct
end
properties (Access = private)
m_struct
end
methods
function self = utstruct(varargin)
if nargin > 0
self.m_struct = builtin('struct', varargin{:});
else
self.m_struct = builtin('struct');
end
% Should update self.modifications here
end
function B = subsref(self, s)
if any(strcmp(s(1).subs, properties(self)))
B = builtin('subsref', self, s);
else
B = subsref(self.m_struct, s);
end
end
function A = subsasgn(self, s, b)
self.m_struct = subsasgn(self.m_struct, s, b);
newMod = builtin('struct');
newMod.type = 'subsasgn';
newMod.modData = {s b};
newMod.stack = dbstack;
self.modifications = [self.modifications; newMod];
A = self;
end
function disp(self)
disp(self.m_struct);
end
function names = fieldnames(self, varargin)
names = fieldnames(self.m_struct, varargin{:});
end
function C = cat(self, dim, varargin)
uts = cellfun(@(x)isa(x, 'utstruct'), varargin);
varargin{uts} = cellfun(@(x)x.m_struct, varargin(uts));
varargin = [{self.m_struct} varargin];
self.m_struct = cat(dim, varargin{:});
% Should update self.modifications here
C = self;
end
function C = horzcat(self, varargin)
C = self.cat(1, varargin{:});
end
function C = vertcat(self, varargin)
C = self.cat(2, varargin{:});
end
function value = get.myStruct(self)
value = self.m_struct;
end
end
end
您应该添加一些代码来在发生初始化/串联操作时更新修改数组。
subsref
和 subsasgn
重写是这里的关键点,使其表现得像一个结构体(通过将所有事件推迟到实际的结构体),但其他重写如fieldnames
和 disp
做同样的事情。在 subsasgn
中,保存了对结构体的所有赋值的记录,以及生成赋值的堆栈。
注意:为了与内置struct
完全兼容,您可能应该重写一些方法,但这应该足以让您开始。请参阅Subclassing MATLAB Built-In Types .
编辑:我让这个例子变得更加健壮。它现在是一个值类 - 正如它应该的那样 - 并且可以与串联一起使用。
编辑:您可以通过重新定义函数 struct
来避免使用查找和替换来重构现有的 struct(...)
调用>:
function s = struct(varargin)
% STRUCT Overrides default struct function to provide unit-testable structs
%
% Set global variable unitTestStructEnabled to true to enable this
% function.
%
global unitTestStructEnabled;
if isempty(unitTestStructEnabled)
unitTestStructEnabled = false;
end
if unitTestStructEnabled
s = utstruct(varargin{:});
else
s = builtin('struct', varargin{:});
end
您可能不希望它一直在您的路径上徘徊,因为当您第一次创建结构时您会收到警告(您可以将其关闭,但这可能会隐藏其他问题),所以您可能应该将其放在通常不在路径中的文件夹中,并暂时将其添加到单元测试的路径中(addpath
/rmpath
)。
关于matlab - 如何找到Matlab中某个结构体执行的命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15985647/