How can I create a subplot of ode45 for a mass spring damper where the two plots have a different k value?

1 view (last 30 days)
I'm new to MATLAB and i'm trying to create two subplots side by side, where the only difference is the 'k' value in the mass spring damper equation is different.
Here is the code:
function zprime= msdfunc(t,z)
m = 4; b = 0.25; k = 2;
zprime=[z(2);-(b/m)*z(2)-(k/m)*z(1);];
end
tspan=[0, 60];
y0=[0, 4];
[t, y]=ode45(@msdfunc, tspan, y0);
plot(t, y);
I need to plot the equation for k=2 and k=4.
Thanks in advance

Accepted Answer

Bjorn Gustavsson
Bjorn Gustavsson on 23 Sep 2019
Simply add another parameter to your msdfunc for k:
function zprime= msdfunc(t,z,k)
m = 4; b = 0.25;
if nargin < 2 || isempty(k)
k = 2; % Your default value
end
zprime=[z(2);-(b/m)*z(2)-(k/m)*z(1);];
end
Then you can solve the ODE for different values of k:
[t_k4, y_k4]=ode45(@(t,y) msdfunc(t,y,4), tspan, y0);
Then you can plot away in any organization of subplots.
HTH

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!