Create a matrix with existing arrays

70 views (last 30 days)
Hi all,
I have a simple question about creating a matrix with existing arrays. Who can please help me with that:
I have 10 arrays named x1, x2,... x10. Each is of dimension 10 by 1. Now I want to put them into a single matrix, say matrix X, which is for sure of dimension 10 by 10.
I first create X=zeros(10);, and run a loop for i=1:10 X(:,i)=x(i); end but does not work, I know there is a mistake on my expression of x(i), who can please help me to fix that?
Many thanks,
Heng
  1 Comment
Stephen23
Stephen23 on 30 Aug 2015
How did you create individually numbered variables? This is a sign of poor program design, as these are really just implied indices and so would be better being defined as indices right from the start.
If these variables were created by hand or dyanamically then there is likely a much better solution that avoids the whole awkward solution of numbered variables and eval.
eval is not really the best solution to your question, as it is still slow to process, makes debugging difficult, breaks lots of code hinting and analysis tools, removes all JIT reprocessing, etc:

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 29 Aug 2015
You need to specify them individually. This is likely the only use of eval I find to be good programming:
x1 = rand(10,1);
x2 = rand(10,1);
x3 = rand(10,1);
for k1 = 1:3;
X(:,k1) = eval(sprintf('x%d',k1));
end
Change the loop limits to 10 from 3 for your code. (I didn’t feel like typing out 10 variables.)
  3 Comments
Star Strider
Star Strider on 29 Aug 2015
My pleasure.
Using eval to put them into a matrix, as you intend, is the correct use of eval.
It is considered to be very bad programming practise to use eval to do the reverse, that is to create different variables from a matrix.
Image Analyst
Image Analyst on 29 Aug 2015
It may work, but I think my code is far simpler, as long as you know how many variables you have, which you should.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 29 Aug 2015
To put the individual x in columns:
xAll = [x1,x2,x3,x4,x5,x6,x7,x8,x9,x10]
To put them in rows, use semicolons instead of commas.

Categories

Find more on Creating and Concatenating Matrices 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!