Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I accumulate cells of different lengths into a matrix in MATLAB?

So, I have a cell-array of 1xN vectors of different lengths. I want to append them into a matrix so I can display them with imagesc. Obviously the matrix must be the width of the largest vector. My current code for this is below:

tcell = {[1,2,3], [1,2,3,4,5], [1,2,3,4,5,6], [1], []};
lens = cellfun('length', tcell);
rmat = NaN(length(tcell), max(lens));
for i = 1:length(tcell)
    rmat(i, 1:lens(i)) = tcell{i};
end

Does anyone know a vectorized solution for this type of problem? I'm not really worried about the speed of this loop because of MATLAB's JIT. I'm just trying to expand my knowledge and this is a case that I come across quite often in my programming.

like image 255
JudoWill Avatar asked Jun 16 '10 14:06

JudoWill


People also ask

How do you accumulate data in MATLAB?

B = cumsum( A , dim ) returns the cumulative sum of the elements along dimension dim . For example, if A is a matrix, then cumsum(A,2) returns the cumulative sum of each row. B = cumsum(___, direction ) optionally specifies the direction using any of the previous syntaxes.

How do you create an array of rows and columns in MATLAB?

To create an array with multiple elements in a single row, separate the elements with either a comma ',' or a space. This type of array is called a row vector. To create an array with multiple elements in a single column, separate the elements with semicolons ';'. This type of array is called a column vector.


1 Answers

Here's one solution that uses cellfun with an anonymous function to first pad each cell with NaN values, then vertcat to put the cell contents into a matrix:

tcell = {[1 2 3], [1 2 3 4 5], [1 2 3 4 5 6], [1], []};  % Sample cell 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

And the output:

rmat =

     1     2     3   NaN   NaN   NaN
     1     2     3     4     5   NaN
     1     2     3     4     5     6
     1   NaN   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN   NaN   NaN
like image 146
gnovice Avatar answered Sep 29 '22 11:09

gnovice