在MatLab中,我有一个尺寸为22 x 4的矩阵SimC。我使用for
循环将该矩阵重新生成10次。
我想最后得到一个U
包含SimC(1)
在第1至22SimC(2)
行,第23至45行等的矩阵。因此,U的末端尺寸应为220 x 4。
谢谢!!
编辑:
nTrials = 10;
n = 22;
U = zeros(nTrials * n , 4) %Dimension of the final output matrix
for i = 1 : nTrials
SimC = SomeSimulation() %This generates an nx4 matrix
U = vertcat(SimC)
end
不幸的是,上述方法不起作用,因为它U = vertcat(SimC)
只能返回SimC
而不是连接。
vertcat
是一个不错的选择,但是它将导致矩阵的增长。在大型程序上,这不是一个好习惯,因为它确实会降低速度。但是,在您遇到的问题中,您不会循环太多,所以vertcat
很好。
使用时vertcat
,您不会预先分配U
矩阵的全部最终大小...只是创建一个empty U
。然后,在调用时vertcat
,需要给它两个要连接的矩阵:
nTrials = 10;
n = 22;
U = [] %create an empty output matrix
for i = 1 : nTrials
SimC = SomeSimulation(); %This generates an nx4 matrix
U = vertcat(U,SimC); %concatenate the two matrices
end
既然您已经知道最终大小,那么执行此操作的更好方法是预先分配您的全部内存U
(如您所做的那样),然后U
通过计算正确的索引将值放入。像这样:
nTrials = 10;
n = 22;
U = U = zeros(nTrials * n , 4); %create a full output matrix
for i = 1 : nTrials
SimC = SomeSimulation(); %This generates an nx4 matrix
indices = (i-1)*n+[1:n]; %here are the rows where you want to put the latest output
U(indices,:)=SimC; %copies SimC into the correct rows of U
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句