How can I get the name of a MATLAB variable as a string?
Mostra commenti meno recenti
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?
Risposta accettata
Più risposte (2)
Jan
il 13 Feb 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
il 15 Mar 2019
Modificato: Frieder Wittmann
il 15 Mar 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)
Categorie
Scopri di più su Document and Integrate Toolboxes in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!