Solving 1st order ODE using Euler Method
12 views (last 30 days)
Show older comments
Hi, I am trying to solve the ODE dydt = 56t using euler in Matlab
The code below gives me x and y values, however they are in the form of horizontal matrices as opposed to vertical and when I try to change the matrice to vertical ( using t = 0;h;0.5; ) it tells me that the vectors are not the same length. Nothing also shows up in the plot generated. Does anybody know where I am going wrong? Thanks.
Also if I wanted to add in the exact solution to compare with the Euler method. How would I add that in and plot it?
The exact solution may be calculated by,
f = @(x)exp(x^2/2);
My code is,
y0 = 0; %initial condition
%h is the increment in t
h = 0.1;
t = 0:h:5;
N = length(t);
%Pre-allocation of y_euler
y_euler = zeros(size(t));
%Initial condition gives solution at t=0.
y_euler(1) = y0;
%dy/dt
dydt = @(t,y) 56*t;
% Solving the equation via Euler's Method
for i=1:(N-1)
k1 = dydt(t(i),y_euler(i));
y_euler(i+1) = y_euler(i) + h*k1;
end
plot(t,y_euler(1));
0 Comments
Answers (0)
See Also
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!