【问题标题】:preallocation of memory in matlab / octave [closed]matlab / octave中的内存预分配[关闭]
【发布时间】:2013-11-14 06:21:18
【问题描述】:

我为一个大数组预分配内存,但是新数据附加在数组的末尾而不是覆盖数据我该如何解决这个问题。所以我可以为一个大数组预分配内存。

注意数组是 44101x5001 我只是在示例中使用了较小的数字。

例子:

clear all
xfreq=zeros(10,10); %allocate memory

for ww=1:1:10
     xfreq_new = xfreq(:,1)+1+ww;
     xfreq=[xfreq xfreq_new]; %would like this to over write and append the new data where the preallocated memory of zeros are instead of appending to the end of it.
end

如果您运行它,您会注意到它会附加一个而不是覆盖零。

阿罗哈 瑞克

希望这能更好地解释事情 分配的数组

1)分配的零内存

[0 0 0 0 0
0 0 0 0 0
0 0 0 0 0]

2) 用数字覆盖分配的零内存,数字可以是任何东西,而不仅仅是数字一,我以数字一为例

[1 0 0 0 0
1 0 0 0 0
1 0 0 0 0]

3) 仍然用数字覆盖分配的内存零,数字可以是任何东西,而不仅仅是数字一,我以数字一为例

[1 1 0 0 0
1 1 0 0 0
1 1 0 0 0]

问题在于这一行 xfreq=[xfreq xfreq_new]; %would like this to over write and append the new data where the preallocated memory of zeros are instead of appending to the end. 结束

【问题讨论】:

  • 我不明白你在做什么。您打算覆盖预分配数组的哪一部分?
  • @C.R.带有所有零的 xfreq 将被 for 循环中 xfreq_new 的新值覆盖
  • xfreq(:,1) = xfreq(:,1)+1+ww?不可能说出你想做什么。您分配 501 列然后总是为第一列和 1,...,10 进行迭代?
  • 您编写了一个不使用迭代器ww 的循环,并且似乎没有输入数据。我不明白你的代码应该做什么。
  • 您对“覆盖和追加”的使用是荒谬的。两者是互斥的。 “覆盖”是替换现有值。 “追加”是通过在某个维度上扩展矩阵来添加新值。如果您不想追加,请不要使用xfreq=[xfreq xfreq_new]。正如@FKaria 在评论中建议的那样,您应该只替换原始矩阵的值xfreq

标签: arrays matlab multidimensional-array octave


【解决方案1】:

如果您希望所有条目都等于x,这将起作用

  x = (some number)
  A = zeros(10,n)
  for i=1:n
    A(:,i) = x;
  end

如果您希望您的列等于其他列,您必须这样做

  A = zeros(10,n)
  for i=1:n
    A(:,i) = v;
  end

其中 v 是大小为 (10,1) 的向量

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 2018-12-08
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多