This is my code to solve a system of difference equations:
function trajectoryDiscrete(sys_eq, init_cond, NIter, par1, par2)
neq = length(init_cond)
traj= zeros(Float64,NIter+1,neq)
traj[1,:] = init_cond
sys(x) = sys_eq(x, par1, par2);
for i in 1:NIter
init_cond = sys(init_cond)
traj[i+1,:] = init_cond
end
return traj
end
Here is a sample system of difference equations:
function test_difference_eq(x,r,k)
a = 5.0; mu = 0.5; d = 0.2;
dx = x[1]*exp(r*(1-x[1]/k)-x[2]/(a+x[1]^2))
dy = x[2]*exp(mu*x[1]/(a+x[1]^2)-d)
return @SVector [dx, dy]
end
Here is the result:
tr = @time trajectoryDiscrete(test_difference_eq, [0.5, 0.3], 10000, 1, 2)
0.000414 seconds (3 allocations: 156.484 KiB)
10001×2 Matrix{Float64}:
0.5 0.3
13.2216 0.380422
0.000982828 2586.64
⋮
0.0 2.5e-323
0.0 2.5e-323
Query: If I remove @SVector
from the return statement of test_difference_eq
then it gives
0.000655 seconds (10.00 k allocations: 1.068 MiB)
10001×2 Matrix{Float64}:
0.5 0.3
0.99971 0.257598
1.5792 0.229228
⋮
2.0 2.5e-323
2.0 2.5e-323
Ah! you guessed it right, I am new to Julia, trying to settle here ditching MATLAB. My queries are:
-
What magic does
@SVector
do so that allocation is reduced. Can you give me an idea when, where and how I can use @SVector and @SMatrix? -
Can this code be optimized further?
My ultimate goal is to solve the system for a range of r=range(1, 5, length = 501)
and k=range(2, 4, length = 501)
in nested for loop, store last few point of tr
to find its period using another user-defined function seqper
(see my previous post) and finally store each r-k
pair along with the associated period in a text file.
What are your suggestions?
Any form of help is appreciated.
Blockquote