我正在Matlab中构建一个向量X
,它通过在循环过程中连接每个迭代的结果。
我现在正在做的是
X=[];
for j=1:N
%do something that delivers a vector A
%X=[X;A]
end
不可能预先确定A的大小。有没有什么方法可以预先分配空间?
答案 0 :(得分: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{:});