Getting mutliple lines into a legend from a for loop that provides different values

Below is my code, im trying to get each of the lines on the plot onto the legend but am unsure how to go about it? I know i can just type it out manually for each gamma value e.g legend('2\gamma = 0','2\gamma = 1','2\gamma = 3',) but i would like a method that automatically adjusts to any variations i may make to gamma
clear all
for gamma = [0,0.5,1.5]
% Parameters
k = 5; % constant
zeta = 2*gamma; %Damping Coefficient
x_initial = 0.1; %Initial Position
v_initial = 0; %Initial Velocity
dt = 0.0001; % Time Step
t_vector = 0:dt:10; % Time Vector
x(1) = x_initial; %Initial position
v(1) = v_initial; %Initial velocity
%for loop
for n= 1:length(t_vector)-1
xslope = v(n);
x(n+1) = x(n) + xslope*dt;
vslope = -zeta*v(n) -k*x(n);
v(n+1) = v(n) + vslope*dt;
end
%plotting the graph
a = -zeta*(-v) -k*(-x);
plot(t_vector,a)
hold on;
end
title("Damped Simple Oscillator");
xlabel("Time");
ylabel("Amplitude");
lgd = legend(sprintf("2\\gamma = %d", zeta));
title(lgd, "\zeta")
grid on;
hold off;

 採用された回答

Voss
Voss 2022 年 4 月 10 日
all_gamma = [0 0.5 1.5];
for gamma = all_gamma
% your code
end
lgd = legend(sprintfc('2\\gamma = %d',2*all_gamma));

1 件のコメント

Adam Lacey
Adam Lacey 2022 年 4 月 10 日
編集済み: Adam Lacey 2022 年 4 月 10 日
This works amazing thank you. Had to change %d to %g to eliminate scientific notation for decimals.

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

その他の回答 (1 件)

Matt J
Matt J 2022 年 4 月 10 日
lgd = legend('2\gamma='+string(2*[0,0.5,1.5]));

1 件のコメント

Adam Lacey
Adam Lacey 2022 年 4 月 10 日
Thanks thats definitely more succinct than what i had but still requires manually updating for each change in gamma value. Is there an automatic way?

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

カテゴリ

ヘルプ センター および File ExchangeGamma Functions についてさらに検索

製品

リリース

R2021b

タグ

質問済み:

2022 年 4 月 10 日

編集済み:

2022 年 4 月 10 日

Community Treasure Hunt

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

Start Hunting!

Translated by