Using variable input to function in plot title

4 views (last 30 days)
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!

Accepted Answer

Star Strider
Star Strider on 18 Jul 2018
Use sprintf:
str = 'Tahiti';
title(sprintf('Preliminary plot of %s time series', str));
  4 Comments
Stephen23
Stephen23 on 18 Jul 2018
Joe Duncan-Duggal's "Answer" moved here:
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
Stephen23 on 18 Jul 2018
Edited: Stephen23 on 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.

Sign in to comment.

More Answers (1)

Steven Lord
Steven Lord on 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.

Tags

Community Treasure Hunt

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

Start Hunting!