使用单线动态结构参考展平MATLAB结构

时间:2016-10-06 14:50:26

标签: matlab structure

我有以下结构:

myStruct.A.var = 'abc';
myStruct.B.var = '123';
myStruct.C.var = 7;
...

我正在寻找一种压缩(1-2行)平面结构的方法,以便将'var'子域的所有值都作为:

flattened_var = {'abc', '123', 7}

例如,类似下面的行(遗憾地不起作用):

inBetweenFields = {'A', 'B', 'C'};
flattened_var   = myStruct.(inBetweenFields{:}).var;

2 个答案:

答案 0 :(得分:3)

简单循环绰绰有余:

% Set up data
myStruct.A.var = 'abc';
myStruct.B.var = '123';
myStruct.C.var = 7;

% Extract data
substructs = fieldnames(myStruct);  % Get substructure names
nsubs = numel(substructs);  % Get number of substructures
flatteneddata = cell(nsubs, 1);  % Preallocate cell array

% Extract data
for ii = 1:nsubs
    flatteneddata{ii} = myStruct.(substructs{ii}).var;
end

这也可以使Twitter与cellfun兼容,这几乎总是比等效循环慢。

% Set up data
myStruct.A.var = 'abc';
myStruct.B.var = '123';
myStruct.C.var = 7;

flatteneddata = cellfun(@(x) myStruct.(x).var, fieldnames(myStruct), 'UniformOutput', false);

两种方法都会产生所需的输出:

flatteneddata =

  3×1 cell array

    'abc'
    '123'
    [  7]

答案 1 :(得分:2)

试试这个:

cellfun(@struct2cell,struct2cell(myStruct))