How to create a multidimensional matrix from a cell array where the cell array sizes are not he same?

I have a cell array C
C{1,1} = {[1 2 3]}
C{1,2} = {[12 21 3]}
C{1,3} = {[12 21 3], [43 45 66]}
C{1,4} = {[2 5 1], [1 65 3], [32 5 1], [2 5 1]}
C{2,1} = {[1 2 3], [11 6 43], [1 5 1], [4 56 1]}
C{2,2} = {[12 21 3]}
C{2,3} = {[43 45 66]}
C{2,4} = {[1 65 3], [32 5 1], [2 5 1]}
C{3,1} = {[4 56 1]}
C{3,2} = {[12 21 3], [23 5 2], [2 4 2]}
C{3,3} = {[1 4 2], [43 45 66]}
C{3,4} = {[37 45 6]}
As can be seen, the cells are of different dimension. Each element of a cell has values like [x y z]
Now I want to convert this to a multidimensional matrix of dimension 3*4*4(in the above example) with the missing entries in the matrix to be [0 0 0].
C_New(1,1,:) = [1 2 3; 0 0 0; 0 0 0; 0 0 0]
C_New(1,2,:) = [12 21 3; 0 0 0; 0 0 0; 0 0 0]
C_New(1,3,:) = [12 21 3; 43 45 66; 0 0 0; 0 0 0]
C_New(1,4,:) = [2 5 1; 1 65 3; 32 5 1; 2 5 1]
.
.
.
.
C_New(3,1,:) = [4 56 1; 0 0 0; 0 0 0; 0 0 0]
C_New(3,2,:) = [12 21 3; 23 5 2; 2 4 2; 0 0 0]
C_New(3,3,:) = [1 4 2; 43 45 66; 0 0 0; 0 0 0]
C_New(3,4,:) = [37 45 6; 0 0 0; 0 0 0; 0 0 0]
what is the best way to do this? I want to do this because having a matrix makes it easy for me to vectorize my operations and gain speed. My actual cell arrays are much bigger (900*3600).
Any help is appreciated! :)

6 件のコメント

your example is not clear. Post a usable example
Andrei Bobrov
Andrei Bobrov 2016 年 7 月 22 日
編集済み: Andrei Bobrov 2016 年 7 月 22 日
? please example:
C{1,3} = {[12 21 3], [43 45 66]};
or
C{1,3} = [12 21 3; 43 45 66] ?
It is the fist one. Question edited
? maybe so:
C_New(:,:,1,1) = [1 2 3; 0 0 0; 0 0 0; 0 0 0];
.
.
C_New(:,:,3,3) = [1 4 2; 43 45 66; 0 0 0; 0 0 0]
Yes.. You are right!
Please see my answer.

サインインしてコメントする。

 採用された回答

Andrei Bobrov
Andrei Bobrov 2016 年 7 月 22 日
編集済み: Andrei Bobrov 2016 年 7 月 22 日
EDIT
n = cellfun(@numel,C);
nmx = max(n(:));
K = cellfun(@(x,y)[cat(1,x{:});zeros(nmx-y,3)],C,num2cell(n),'un',0);
CC = cat(3,K{:});
C_New = reshape(CC,[nmx,3,size(C)]);

その他の回答 (1 件)

Zpad3 = @(V) [V(:);zeros(3-length(V),1)];
Result = cell2mat(permute(cellfun(Zpad3, YourCell, 'Uniform', 0), [3 1 2]));
You might be able to do a little better on efficiency by using cat() to put portions together. You would look at the code for cell2mat and see if you could tweak it slightly so that you did not have to do the permute() while putting the slices together.
The permute() is there to reshape the array to be length 1 in the first dimension, ready to be expanded to length 3 by the length 3 column vector (column vector is occupied in the first dimension.)

カテゴリ

ヘルプ センター および File ExchangeMultidimensional Arrays についてさらに検索

タグ

質問済み:

2016 年 7 月 22 日

コメント済み:

2016 年 7 月 22 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by