Is there a way to return a variable name from the variable value?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Just say a=2; is there a way to return an answer of a using the value 2?
1 Kommentar
Stephen23
am 19 Mai 2017
Bearbeitet: Stephen23
am 19 Mai 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.
Antworten (2)
Adam
am 19 Mai 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.
0 Kommentare
Guillaume
am 19 Mai 2017
Bearbeitet: Guillaume
am 19 Mai 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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!