0
votes

I am trying to convert a cell array with cell contents different sizes into a matrix. I have tried the following code (from a previous question):

tcell = {[1,2,3], [1,2,3,4,5], [1,2,3,4,5,6], [1], []};  %# Sample array
maxSize = max(cellfun(@numel,tcell));    %# Get the maximum vector size
fcn = @(x) [x nan(1,maxSize-numel(x))];  %# Create an anonymous function
rmat = cellfun(fcn,tcell,'UniformOutput',false);  %# Pad each cell with NaNs
rmat = vertcat(rmat{:})                  %# Vertically concatenate cells

I get the following error code :

Dimensions of matrices being concatenated are not consistent.

Error in @(x)[x,nan(1,maxSize-numel(x))]

I think my cell array is different in content from the test example (see tell) : The content of my cell array(1x31 cell) when viewing in MATLAB is

30x1 cell    40x1 cell    37x1 cell 

Do I have to do another conversion of my cell array first ? How do I convert my cell array into the form of tcell ?

I have been searching for some time now but I am not yet familiar with all the terminology. The solution can be simple, but I don't have the knowledge yet to see it. All inputs are welcome !

2
How do you want to concatenate them? What is the size of the expected output? - Andras Deak
You have to transpose your content within the cells. The piece of code works only for line vectors. - marsei
@marsei has the solution: you either have to transpose the cells, or write your anonymous function with column vector output (@(x)[x; nan(...)]). - Andras Deak
Does vertcat(tcell{:}) not work? - Dan
Nice one-you can post your comment as an answer and accept it! - marsei

2 Answers

1
votes

Actually your original code was almost perfect, but for line vectors. For column vectors in a cell you missed a semicolon.

    maxSize = max(cellfun(@numel,tcell));    %# Get the maximum vector size
    fcn = @(x) [x ; nan(1,maxSize-numel(x))];  %# semicolon here                
    rmat = cellfun(fcn,tcell,'UniformOutput',false);  %# Pad each cell with NaNs
0
votes

I found the following answer thanks to the input of the commentators:

A = cellfun(@transpose,Arad,'UniformOutput',false); %transpose the cell array
maxSize = max(cellfun(@numel,A)); %# Get the maximum vector size 
fcn = @(x) [x nan(1,maxSize-numel(x))]; %# Create an anonymous function rmat = cellfun(fcn,A,'UniformOutput',false); %# Pad each cell with NaNs 
rmat = horzcat(rmat{:}) ; % concatenate horizontally 
rmat = horzcat(rmat{:}) ; % concatenate horizontally again 
rmat = reshape(rmat,maxSize, []);% reshape to m(=maxsize)x n(determined by total number of elements/number of rows(maxsize)