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 !
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)