How to insert variable name into graph title

150 次查看(过去 30 天)
Dear All,
I would like to ask how I would print the variable name into the graph title
example:
function abc(varname)
.
.
.
title('Graph of 'insert varname here'')
thank you

采纳的回答

Jan
Jan 2017-3-15
编辑:Jan 2017-3-15
The name of the variable should not matter. Not that it is "varname" in every case here. But the name might be different in the caller. Nevertheless, relying on the name is a pitfall. Better create a specific variable, which carries the name:
data = 1:10;
name = 'My Data';
function abc(data, name)
plot(data);
title(sprintf('Graph of %s', name));
But beside this general advice to separate the program and the data strictly, there is a dirty command to do this:
function abc(data)
name = inputname;
if isempty(name)
name = 'unknown';
end
plot(data);
title(sprintf('Graph of %s', name));
The test for the empyt name is required when you call your function e.g. by:
abc(1:10)
Then there is no name, because the data are created dynamically. The same problem:
x = 1:10;
abs(x(2:7))
I'm not sure if inputname works here. Therefore I would not play with such meta-programming techniques, when providing a specified name as additional variable is such dry and clean.
Perhaps you can use a struct:
data.value = 1:10;
data.name = 'Voltage at point X'
data.unit = 'mV'
You see, this offers many elegant ways to keep the data and the meaning packed together. And the name is not restricted to allowed names of variables.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Title 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by