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

2 次查看(过去 30 天)
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
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

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

尚未输入任何标签。

产品

Community Treasure Hunt

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

Start Hunting!

Translated by