Accumulating different sized column vectors stored as a cell array into a matrix padded with NaNs

前端 未结 2 1225
隐瞒了意图╮
隐瞒了意图╮ 2020-12-21 16:49

Imagine I have a series of different sized column vectors inside an array and want to group them into a matrix by padding the empty spaces with NaN. How can I d

2条回答
  •  清酒与你
    2020-12-21 17:22

    You can just slightly tweak that answer you found to work for columns:

    tcell = {[1,2,3]', [1,2,3,4,5]', [1,2,3,4,5,6]', [1]', []'};                      %\\ ignore this comment, it's just for formatting in SO
    maxSize = max(cellfun(@numel,tcell));    
    fcn = @(x) [x; nan(maxSize-numel(x),1)]; 
    cmat = cellfun(fcn,tcell,'UniformOutput',false);  
    cmat = horzcat(cmat{:}) 
    
    cmat =
    
         1     1     1     1   NaN
         2     2     2   NaN   NaN
         3     3     3   NaN   NaN
       NaN     4     4   NaN   NaN
       NaN     5     5   NaN   NaN
       NaN   NaN     6   NaN   NaN
    

    Or you could tweak this as an alternative:

    cell2mat(cellfun(@(x)cat(1,x,NaN(maxSize-length(x),1)),tcell,'UniformOutput',false))
    

提交回复
热议问题