How can I convert comma-separated elements in a string into variable names?
이전 댓글 표시
Dear community,
I have a string of variable names separated by commas that was useful in collectng the variables into one vector. For example I created a list of variable names (these variables already have assigned values) in zlist, and then collected all the values into a vector called zin:
zlist = 'A,B,C';
zin = eval('['+zlist+']');
Now, I want to convert the values in zin back into variable names. How can I do that?
Thanks
댓글 수: 1
Rik
2023년 5월 20일
You should change your design. It is possible (with some constraints), but you should never need to do this.
답변 (1개)
Walter Roberson
2023년 5월 20일
Consider
A=1
B=1
C=2
zlist1='A,C'
zlist2='B,C'
zin1=eval("["+zlist1+"]")
zin2=eval("["+zlist2+"]")
You would expect that zin1=[1 2] and zin2=[1 2]
Now you want to be able to take zin1 and analyze it back to 'A,C' and analyze zin2 back to 'B,C' even though they both contain the same numeric values.
If the variables contained unique patterns of values it might be possible to analyze the combinations to figure out which one led to the overall result. That would be a task of "parsing"; it is more complicated than it seems at first, but the techniques are fairly well understood by now.
But in the case where the combinations can form duplicate results, such as here where the leading 1 can come from either A or B, there is no (reliable) way to determine from the numeric vector zin1 which variables were used to create it.
Not, that is, unless you believe that after MATLAB has created a variable, that it somehow keeps track of which variables were used to create the variable. And that simply does not happen. Once matlab has created a result and assigned it to a location, it completely discards any information about which variables or expressions were used to create the result.
카테고리
도움말 센터 및 File Exchange에서 Entering Commands에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!