How to create a multidimensional matrix from a cell array where the cell array sizes are not he same?
Show older comments
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 Comments
Azzi Abdelmalek
on 22 Jul 2016
your example is not clear. Post a usable example
Andrei Bobrov
on 22 Jul 2016
Edited: Andrei Bobrov
on 22 Jul 2016
? please example:
C{1,3} = {[12 21 3], [43 45 66]};
or
C{1,3} = [12 21 3; 43 45 66] ?
Amulya NV
on 22 Jul 2016
Andrei Bobrov
on 22 Jul 2016
? 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
on 22 Jul 2016
Andrei Bobrov
on 22 Jul 2016
Please see my answer.
Accepted Answer
More Answers (1)
Walter Roberson
on 22 Jul 2016
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.)
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!