Hold on command in ode45
Show older comments
I want to plot the graph of first order ODE y'=ax for different numerical values of 'a' in the same graph using ode45. I tried using 'hold on' command but it is not working. could anyone tell me how to do that?
Answers (1)
Davide Masiello
on 7 Feb 2022
Edited: Davide Masiello
on 7 Feb 2022
You could do this.
clear,clc
a = linspace(0.1,0.2,10); % 'a' takes 10 values between 0.1 and 0.2
tspan = [0,10]; % Time span of integration
y0 = ones(size(a)); % Initial conditions
[t,y] = ode45(@(t,y)myode(t,y,a'),tspan,y0); % Passes function to ode solver
plot(t,y) % Plots results
legend(string(a),'Location','northwest') % Displayes legend
function out = myode(t,~,a)
out = a.*t;
end
Which result is

EXPLANATION:
There is no need to use 'hold on', because you can first integrate the equation for every value of 'a' and then plot them all together.
A way of doing this could be to put the 'ode45' call in a 'for loop' and change the value of 'a' at each iteration.
However, the solution I provided solves all the equations together saving a bit of time and lines of code.
Categories
Find more on Ordinary Differential Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!