在MatLab中的for循环内连接矩阵
在MatLab中,我有一个矩阵SimC,其尺寸为22 x4.我使用for
循环将该矩阵重新生成10次.
In MatLab, I have a matrix SimC which has dimension 22 x 4. I re-generate this matrix 10 times using a for
loop.
我想最后得到一个矩阵U
,该矩阵在第1至22行中包含SimC(1)
,在第23至45行中包含SimC(2)
,依此类推.因此,U的末端尺寸应为220 x 4.
I want to end up with a matrix U
that contains SimC(1)
in rows 1 to 22, SimC(2)
in rows 23 to 45 and so on. Hence U should have dimension 220 x 4 in the end.
谢谢!
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
而不是级联.
Unfortunately the above doesn't work as U = vertcat(SimC)
only gives back SimC
instead of concatenating.
vertcat
是一个不错的选择,但是它将导致矩阵的增长.在较大的程序上,这不是一个好习惯,因为它确实会降低速度.但是,在您遇到的问题中,您循环的次数不多,因此vertcat
很好.
vertcat
is a good choice, but it will result in a growing matrix. This is not good practice on larger programs because it can really slow down. In your problem, though, you aren't looping through too many times, so vertcat
is fine.
要使用vertcat
,您不会预先分配U
矩阵的完整最终大小...只是创建一个空的U
.然后,在调用vertcat
时,需要给它两个要连接的矩阵:
To use vertcat
, you would NOT pre-allocate the full final size of the U
matrix...just create an empty U
. Then, when invoking vertcat
, you need to give it both matrices that you want to concatenate:
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
中.像这样:
The better way to do this, since you already know the final size, is to pre-allocate your full U
(as you did) and then put your values into U
via computing the correct indices. Something like this:
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