Clear Filters
Clear Filters

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

2 views (last 30 days)
Just say a=2; is there a way to return an answer of a using the value 2?
  1 Comment
Stephen23
Stephen23 on 19 May 2017
Edited: Stephen23 on 19 May 2017
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.

Sign in to comment.

Answers (2)

Adam
Adam on 19 May 2017
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 on 19 May 2017
Edited: Guillaume on 19 May 2017
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

Tags

No tags entered yet.

Products

Community Treasure Hunt

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

Start Hunting!