Merging several row vectors in a single matrix

7 views (last 30 days)
Hey everybody, I am new to Matlab so my question may seem naive. I have a series of rows vectors A1, A2, A3.....An that I want to merge in a single matrix. I don't want to input them individually , that would be too long Is there a FOR-LOOP that I could use to do that? something that would look like:
Matrix= zeros(n);
for i=1:n % n is the number of vectors
statement... % a code to identify A(i)
Matrix(:,i)=A(i); % Put the vector A(n) in the i-th column of the matrix
end
I think that my main problem is that I don't know how to index A1, A2, A3...An in the for-loop.
Thanks for your help.

Accepted Answer

Ahmet Cecen
Ahmet Cecen on 21 Dec 2016
Naming your vectors A1,A2,A3 ... then assembling them like this is very inefficient. You want to either load them directly into the matrix (wherever you are getting these variables from) or use a cell array to store them as A{1}, A{2} ... instead. However, I will write down an answer that will work for this case, simply to solve your problem in the short term:
for i=1:n % n is the number of vectors
eval(["Matrix(:,i)=A",num2str(i),";"]; % will evalute the expression - Matrix(:,i)=Ai;
end
  3 Comments
Cole
Cole on 22 Dec 2016
It worked! Thank you very much Ahmet and James.
manvi kaushik
manvi kaushik on 31 Jan 2020
This answer is giving the transpose of the matrix. How can i correct it?

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!