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

1 visualización (últimos 30 días)
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 comentarios
dpb
dpb el 15 de Feb. de 2021
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 el 15 de Feb. de 2021
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.

Iniciar sesión para comentar.

Respuestas (1)

Adam Danz
Adam Danz el 15 de Feb. de 2021
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'

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by