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

Stephen23
Stephen23 2015년 8월 30일
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:

댓글을 달려면 로그인하십시오.

 채택된 답변

Star Strider
Star Strider 2015년 8월 29일

0 개 추천

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

Heng Xu
Heng Xu 2015년 8월 29일
Thank you Star Strider, That works. eval works perfectly.
Star Strider
Star Strider 2015년 8월 29일
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 2015년 8월 29일
It may work, but I think my code is far simpler, as long as you know how many variables you have, which you should.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2015년 8월 29일

1 개 추천

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.

카테고리

도움말 센터File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

질문:

2015년 8월 29일

댓글:

2015년 8월 30일

Community Treasure Hunt

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

Start Hunting!

Translated by