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

1 visualización (últimos 30 días)
Kaelan Wade
Kaelan Wade el 19 de Mayo de 2017
Editada: Guillaume el 19 de Mayo de 2017
Just say a=2; is there a way to return an answer of a using the value 2?
  1 comentario
Stephen23
Stephen23 el 19 de Mayo de 2017
Editada: Stephen23 el 19 de Mayo de 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.

Iniciar sesión para comentar.

Respuestas (2)

Adam
Adam el 19 de Mayo de 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 el 19 de Mayo de 2017
Editada: Guillaume el 19 de Mayo de 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

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Aún no se han introducido etiquetas.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by