Using variable input to function in plot title

4 ビュー (過去 30 日間)
Joe Duncan-Duggal
Joe Duncan-Duggal 2018 年 7 月 18 日
回答済み: Steven Lord 2018 年 7 月 19 日
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!

採用された回答

Star Strider
Star Strider 2018 年 7 月 18 日
Use sprintf:
str = 'Tahiti';
title(sprintf('Preliminary plot of %s time series', str));
  4 件のコメント
Stephen23
Stephen23 2018 年 7 月 18 日
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 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
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.

カテゴリ

Help Center および File ExchangeTitle についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by