Is there a way to return a variable name from the variable value?

Just say a=2; is there a way to return an answer of a using the value 2?

댓글 수: 1

Stephen23
Stephen23 2017년 5월 19일
편집: Stephen23 2017년 5월 19일
There are ways, but if you are starting to write code like this then you should consider revising your algorithm:
code should be independent of data. When you mix the two of them together then you will make your code much slower, buggier, harder to understand, and harder to fix. If you need a mapping, such as 2 to a, then use simple methods, such putting them into arrays and using indexing. If fact that would be so simple it would have taken less time than you took writing your question.

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

답변 (2개)

Adam
Adam 2017년 5월 19일

0 개 추천

No. Feeling the need to do this is also a sign that your code design has gone very wrong too. The variable name is just a handle by which the code can identify the variable, it should never need to be transported around in any other way through the program.
Guillaume
Guillaume 2017년 5월 19일
편집: Guillaume 2017년 5월 19일
There is a way, but as Adam says the fact that you want this is an indication that your design is bad.
vars = who;
equal2 = vars(cellfun(@(var) isequal(eval(var), 2), vars)
The fact that the above is using eval should ring alarm bells. So, again, don't do this
You haven't described the use case so it's difficult to give advice but the normal way to do something like that is to have just one variable, a vector, matrix, ND array or cell array as a container for what is now your individual variables. Searching for which element of the container contains a given value is then easily achieved with set membership functions such as ismember

카테고리

도움말 센터File Exchange에서 Variables에 대해 자세히 알아보기

제품

태그

아직 태그를 입력하지 않았습니다.

질문:

2017년 5월 19일

편집:

2017년 5월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by