【问题标题】:MATLAB preallocating space to unroll different size matrices from cell arraysMATLAB 预分配空间以从元胞数组展开不同大小的矩阵
【发布时间】:2015-10-02 12:56:49
【问题描述】:

我正在尝试为我的 for 循环分配空间,但它不起作用。

我查看了所有类似的问题和 matlab 帮助,但没有任何区别。我一定是错过了什么。

xt = [];
yt = [];

for ii = 1:size(result,1)
        x = result{ii,1}(:,1);
          xt = [xt;x];
        y = result{ii,1}(:,2);
          yt = [yt;y];
end

而我为 xt 预先整理空间的尝试是

xt = zeros(size(result,1),1);

没有结果。我想我的问题可能是result 是一个单元格数组??

【问题讨论】:

  • 什么是x,是标量还是数组?
  • x 是一个非标量数组

标签: arrays matlab memory


【解决方案1】:

如果您连接,则不需要预先分配。如果您预先分配,请不要连接!

 xt = [xt;x]; 

上一行将采用xt,将在其末尾添加x 数量的NEW 值,附加。它不会替换 xt 的值。

为了能够为不同大小的元胞数组分配内存,您需要知道每个元胞数组的元素数。

sizes=zeros(size(result,1),1);
for ii=1:size(result,1)
    sizes(ii)=size(result{ii},1);  %//get the size of the matrix
end
%// now we know the sizes

xt=zeros(sum(sizes),1); %the total number is the sum of each of them

%// handle the first special case
xt( 1:sizes(1) )=result{1,1}(:,1);
%// add the rest
for ii = 2:size(result,1)
    xt( 1+sum(sizes(1:ii-1)) : sum(sizes(1:ii)) )= result{ii,1}(:,1);
end

【讨论】:

  • 结果是 ,里面的矩阵是
  • @user3536870 matlab 矩阵的问题是, 不是有效维度!您希望如何将数据放在简短的xt 中?
  • 刚刚注意到 x 实际上是一个数组,而且元胞数组中的矩阵大小各不相同,但都是 x2
  • @user3536870 最好的办法就是不预先分配内存。
  • 但是当读取数百万的数据时,这需要很长时间,对吧?这是我尝试预分配以加快速度的目的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
  • 2021-07-08
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
相关资源
最近更新 更多