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+X-d*X, b*X*X-s*X, m*X-(p1+p2)*X-b*X*X
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
``````

Have a look at Performance Tips · The Julia Language, the first section.

Welcome to Julia!

3 Likes

This version is ~160x faster:

Let me know how that compares to matlab!

Magic ingredients are:

• move used variables out of global scope
• use Vector{Vec3} instead of a Matrix with 3xN - this also makes it a lot easier to write generic code that works on all Ns (2D mainly, I guess). It also removes allocations from slicing into `y` etc.

Btw, funnily enough in my opionion Matlab is the hardest language to bring to Julia and have Julia be much faster.
This comes mainly from the fact, that Matlab has a long history of teaching people some “anti patterns” for performance, and then optimizing the hell out of those anti patterns. It’s really very impressive, that Matlab achieves good performance with code written in such a way.

Because of that, it often needs quite a bit of rethinking to port an algorithm to Julia and have it nicely written + fast - but if you do, I think it yields more composable and readable code and should be faster.
Julia frees you from Matlab’s rigid “one and only way” (putting things into matrices) to make code fast. Also, it’s still really hard to achieve peak performance with Matlab, while it should almost always be possible to make an algorithm as fast as possible in Julia!

16 Likes