MATLAB Answers

How to solve a system of ODEs and plot the result

2 views (last 30 days)
Thomas Ward
Thomas Ward on 10 Feb 2020
Commented: Thomas Ward on 10 Feb 2020
Hello, I am fairly new to Matlab. I am trying to use matlab to solve an ODE with known boundary conditions and plot the results against those I've obtained analytically. The ODE in question is
d^2y/dt^2 + 400y = 0
For t 0-5 seconds and initial displacement y(0)=0.1 and velocity dy/dt=0. Since it has a second derivative, my understanding from reading so far is that I need to rewrite it as a sytem of equations with only first order derivatives. So subsituting y(1)=y(t) and y(2)=dydt, I tried using this code that I found,
function dydt = odefun(t,y)
dydt = zeros(2,1);
dydt(1) = 0*y(1)+y(2);
dydt(2) = -400*y(1)+0*y(2);
But it says that I don't have enough input arguements. I added in the 0* terms in hopes of correcting that, but no luck. I'm thinking maybe its asking for a t domain, but I tried a couple ways of defining that without sucess. I also played around with a couple alternative codes but no dice there either. I'm thinking if I get this ODE function to work, I insert it into ODE45 solver and plot the results. Thanks in advance for any help.

  0 Comments

Sign in to comment.

Accepted Answer

James Tursa
James Tursa on 10 Feb 2020
Edited: James Tursa on 10 Feb 2020
This is where you needed to show us the complete code and the complete error message. It is probably complaining about your initial conditions input, but without seeing your complete code I can't be sure. So something like this might be the fix:
[T,Y] = ode45(@odefun,[0 5],[0.1;0]); % Two-element initial conditions
Adding those 0* terms in your derivative function has no effect and can be removed.

  1 Comment

Thomas Ward
Thomas Ward on 10 Feb 2020
I think that worked, I didn't realize it needed the ode45 part to be considered fully defined, I thought I could troubleshoot this part of the code and then add the ODE solver at the end. The entirety of my code is now:
[T,Y] = ode45(@odefun,[0 3],[0.1;0]);
t=linspace(0,3);
undampedx = 0.1 * cos(10*t);
figure(1)
plot(t,undampedx,T,Y)
function dydt = odefun(t,y)
dydt = zeros(2,1);
dydt(1) = 0*y(1)+y(2);
dydt(2) = -400*y(1)+0*y(2);
end

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Tags

Products


Release

R2018b

Translated by