问题
In MatLab, I have a matrix SimC which has dimension 22 x 4. I re-generate this matrix 10 times using a for
loop.
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.
Thank you!!
Edit:
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
Unfortunately the above doesn't work as U = vertcat(SimC)
only gives back SimC
instead of concatenating.
回答1:
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.
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
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
来源:https://stackoverflow.com/questions/27332427/concatenating-matrices-within-for-loop-in-matlab