首页 文章

在不知道尺寸的情况下在Matlab中预先分配空间?

提问于
浏览
2

我通过在循环过程中连接每个迭代的结果在Matlab中构造一个向量 X .

我现在正在做的是

X=[];
for j=1:N
    %do something that delivers a vector A
    %X=[X;A]
end

不可能事先预测A的大小 . 有没有什么方法可以预先分配空间?

1 回答

  • 6

    可能的解决方案:

    A=cell(1,N); %Pre-allocating A instead of X as a cell array
    for k=1:N    %I changed the name of loop variable since `j` is reserved for imag numbers
      %Here I am generating a matrix of 5 columns and random number of rows. 
      %I kept number of columns to be constant (5) because you used X=[X;A] 
      %in the question which means number of columns will always be same
      A{k} =  rand(randi([1,10],1,1),5); %doing something that delivers a vector A   
    end
    X = vertcat(A{:});
    

相关问题