Concatenated cell array vectors in matlab

In Matlab, I have an array of 4x5 cells, where each cell consists of a 121x1 vector.

What is the easiest way to create a 3x 4x5x121 matrix, avoiding a double cycle.

+7
source share
4 answers

One way (not necessarily the fastest)

%# 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); 
+7
source

Let's pretend that

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

then usually i would say

 cat(3, A{:}) 

but this will give a 121 by 1 by 20 matrix. For your case an additional 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 

therefore, the cell2mat command cell2mat almost 5 times slower than the reshape extension. Use what works best for your business.

+4
source

The answers of Jonas and Rodi are, of course, beautiful. A slight performance improvement is to reshape your vectors in cells, rather than permute them to:

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

And, of course, the fastest, if you can remove the requirements regarding output sizes, just concatenate the cell vectors and reformat

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

which gives the matrix [121 x 4 x 5] .

+1
source

How about this, avoiding cellfun :

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

They did not compare speed with other offers.

0
source

All Articles