1

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.

2
  • Take a look at vertcat maybe? Commented Dec 6, 2014 at 14:11
  • thanks, vertcat looks promising. However I can't get it to work within the code: Commented Dec 6, 2014 at 15:23

1 Answer 1

2

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 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.