I wrote Runge-Kutta order 4 code with Julia. and I also wrote with Matlab. And I compared time.
I thought that Julia is fater than Matlab. But actually Matlab is vary vary fater than Julia.
I have thought there exist something method which make Julia fater than Matlab.
Also I have wanted to learn about that method.
Here is my code
Julia Code
# starting node
x0 = 0
#ending node
T = 1000
# example
a = 0.056; b = 0.001; d = 0.0024; s = 0.03; m = 0.013; p1 = 1; p2 = 4; IC = [400;0;10];
function f(t,X)
a-b*X[1]+X[3]-d*X[1], b*X[1]*X[3]-s*X[2], m*X[2]-(p1+p2)*X[3]-b*X[1]*X[3]
end
# Making background
# internal Variable
h = 0.01
N = convert(Int, abs(T-x0)/h)
dim = length(IC)
y = zeros(dim,N+1)
y[:,1] = IC
t = collect(x0 : h : T);
# Body of Algorithm
@time for i = 1 : N
K1 = h.*f(t[i], y[:,i])
K2 = h.*f(t[i]+0.5*h, y[:,i].+K1./2)
K3 = h.*f(t[i]+0.5*h, y[:,i].+K2./2)
K4 = h.*f(t[i]+h, y[:,i].+K3)
y[:,i+1] = y[:,i] .+ (K1 .+ K2.*2 .+ K3.*2 .+ K4)./6
end
2.123314 sec
Matlab Code
% starting node
x0 = 0;
% ending node
T = 1000;
%% Examples
a = 0.056; b = 0.001; d = 0.0024; s = 0.03; m = 0.013; p1 = 1; p2 = 4; IC = [400;0;10]; % alp >= 0.853
f = @(t,X) [a-b*X(1)*X(3)-d*X(1) ; b*X(1)*X(3)-s*X(2) ; m*X(2)-(p1+p2)*X(3)-b*X(1)*X(3)];
%% Making background
% Internal Variables
h = 0.01;
N = abs(T-x0)/h;
dim = length(IC);
y = zeros(dim,N+1);
y(:,1) = IC;
t = (x0 : h : T);
%% Body of Algorithm
tic()
for i = 1 : N
K1 = h*f(t(i),y(:,i));
K2 = h*f(t(i)+h/2,y(:,i)+K1/2);
K3 = h*f(t(i)+h/2,y(:,i)+K2/2);
K4 = h*f(t(i)+h,y(:,i)+K3);
y(:,i+1) = y(:,i) + (K1 + 2*K2 +2*K3 + K4)/6;
end
toc
0.663678 sec