Using variable input to function in plot title
4 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Star Strider
2018 年 7 月 18 日
Use sprintf:
str = 'Tahiti';
title(sprintf('Preliminary plot of %s time series', str));
4 件のコメント
Stephen23
2018 年 7 月 18 日
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
2018 年 7 月 18 日
編集済み: Stephen23
2018 年 7 月 18 日
@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.
その他の回答 (1 件)
Steven Lord
2018 年 7 月 19 日
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Title についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!