7

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

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

4

4 回答 4

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);
于 2012-10-22T09:49:37.843 回答
4

Suppose

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

then normally I would say

cat(3, A{:})

but that would give a 121-by-1-by-20 array. For your case, an extra step is needed:

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

or, alternatively,

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

although

>> 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

so the command cell2mat is almost 5 times slower than the reshape of the expansion. Use whichever seems best suited for your case.

于 2012-10-22T09:54:15.847 回答
1

乔纳斯和罗迪的答案当然很好。一个小的性能改进是对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]矩阵。

于 2012-10-22T10:12:05.287 回答
0

怎么样,避免cellfun

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

不过,还没有将速度与其他建议进行比较。

于 2012-10-22T18:36:03.797 回答