MATLAB/OCTAVE Extracting elements from different sized vectors in a cell array

后端 未结 5 758
旧巷少年郎
旧巷少年郎 2021-01-13 21:40

I have a simple question but I can\'t figure it out or find it anywhere. I have a cell array where c{1} is a vector and c{2} is a vector but of different lengths, up to c{i

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-13 22:22

    In Matlab; without loops:

    1. If the cell array contains column vectors and you want to arrange them into one big column vector:

      result = vertcat(c{:}); %// vertically concat all vectors
      

      Example:

      >> c = {[1;2], [1;2;3]};
      >> result = vertcat(c{:})
      result =
           1
           2
           1
           2
           3
      
    2. If the cell array contains row vectors, you can arrange them as rows of a matrix, filling non-existent values with NaN (or any other value):

      M = max(cellfun(@numel, c)); %// max length of vectors
      c2 = cellfun(@(row)[row NaN(1,M-numel(row))], c, 'uni', 0); %// fill with NaN
      result = vertcat(c2{:}); %// concat all equal-size row vectors into a matrix
      

      Example:

      >> c = {[1 2], [1 2 3]};
      >> M = max(cellfun(@numel, c));
      >> c2 = cellfun(@(row)[row NaN(1,M-numel(row))], c, 'uni', 0);
      >> result = vertcat(c2{:})
      result =
           1     2   NaN
           1     2     3
      

提交回复
热议问题