【问题标题】:Accumulating different sized column vectors stored as a cell array into a matrix padded with NaNs将存储为单元阵列的不同大小的列向量累积到填充有 NaN 的矩阵中
【发布时间】:2023-04-06 09:37:01
【问题描述】:

假设我在一个数组中有一系列不同大小的列向量,并希望通过用NaN 填充空白空间将它们组合成一个矩阵。我该怎么做?

已经有一个非常相似的问题(accumulate cells of different lengths into a matrix in MATLAB?)的答案,但是该解决方案处理的是行向量,而我的问题是列向量。一种可能的解决方案是转置每个阵列组件,然后应用上述解决方案。但是,我不知道该怎么做。

另外,速度也是一个问题,所以如果可能的话,请考虑到这一点。

【问题讨论】:

    标签: arrays matlab


    【解决方案1】:

    您可以稍微调整 that answer you found 以适用于列:

    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
    

    或者您可以调整 this 作为替代方案:

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

    【讨论】:

    • 谢谢,它成功了。我不能投票给你,因为我没有足够的积分,但我保证我会的。感谢您的快速回答!
    【解决方案2】:

    如果您想提高速度,cell 数据结构就是您的敌人。对于这个例子,我假设你将这个向量存储在一个名为 vector_holder 的结构中:

    elements = fieldnames(vector_holder);
    
    % Per Dan request
    maximum_size = max(structfun(@max, vector_holder));
    
    % maximum_size is the maximum length of all your separate arrays
    matrix = NaN(length(elements), maximum_size);
    
    for i = 1:length(elements)
        current_length = length(vector.holder(element{i}));
        matrix(i, 1:current_length) = vector.holder(element{i});
    end
    

    许多 Matlab 函数在处理 cell 变量时速度较慢。此外,带有N 双精度元素的cell 矩阵比带有N 元素的双精度矩阵需要更多的内存。

    【讨论】:

    • 你应该添加如何从vector_holder找到maximum_size
    • 你测试过maximum_size = max(structfun(@max, vector_holder))吗?在 Octave Online 上它给出了一个错误(错误 btw 让我相信 structfun 将在内部将您的结构转换为 cellarray 因此失去它可能拥有的任何内存优势。另外添加 'uni',false 没有帮助),但它可能在 Matlab 中工作 - 请确认。
    • @Dan 甚至可以摆脱 for 循环,但代码看起来很糟糕。
    • @Dan 是的,它在 Matlab 中工作。很遗憾,我无法访问 Octave。
    • +1 那么,我现在无法访问 Matlab,这就是我检查 Octave Online 的原因。我想这是两种语言不同的情况之一。
    猜你喜欢
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2016-10-25
    相关资源
    最近更新 更多