How can I get the name of a MATLAB variable as a string?

971 visualizaciones (últimos 30 días)
I would like to convert the name of my MATLAB variable to a string so that, for example, I can plot a variable and then use the name of the variable as a title for the plot. Is there a way to do this without having to store the name of the variable along with the data?

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 29 de En. de 2018
There is no direct way to get the name of a variable as a string, but there is a function called "inputname" that will return the name of a variable that was input into a function:
Using this, you can create a short function that, given a variable, will output the name of it as a string, as in the following example:
 
function out = getVarName(var)
out = inputname(1);
end
As long as the file is included on the MATLAB path, you can use the function in the following way:
 
>> x = 1:10; % example data
>> plot(x)
>> title(getVarName(x))
 
  6 comentarios
Walter Roberson
Walter Roberson el 18 de Sept. de 2021
Perhaps a new function, something like
inputexpression(3)
and maybe something like
inputlocation(5)
except I am not really happy with the function name inputlocation . inputreference() maybe ??
Semantics:
inputreference() applied to an input that was a name and a chain of indexing expressions, would result in the name and the sequence of fieldnames and numeric indices needed to get to the endpoint... assuming that nothing in the chain had been modified since the call.
Now... suppose you have
struct('abc', def(7)).abc(3)
passed as a parameter. Then the result is a field name, and so you would like to be able to get the field reference. But it is not a variable that is being referenced, it is the result of a function call. This has been legal for a small number of releases. The result of any function call can have dot indexing applied to it. If you look at this hack, it is effectively calling def(7) and indexing at 3, which would be nice as def(7)(3) but that is not permitted syntax.. but you can use the intermediate struct to implement it !
So what should hypothetical inputreference() return in such a case? Empty because there is no ultimate name to index off of? Or something like "_anonymous.abc(3)" ?
... I'm still not sure what the use case would be for returning this information? What would you do with it?
If the idea is that you would like to be able to find out the "address" of an input and examine what is there... then remember that it is legal to use assignin() to modify things in the calling workspace.
assignin('caller', 'abc' [struct('def', []); VariableThatReceivedParameter])
and now the information that VariableThatReceivedParameter came from abc(1).def is out of date, and the value you are looking at now lives at abc(2).def -- which is an operation that did not require changing the memory location or reference count of what used to be at abc(1).def because each field of each structure array member has its own independent reference count and memory address...
If the question is "what was the chain of references that got to this location"? then that chain might no longer refer to the same thing. If you ask "What chain of references would you use at the moment to reach this location"? then the answer might be that it has been unlinked from the variable already...
So, again, what would you do with the information?
Walter Roberson
Walter Roberson el 18 de Sept. de 2021
For example, would it perhaps make sense to instead implement a more general call, something like parent(), that returned a list of all the places that had a reference to this memory address?
abc = [1 5 9]
parent(abc(2)) --> probably "abc"
def.ghi.jkl = [2 4 6]
m = def.ghi;
parent(def.ghi.jkl(3)) --> probably ["def.ghi.jkl", "m.jkl"] %all places!
function myfun(X)
parent(X(1))
end
myfun(def.ghi.jkl) --> ["X"] at least -- but maybe also "caller::def.ghi.jkl" ?
or if the caller is a named function then should "caller" be replaced with the function name? And if it is a subfunction then should > chaining be used? "MyProgram>localfun1>subfun>def.ghi.jkl" ?

Iniciar sesión para comentar.

Más respuestas (2)

Jan
Jan el 13 de Feb. de 2018
Try to avoid this whenever it is possible. The names of the variables should not carry important information. If names really matter, store them explicitly in the data, e.g. as struct:
Data(1).name = 'Level 1';
Data(1).value = 4711;
Data(2).name = 'Level 2';
Data(2).value = 31415;
Now you can access the name of the data, but are not restricted to specific names for the data. You can even create a temporary object:
yourFunction(struct('name', 'hello', 'value', 15))
With inputname this would fail, because the temporary object does not have a name of the variable.

Frieder Wittmann
Frieder Wittmann el 15 de Mzo. de 2019
Editada: Frieder Wittmann el 15 de Mzo. de 2019
@OP: I also think this would be very useful. For other programs like R it is standard to use the variable name for the title and xlabel, unless of course it is defined explicitly.
It might be bad practice for production code, but for quick data exploration and sharing it would be VERY useful to have a function like
function h = quickPlot(x,y)
xLabelName = inputname(1)
ylabelName =inputname(2)
figure()
plot(x,y)
xlabel(xLabelName)
title(ylabelName)
ylim(1.1 * [min(y),max(y)])
end
This works for
xx = 1:10
yy = 1:10
quickPlot(xx,yy)
but not for structs, e.g.
s.xx = 1:10
s.yy = 1:10
quickPlot(s.xx,s.yy)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Aún no se han introducido etiquetas.

Productos


Versión

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by