How can i create variables from a string?

Hi! I want to create an array of variables m1,m2,m3,....,mn, that are created by join "m" with array "1,2,3,...,n" I wrote a code (below), and i want to after run it, Matlab returns: m1=1 m2=5
M=[1 2 3;
4 5 6;
7 8 9];
mch=diag(M,0)';
x=2;
for i=1:x
ha=num2str(i);
m(ha)= mch(i);
end
Thank you so much!

 채택된 답변

KSSV
KSSV 2017년 5월 18일

0 개 추천

Why you need a dynamic variable naming? This is not suggested and you should avoid.
You have matrix already and you can happily call them:
M=[1 2 3;
4 5 6;
7 8 9];
M(1) % is M1
M(2) % is M2
M(6) % is M6
.
.
.M(i) % is Mi where i <= numel(M)

댓글 수: 3

Le Dung
Le Dung 2017년 5월 18일
편집: Le Dung 2017년 5월 18일
Yes, It's very kind of you. But, because i want to make a general problem. Thank you so much. I wrote a code as (below), why matlab returns results that i don't want. Detail, I received a variable "eval" that has size is (1x77) and, only end value of eval is equal to 5. Why?, I want to m1 = 1, m2 = 5
M=[1 2 3;
4 5 6;
7 8 9];
mch=diag(M,0)';
x=2;
for i=1:x
eval(['M' num2str(i)'])=mch(i);
end
Stephen23
Stephen23 2017년 5월 18일
편집: Stephen23 2019년 10월 7일
"But, because i want to make a general problem"
Yes, you are trying to make a general problem. And KSSV gave you a general solution instead.
Good work, KSSV.
M = [1,2,3;4,5,6;7,8,9];
mch = diag(M,0); % this is all you need
Sami Aldalahmeh
Sami Aldalahmeh 2019년 10월 7일
I believe that you should answer the question if you can not discourage the user. Giving advice in a polite way, on the other hand, is always welcomed.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2017년 5월 18일

편집:

2019년 10월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by