Reputation: 1
I am trying to model the equation y" + 4y = 0, with initial conditions y(0) = 1 and y'(0) = 0, in Matlab. The snippet of code below shows a working approximation of the position as a function of time for the above ODE:
clear
syms y(t)
%Differential Equation Conversion
P = odeToVectorField(diff(y, 2) == -4*y);
M = matlabFunction(P,'vars',{'t','Y'});
%Position Approximation
pos_solution = ode45(M,[0 20],[1 0]);
x = linspace(0,20,1000);
y = deval(pos_solution,x,1);
%Plot of Position as a function of time
figure(3)
plot(x,y,'b');
I am trying to take this data produced and find the velocity of the system as a function of time, but have no idea how to do so. Any help with this would be appreciated.
Upvotes: 0
Views: 417
Reputation: 18494
The optional third argument to deval
specifies which index of the solution to return. The index corresponds to the state vector (and initial conditions) and the output of your ODE integration function (M
). In the particular case of your system, index 1
corresponds to the position and index 2
to the velocity. If you want output (and plot) both, you can omit the third argument:
...
y = deval(pos_solution,x);
% Plot of Position as a function of time
figure(3)
plot(x,y(1,:),'b',x,y(2,:),'r');
legend('Position','Velocity');
Upvotes: 0