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 comentarios

your example is not clear. Post a usable example
? 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]

Iniciar sesión para comentar.

 Respuesta aceptada

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)]);

Más respuestas (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.)

Categorías

Etiquetas

Preguntada:

el 22 de Jul. de 2016

Comentada:

el 22 de Jul. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by