Using variable input to function in plot title
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Joe Duncan-Duggal
am 18 Jul. 2018
Beantwortet: Steven Lord
am 19 Jul. 2018
Hi, I have a function:
tsplot(station)
which outputs a plot when tsplot(EXAMPLE) is put into the command window.
I would like the title of this plot to read 'Preliminary plot of EXAMPLE time series', with EXAMPLE obviously changing to reflect whatever is input to the function.
Currently I have this:
str = station;
title(['Preliminary plot of',str,'time series']);
which doesn't work and causes the function to plot an incorrect figure, as well as an incorrect title.
Finally, the 'station' that is input to the function is the name of a table of data in the workspace, if that helps.
Any advice appreciated, cheers!
0 Kommentare
Akzeptierte Antwort
Star Strider
am 18 Jul. 2018
Use sprintf:
str = 'Tahiti';
title(sprintf('Preliminary plot of %s time series', str));
4 Kommentare
Stephen23
am 18 Jul. 2018
Unfortunately still no luck. I put in:
str = station;
title(sprintf('Preliminary plot of %s time series', str));
And get the error:
Error using sprintf
Unable to convert 'table' value to 'char'.
Error in tsplot (line 22)
title(sprintf('Preliminary plot of %s time series',
str));
Any other ideas? Is it related to the fact that "station" changes depending on what station name is input into the function?
Stephen23
am 18 Jul. 2018
Bearbeitet: Stephen23
am 18 Jul. 2018
@Joe Duncan-Duggal: read the error message: station is apparently a table, which means that it it cannot be provided to sprintf as an input argument. You will need to extract the exact value/s from the table that you want to input to sprintf, either using the variable names or indexing.
Weitere Antworten (1)
Steven Lord
am 19 Jul. 2018
So you want your function to use the name of the variable that was passed into it in the title of the plot it creates? You can use inputname for this purpose ... but be careful. Don't try to use that to perform computations (the data will be known inside your function using the name you specified in the function declaration), and make sure to handle appropriately (for some definition of appropriately) the case where the input doesn't have a name.
function displayInputname(x)
fprintf('The first input to displayInputname is named "%s".\n', inputname(1))
Now call this function:
qwerty = 1:10;
displayInputname(qwerty)
Looks good, right?
displayInputname(1:10)
Not so much.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Title finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!