How can I get the name of a MATLAB variable as a string?
古いコメントを表示
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?
採用された回答
その他の回答 (2 件)
Jan
2018 年 2 月 13 日
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
2019 年 3 月 15 日
編集済み: Frieder Wittmann
2019 年 3 月 15 日
@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)
カテゴリ
ヘルプ センター および File Exchange で Programming についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!