Generating a legend for one function that is associated with two variables

2 ビュー (過去 30 日間)
Olivia Kline
Olivia Kline 2021 年 2 月 15 日
コメント済み: Olivia Kline 2021 年 2 月 15 日
I am putting together a script that plots projectile motion as a function of the initial velocity and the launch angle. I am trying to add a legend that denotes v0 and theta for the plot and updates with the variables assigned in the command window. When I run the script, I get the legend, but the string message associated with the variable is listed twice. Can anyone provide any suggestions? This is the code I have right now for labeling the plot:
% Plot title and legend
title('2D Projectile Motion')
variableconvert = sprintf('Velocity and theta: %3d', v0, theta);
legend(variableconvert)
  2 件のコメント
dpb
dpb 2021 年 2 月 15 日
You asked to output two variables but only gave one output field -- so the whole format string is repeated.
variableconvert = sprintf('Velocity %3d and theta: %3d', v0, theta);
would be one way to fix. Salt to suit...
NB: that the '%d' format will limit you to showing only integer values. If that's all you're using, that's fine; you might consider
variableconvert = sprintf('Velocity and theta: %.1f, %.1f', v0, theta);
as another possibility.
Olivia Kline
Olivia Kline 2021 年 2 月 15 日
Thank you so much! That worked like a charm. I am not super familar with sprintf so the documentation was difficult to follow. Thanks for your help.

サインインしてコメントする。

回答 (1 件)

Adam Danz
Adam Danz 2021 年 2 月 15 日
The call to sprintf contains one format specification and two values. That applies the formatSpec twice.
demo:
sprintf('Demo %d ', 1,2)
ans = 'Demo 1 Demo 2 '
Either add another formatSpec or remove one of the values.
sprintf('Demo %d ', 1)
ans = 'Demo 1 '
sprintf('Demo %d %d', 1, 2)
ans = 'Demo 1 2'

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by