在matlab中连接单元格数组的向量

时间:2012-10-22 09:46:18

标签: matlab matrix concatenation cell-array

在matlab中我有一个4x5单元阵列,其中每个单元由一个121x1向量组成。

创建3维4x5x121矩阵以避免2倍循环的最简单方法是什么。

4 个答案:

答案 0 :(得分:7)

一种方式(不一定是最快的)

%# convert all arrays in the cell array inCell to 1x1x121
permCell = cellfun(@(x)permute(x,[3,2,1]),inCell,'uniformOutput',false);

%# catenate
array = cell2mat(permCell);

答案 1 :(得分:4)

假设

A = cellfun(@(~)rand(121,1), cell(4,5), 'uniformoutput', false)

然后通常我会说

cat(3, A{:})

但这会产生一个121×1×20的阵列。对于您的情况,需要额外的步骤:

A = cellfun(@(x)permute(x,3,2,1), A, 'uniformoutput', false)
A = reshape([A{:}], size(A,1), size(A,2), size(A{1},3))

或者,

A = cellfun(@(x)permute(x,3,2,1), A, 'uniformoutput', false)
A = cell2mat(A);

虽然

>> start = tic;
>> for ii = 1:1e3
>>     B1 = reshape([A{:}], size(A,1), size(A,2), size(A{1},3)); end
>> time1 = toc(start);
>> 
>> start = tic;
>> for ii = 1:1e3
>>     B2 = cell2mat(A); end
>> time2 = toc(start);
>> 
>> time2/time1
ans = 
     4.964318459657702e+00

因此命令cell2mat几乎比扩展的reshape慢5倍。使用最适合您的情况。

答案 2 :(得分:1)

Jonas和Rody的回答当然很好。一个小的性能改进是reshape你的向量在单元格而不是permute它们:

permCell = cellfun(@(x)reshape(x,[1 1 numel(x)]), inCell, 'uni',false);
A = reshape([permCell{:}], [size(inCell) numel(inCell{1,1})]);

到目前为止最快,如果你可以放宽对输出维度的要求,只需简单地连接细胞载体并重塑

A = reshape([inCell{:}], [numel(inCell{1,1}) size(inCell)]);

产生[121 x 4 x 5]矩阵。

答案 3 :(得分:0)

如何做到这一点,避免cellfun

 output=permute(cell2mat(permute(input,[3 1 2])),[2 3 1]);

虽然没有将速度与其他建议进行比较。