MATLAB预分配空间以从单元阵列中展开不同大小的矩阵

时间:2015-10-02 12:56:49

标签: arrays matlab memory

我正在尝试为我的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是一个单元格数组?

1 个答案:

答案 0 :(得分:2)

如果你连接,你不需要预先分配。如果你预先分配不要连接!

 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