MATLAB Vector concatenation in for loop (MATLAB)

AI Thread Summary
The discussion focuses on a MATLAB programming issue related to concatenating vectors generated in a for loop into a matrix. The user initially struggles with overwriting the vector y during each iteration, resulting in only the last vector being retained. A solution is proposed to preallocate a matrix to hold the vectors before the loop begins, allowing for efficient storage of each vector in its respective column. This method avoids the performance drawbacks of repeatedly appending to the matrix. The user confirms that the suggested approach successfully resolves their problem.
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.
 
Back
Top