在不知道大小的情况下在Matlab中预分配空间? [英] Preallocating the space in Matlab without knowing the size?
本文介绍了在不知道大小的情况下在Matlab中预分配空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在通过在循环过程中串联每次迭代的结果来在Matlab中构造向量X
.
I am constructing a vector X
in Matlab by concatenating the outcomes of each iteration in a loop procedure.
我现在正在做的是
X=[];
for j=1:N
%do something that delivers a vector A
%X=[X;A]
end
不可能先验地预测A的大小.有什么方法可以预分配空间?
It is not possible to predict a priori the size of A. Is there any way in which I can preallocate the space?
推荐答案
可能的解决方案:
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{:});
这篇关于在不知道大小的情况下在Matlab中预分配空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文