Using variable input to function in plot title
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Joe Duncan-Duggal
il 18 Lug 2018
Risposto: Steven Lord
il 19 Lug 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 Commenti
Risposta accettata
Star Strider
il 18 Lug 2018
Use sprintf:
str = 'Tahiti';
title(sprintf('Preliminary plot of %s time series', str));
4 Commenti
Stephen23
il 18 Lug 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
il 18 Lug 2018
Modificato: Stephen23
il 18 Lug 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.
Più risposte (1)
Steven Lord
il 19 Lug 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 Commenti
Vedere anche
Categorie
Scopri di più su Title in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!