Create a matrix with existing arrays

62 vues (au cours des 30 derniers jours)
Heng Xu
Heng Xu le 29 Août 2015
Commenté : Stephen23 le 30 Août 2015
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 commentaire
Stephen23
Stephen23 le 30 Août 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:

Connectez-vous pour commenter.

Réponse acceptée

Star Strider
Star Strider le 29 Août 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 commentaires
Star Strider
Star Strider le 29 Août 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 le 29 Août 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.

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 29 Août 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.
  1 commentaire
Heng Xu
Heng Xu le 29 Août 2015
That works, Thank you!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by