Creating a legend inside a loop, using sprintf

51 visualizaciones (últimos 30 días)
positron96
positron96 el 27 de Mayo de 2018
Comentada: Jan el 22 de Jul. de 2018
I am trying to make a legend for a plot with 'beta' number of curves. Basically, beta would be beta = [1 : 5] if I decided to have five curves, but it can be any number. I want to make a legend for that number of curves, and specifically do this by using a for loop (I know there are other ways that don't need for loops but I want to use a for loop for this one specifically). The code that I have (below) just gives me a legend for one curve "beta=1beta=2beta=3beta=4beta=5". I would need a legend for five curves. Basically the first curve would be beta = 1, the second curve would be beta = 2, and so on. Can someone help me?
for beta_val = beta
plot(time, y);
hold on
lgd = sprintf('beta = %0.0f', beta);
legend(lgd);
end

Respuesta aceptada

Star Strider
Star Strider el 28 de Mayo de 2018
Try something like this:
time = linspace(0, 2*pi); % Create Data
beta = 1:5; % Create Data
y = sin(time(:)*beta); % Create Data
for beta_val = beta
plot(time, y(:,beta_val));
hold on
lgd{beta_val} = sprintf('beta = %0.0f', beta(beta_val));
end
legend(lgd);
  6 comentarios
Star Strider
Star Strider el 28 de Mayo de 2018
As always, my pleasure!
Jan
Jan el 28 de Mayo de 2018
If this works, you can omit the loop:
plot(time, y);
lgd{beta_val} = sprintfc('beta = %0.0f', beta);
legend(lgd, 'Location','N')

Iniciar sesión para comentar.

Más respuestas (1)

Kai Åsvik
Kai Åsvik el 22 de Jul. de 2018
I am getting this error message: "Function 'subsindex' is not defined for values of class 'cell'."
  1 comentario
Jan
Jan el 22 de Jul. de 2018
@Kai: The problem is solved already and the readers cannot guess, which code causes your problem. Please open a new thread and include the code and the complete error message.

Iniciar sesión para comentar.

Community Treasure Hunt

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

Start Hunting!

Translated by