【问题标题】:MATLAB - Insert Rows Into A Much Larger Preallocated Zeros MatrixMATLAB - 将行插入到更大的预分配零矩阵中
【发布时间】:2013-11-04 18:54:03
【问题描述】:

我希望将可变行但不变的列数据垂直连接到一个“集合”矩阵中。

当动态扩展集合矩阵时,性能会变慢(原因很明显)。我想预先分配这个集合矩阵(清零),然后用新数据行逐渐覆盖零。我通常不知道我总共有多少行数据,所以我可能不得不超出矩阵大小然后修剪。

所以,我的问题是,如何才能有效地安全地做到这一点?

我目前预先分配了一个大的'ol 集合矩阵,然后保留一个名为“myMatrixPtr”的单独标量变量。它指向下一个空闲行。然后我这样插入:

myMatrix(myMatrixPtr:(myMatrixPtr+numOfNewRows)-1, :) = newRowData;

这很麻烦,我担心有一天早上我不会喝咖啡,我把事情搞砸了,覆盖错误的数据,事情爆炸等等。

有没有更简单的方法来做到这一点?我不想插入行,我想使用我已经拥有的并在必要时分配新的大块。但是,如果有更好的方法,我很想听听和学习。

感谢您的帮助!

【问题讨论】:

标签: matlab


【解决方案1】:

不,这几乎就是你的做法。唯一的补充是你实际上不需要让你的累积数组开始那么大,只要你有一个聪明的重新分配方案。我最喜欢的通常是在空间用完时将尺寸加倍。

下面是一个快速的端到端实现。

nCols = 4;
initSize = 1024;
ixNext = 1;

dataAccumulation = zeros(initSize, nCols);
collectionComplete = false;


while ~collectionComplete
    %Newly collected data
    newCollectedData = randn(ceil(rand*15),nCols);

    %Some row computations
    numOfNewRows = size(newCollectedData,1);
    ixLastInsertRow = ixNext+numOfNewRows-1;

    %Double the accumulation array if needed
    if size(dataAccumulation,1)<ixLastInsertRow
        dataAccumulation(size(dataAccumulation,1)*2,1)=0;
    end

    %Place the data and increment pointer
    dataAccumulation(ixNext:ixLastInsertRow, :) = newCollectedData;
    ixNext = ixLastInsertRow + 1;

    %Deterimine if we want to continue
    collectionComplete = (rand<0.001);
end

%Trim to size
dataAccumulation = dataAccumulation(1:(ixNext-1),:);

【讨论】:

猜你喜欢
  • 2013-08-14
  • 2016-01-26
  • 1970-01-01
  • 2011-04-08
  • 1970-01-01
  • 2013-09-22
  • 1970-01-01
  • 2016-06-02
  • 1970-01-01
相关资源
最近更新 更多