Vector concatenation in for loop (MATLAB)

  • Context: MATLAB 
  • Thread starter Thread starter Prometheos
  • Start date Start date
  • Tags Tags
    Loop Matlab Vector
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 30K views
Prometheos
Messages
13
Reaction score
0
I have a program that calculates the inverse of a matrix. However, in my for loop I generate n vectors y which are nx1 vectors. The vectors are correctly calculated, but I can't figure out how to concatenate them into an nxn matrix.

The problem I think I'm having is that my vector y is generated but it isn't indexed ie y_1, y_2, or something like that. So I can't just make X=[y_1 y_2 ...]. Each time the loop runs it erases y and replaces it with the new y, so at the end I only have the nth vector left.

Does anyone know of a way to fix this so the output each loop would be [y_1] -> [y_1 y_2] -> ... n times?

This is my first program using MATLAB and I am quite stuck, thanks in advance.
 
Physics news on Phys.org
One simple way to do it is to define a matrix to hold the vectors before entering the loop; once you're inside the loop you can then concatenate the vector to the matrix.

Code:
A = []; % This is the matrix to hold the vectors.

for i = 1:n
   % Do stuff with the vector.
   A = [A y]; % Append the vector y to A.
end

This should work as a first approximation but it suffers one major drawback: each time you append the vector to the matrix A in the loop, the matrix A is redefined; this takes a lot of time. If you know in advance how many vectors you want to store, you can preallocate the matrix A and simply redefine the necessary portion in each step of the loop.

For instance, if you wish to store n vectors, with the dimension of each being mx1, something like the following might be useful.

Code:
A = zeros(m,n); % Preallocate A to be a mxn matrix of zeros.

for i = 1:n
   % Do stuff with the vector.
   A(:,i) = y; % Store the vector y in the ith column of A.
end
 
Last edited:
Awesome! Thank you so much Shoehorn, that worked like a charm. I thought I had fought through all the "hard" stuff in writing my program until I ran into this concatenation problem.