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

别说谁变了你拦得住时间么 提交于 2019-11-26 13:46:01

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!