【问题标题】:How can I accumulate cells of different lengths into a matrix in MATLAB?如何在 MATLAB 中将不同长度的单元格累积到矩阵中?
【发布时间】:2011-03-04 12:33:57
【问题描述】:

所以,我有一个由不同长度的 1xN 向量组成的元胞数组。我想将它们附加到矩阵中,以便可以使用imagesc 显示它们。显然矩阵必须是最大向量的宽度。我目前的代码如下:

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

有人知道此类问题的矢量化解决方案吗?由于 MATLAB 的 JIT,我并不真正担心这个循环的速度。我只是想扩展我的知识,这是我在编程中经常遇到的一个案例。

【问题讨论】:

    标签: matlab matrix cell-array


    【解决方案1】:

    这是一种使用cellfunanonymous function 的解决方案,首先用NaN 值填充每个单元格,然后vertcat 将单元格内容放入矩阵中:

    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
    

    还有输出:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      相关资源
      最近更新 更多