How to convert string to variable name ?
조회 수: 1,094 (최근 30일)
이전 댓글 표시
I try to do like this
if true
Varname=matlab.lang.makeValidName(strcat('Indiv_Reg_',Month))
end
where Month is a input variable represent char '01,02,...,12'
My problem is I cannot refer variable such as 'Indiv_Reg_01' to get a data from this variable. For example, I cannot get data from Indiv_Reg_01{1,1} by using this code
if true
Varname{1,1}
end
How Can I fix this problem ?
thanks in advance.
댓글 수: 1
Stephen23
2018년 1월 13일
"My problem is I cannot refer variable such as 'Indiv_Reg_01' to get a data from this variable"
The problem is that you are hiding pesudo-indices in variable names. Turn them into real indices and your "problem" instantly goes away. Solving problems through better code design is always preferred to writing slow, buggy, hack code accessing variable names.
채택된 답변
Jan
2018년 1월 13일
편집: Jan
2018년 1월 13일
This question is an evergreen. The solution is easy: Don't do this. It is a shot in your knee.
See:
- https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
- https://www.mathworks.com/matlabcentral/answers/57445-faq-how-can-i-create-variables-a1-a2-a10-in-a-loop
- and hundreds of discussions concerning eval in this forum.
Do not hide indices in the names of variables, but use indices instead: Let Indiv_Reg be a cell array and use the numerical value as index. This is much better than the indirection over the conversion to a string and hiding it in the names of dynamically created variables.
댓글 수: 5
Jan
2022년 11월 3일
"When we visit the site like this and post our questions, we are looking for a direct 'answer' to our question."
Of course. And the "direct" answer is often not the optimal solution, if the problem was formulated in a suboptimal way. This is the core of the already mentioned "XY-problem".
"We in general spend enough time (clicking, reading, and testing) and we still wants to do it for various reasons."
I cannot confirm this. The majority of users asking questions in this forum do not search before. Many newcomers tend to use eval and assignin folloing the wrong opinion, that this is useful. In the last 25 years I had many discussion about this topic and in all of them other methods have been fater, more elegant and reduce the effort for debugging. I'd be happy if all beginners read and consider Stephen's great summary about this topic,before they ask a concerning question, but this is not the case in general. If you a an exception, this is really nice for you. But as far as I can see, this is not your thread, but the question of Pradya Panyainkaew. He has accepted this answer and therefore I assume, it was useful.
Feel free to use assign in however you want. I'm not your teacher and you will not get any grades from me. But if you ask me for a good solution, I will suggest another method due to my experiences with Matlab and other programming languages. I have no problem, if you have another opinion. Feel free to post answers with your preferred method. Remember that I am a Matlab user as you are. There is no certificate or other sign, that makes me an "expert" - except that a certain number of users found my answers useful in the past.
"I rather unify parameters for all possible variations, still small size, and key inputs to a funciton are these versions predefined like m##### and p#####, respectively. I then load model and parameter mat file like M##### and P##### and pick elements from variables in the mat file loaded."
This is not clear enough to be discussed in detail. "m#####" looks like information is hidden in the name of the variables. As you know, I consider this as a bad code design, but this does not matter as long as you do not ask me for my opinion :-)
Have a nice day and I hope you find all needed asnwers in this forum.
Walter Roberson
2022년 11월 3일
When we visit the site like this and post our questions, we are looking for a direct 'answer' to our question.
This site gets quite a lot of questions from students. A fair portion of the students are "looking for" complete working code for their homework or honours project, that they can submit as their own work, without having to learn how to solve the problems themselves. Does it follow that we should provide that to them?
추가 답변 (3개)
Luna
2019년 1월 4일
편집: Luna
2019년 1월 4일
Hi all,
I agree with Jan & Stephen what they said about eval function. Don't use it. Instead use struct and arrays with dynamic naming.
For this example I have created a solution you can check:
Month = '01,02,03,04,05,06,07,08,09,10,11,12';
monthsArray = strsplit(Month,',');
for i = 1:numel(monthsArray)
Varnames{i} = matlab.lang.makeValidName(strcat('Indiv_Reg_',monthsArray{i}));
myStruct.(Varnames{i}) = randi(20,1,1);
end
myStruct.(Varnames{1,1}) % should give you a value of a random number
myStruct.Indiv_Reg_01 % same result above
ps: if you are forced to name your variables use this. Otherwise use directly indices of your Nx12 array.
댓글 수: 4
joe zhong
2020년 5월 21일
In fact, this two solutions should be the "Accepted" answer.
We all know we should don't do something, but things just happened, and we need a real solution rather than "just redo all scripts you got".
Luna
2020년 6월 1일
Believe me you will put much more effort to the solution you are asking for in your way rather than "just redoing all scripts you got".
You will spend time just for once redoing your code with indexing and implementing arrays. After that you will be free. Think that when you want to change a single variable name, that will force you to "redo all your scripts" again.
I only use eval if I'm running Simulink models with from Workspace blocks.
Don't use it if you really don't know what eval is used for. Here is some informations about justifiable usages of eval. These advices are from Matlab experts, at least they know some programming better than most.
Gabor
2021년 2월 18일
편집: Gabor
2021년 2월 18일
Your answer does not work if you only have hammer and a screw available at hand (curvfitting tool does not accept structs as variable for eg.). In that case its perfect to use the hammer to pop that screw in fast :D
I found this:
assignin('base',var_name, value)
댓글 수: 4
Stephen23
2021년 12월 16일
편집: Stephen23
2021년 12월 16일
"In my case, I needed to create a list of variables in a very specific format so that they can be exported out to a different piece of software."
You write that you need "a very specific format" (by which I presume that you mean that the variable name needs to have a very specific format, as of course the variable format itself is an unrelated topic). The most commonly-used MATLAB function for exporting data which relies on the variable names is SAVE, but of course SAVE has the -STRUCT option which completely avoids the need for dynamically named variables, so you must be using some other export function. Which one?
In the interest of helping other users understand the need you have, would you be so kind as to provide some sample code, or a description of the file format, or something similar so that we can understand why your use-case has this particular "need" which cannot be fulfilled with simpler, more efficient code.
Govind Narayan Sahu
2022년 6월 17일
편집: Govind Narayan Sahu
2022년 6월 17일
This works perfectly fine for me. Thanks a lot.
data = rand(1,8);
vars = {'a', 'b', 'd', 'e', 'f', 'g', 'h', 'i'};
index_vars = 1:8;
for k = 1:length(vars)
assignin('base',vars{k}, data(1, index_vars(k)))
end
Anshuman Agrawal
2020년 6월 19일
편집: Anshuman Agrawal
2020년 6월 19일
Hopefully, what you wanted to do was covered here.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Numeric Types에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!