Ale*_*lex 1 matlab matlab-struct
例如
test = struct('one', [1;2;3], 'two', [4;5;6]);
Run Code Online (Sandbox Code Playgroud)
我想垂直连接结构中的向量test.例如,如果它被定义为单元格数组test = {[1;2;3], [4;5;6]},我可以这样做vertcat(test{:}).但是,如果是结构,则vertcat(test{:})返回struct对象test.
我想有一个解决方案,不涉及使用创建临时单元阵列struct2cell.
你想要做的是实际使用struct2array然后展平结果.
A = reshape(struct2array(test), [], 1);
% 1
% 2
% 3
% 4
% 5
% 6
Run Code Online (Sandbox Code Playgroud)
作为一项后续行动,我已经进行比较的使用基准的一点点struct2cell来struct2array.我们希望该cell2mat(struct2cell())方法更慢,因为1)它在单元阵列上运行; 2)它使用单元数组而不是数字数组,这是众所周知的慢速.这是我用来执行测试的脚本.
function tests()
sizes = round(linspace(100, 100000));
times1 = zeros(size(sizes));
times2 = zeros(size(sizes));
for k = 1:numel(sizes)
sz = sizes(k);
S = struct('one', rand(sz, 1), 'two', rand(sz, 1));
times1(k) = timeit(@()cellbased(S));
times2(k) = timeit(@()arraybased(S));
end
figure;
plot(sizes, cat(1, times1 * 1000, times2 * 1000));
legend('struct2cell', 'struct2array')
xlabel('Number of elements in S.a and S.b')
ylabel('Execution time (ms)')
end
function C = cellbased(S)
C = cell2mat(struct2cell(S));
end
function C = arraybased(S)
C = reshape(struct2array(S), [], 1);
end
Run Code Online (Sandbox Code Playgroud)
结果(R2015b)