ODE graph for multiple occurrences

1 view (last 30 days)
Caleb Coombe
Caleb Coombe on 29 Jun 2021
Answered: Star Strider on 30 Jun 2021
Hello,
My MATLAB code as of right now will graph a ODE for one value of gamma. I would like to write the code so that it graphs 8 plots all on the same graph for varrying values of gamma. Values of gamma will be 0 through 2 with a step of .25. Here is my code currently:
tspan = [0 50];
y0 = [2 0]';
[t,y] = ode45(@hw1,tspan,y0);
plot(t,y(:,1))
function dy = hw1(t,y)
gamma = 1
dy(1)= y(2);
dy(2)= -gamma*y(2)-y(1);
dy = [dy(1);dy(2)];
title('Gamma equals .25')
end
Thank yoU!

Answers (1)

Star Strider
Star Strider on 30 Jun 2021
Define the γ vector (‘gammav’ here), use a loop, and see the documentation section on Passing Extra Parameters.
tspan = [0 50];
y0 = [2 0]';
gammav = logspace(-1, 1, 5)
gammav = 1×5
0.1000 0.3162 1.0000 3.1623 10.0000
for k = 1:numel(gammav)
[t{k},y{k}] = ode45(@(t,y)hw1(t,y,gammav(k)),tspan,y0);
end
figure
hold on
for k = 1:numel(gammav)
plot(t{k},y{k}(:,1))
end
grid
legend(compose('$\\gamma = %.2f$',gammav), 'Location','best', 'Interpreter','latex')
function dy = hw1(t,y,gamma)
dy(1)= y(2);
dy(2)= -gamma*y(2)-y(1);
dy = [dy(1);dy(2)];
end
.

Tags

Community Treasure Hunt

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

Start Hunting!