How to create Runge-Kutta 4th order routine to solve first-order ODE's

23 views (last 30 days)
1. Write your own 4th order Runge-Kutta integration routine based on the general equations. Do not use Matlab functions, element-by-element operations, or matrix operations.

Accepted Answer

Christopher Salerno
Christopher Salerno on 8 Dec 2018
clear all
close all
clc
h = ___; % set the step size
x = ________; % set the interval of x
y = zeros(1,length(x));
y(__) = ___; % set the intial value for y
n = length(x)-1;
y_dot =@(x,y)(___________); %insert function to be solved
for i = 1:n
k1 = y_dot(x(i),y(i));
k2 = y_dot(x(i)+.5*h,y(i)+.5*k1*h);
k3 = y_dot(x(i)+.5*h,y(i)+.5*k2*h);
k4 = y_dot(x(i)+h,y(i)+k3*h);
y(i+1) = y(i)+((k1+2*k2+2*k3+k4)/6)*h;
end
[t,y_check] = ode45(y_dot,x,2);
plot(x,y)
title('Eulers Method')
figure
plot(x,y_check)
title('ode45 Check')
  4 Comments

Sign in to comment.

More Answers (1)

Anthony Fitch
Anthony Fitch on 9 Dec 2018
%% Problem 1
%4th order Runge-Kutta integration routine
clear,clc
%Input custom values and custom first-order differential equation
Step_Value = input('Enter Step Value: ')
x_beg = input('Enter intial value of "x" at the beginning of the interval: ')
x_end = input('Enter final value of "x" at the end of the interval: ')
x_intial=input('Enter intial "x" value: ')
y_intial=input('Enter intial "y" value: ')
% Routine starts here
F_xy=@(x,y) 'Enter equation here: ';
h=Step_Value;
x=x_beg:h:x_end;
y=zeros(1,length(x));
y(x_intial)=y_intial;
for i=1:(length(x)-1)
k1 = F_xy(x(i),y(i));
k2 = F_xy(x(i)+0.5*h,y(i)+0.5*h*k1);
k3 = F_xy((x(i)+0.5*h),(y(i)+0.5*h*k2));
k4 = F_xy((x(i)+h),(y(i)+k3*h));
y(i+1) = y(i) + (1/6)*(k1+2*k2+2*k3+k4)*h;
end
%Checking custom routine and MATLAB function ode45
[x_c,y_c] = ode45(F_xy,x,y_intial);
%Plot in one figure
figure(1)
plot(x,y)
hold on
plot(x_c,y_c)
hold off
y_c2=y_c';
%Calculates error between custom runge-kutta routine and MATLAB function
%ode45
disp('Error between Runge-Kutta and ode45')
err = immse(y,y_c2)
  3 Comments
David After
David After on 5 Sep 2020
How can i solve this eqaution?
F''' + F*F"+ F'^2 = 0
with the boundary conditions
F(0)=F''(0)=0 and F'(infinity)=0 and eta is 0:0.1:6
i want to plot it and create a table for it (eta-f-f'-f'')
I am new to using the ode solver in matlab and am not sure how to make it solve a equation. Any suggestion would be appreciated.
please help me
thank you
my email : ff223325@gmail.com

Sign in to comment.

Categories

Find more on Programming 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!