MATLAB Answers

0

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

Asked by Christopher Salerno on 8 Dec 2018 at 0:37
Latest activity Edited by Christopher Salerno on 9 Dec 2018 at 0:22
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.

  0 Comments

Sign in to comment.

2 Answers

Answer by Christopher Salerno on 8 Dec 2018 at 0:37
 Accepted Answer

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')

  1 Comment

Nice Job, my Code came out very similar to yours :)

Sign in to comment.


Answer by Anthony Fitch on 9 Dec 2018 at 0:13

%% 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)

  1 Comment

I like the error checking and the user inputs. Very nice man!.. a bit better than my code.. thanks for posting your code so I can see how to be more user friendly. Love it!

Sign in to comment.