Using the text in a char matrix as the name of a matrix

조회 수: 10 (최근 30일)
Ehsan Khorsandnejad
Ehsan Khorsandnejad 2018년 2월 28일
댓글: Walter Roberson 2018년 3월 9일
Imagine I have a char matrix as follows:
val =
AAAAA
BBBBB
CCCCC
How can I use these texts as the names of some matrices?
For example I want my first matrix to be:
AAAAA = [3 4 5];
  댓글 수: 1
Stephen23
Stephen23 2018년 3월 9일
Avoid doing this. Dynamically accessing variable names is how beginners force themselves into writing slow, complex, buggy code that is hard to debug. For more information see:
Note that indexing is neat, simple, very easy to debug, and very efficient. You should consider using indexing.

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

답변 (3개)

Vishwanath Bailore Acharya
Vishwanath Bailore Acharya 2018년 3월 9일
You can use 'genvarname' for your purpose.
For example, if you have a character array 'val' as,
val = 'ABC';
then you can use 'genvarname' to construct a variable name from the strings as,
a = genvarname(val(1));
then you can use variable 'a' as a variable to any data by using 'eval' function as,
eval([a ' = [1,2,3]']);
Hope this helps.
  댓글 수: 1
Walter Roberson
Walter Roberson 2018년 3월 9일
Using eval() is not recommended. Using dynamic variable names is not recommended.

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


Walter Roberson
Walter Roberson 2018년 3월 9일

Ehsan Khorsandnejad
Ehsan Khorsandnejad 2018년 3월 9일
편집: Ehsan Khorsandnejad 2018년 3월 9일
Thanks, but I think you got my question wrong. I am not going to make dynamic name vairables. I am going to use some available names or strings as the name of a new variable.
For example I have some str like: 'MyNameIsJack'
I want to use the first 6 letters as the name of a new variable so I finally have:
MyName = 3;
How can I do this automatically via a code?
  댓글 수: 1
Walter Roberson
Walter Roberson 2018년 3월 9일
Creating a variable name from data at run time is making a dynamic variable name. You compute the variable name, such as
varname = str(1:6);
and then you want to use the content of varname as the name of the variable to write to. "Dynamic" in "dynamic variable name" is the opposite of "static" as in "static variable name", with static variable names being the ones that are hard-coded and unchangeable, and dynamic variable names changing depending on the circumstances.

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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by