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 件のコメント
Azzi Abdelmalek
2016 年 7 月 22 日
your example is not clear. Post a usable example
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] ?
Amulya NV
2016 年 7 月 22 日
Andrei Bobrov
2016 年 7 月 22 日
? 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]
Amulya NV
2016 年 7 月 22 日
Andrei Bobrov
2016 年 7 月 22 日
Please see my answer.
採用された回答
その他の回答 (1 件)
Walter Roberson
2016 年 7 月 22 日
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 Exchange で Multidimensional Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!