# Sampling and Reconstructing a signal in Julia

I am a newcomer to the Julia world, so I started trying to implement a very simple program:

• Sample a signal
• Reconstruct it (various ways, just rectangular for now)
• Plot it

Everything is fine and 'working' properly, but coming from a OOP (java) and functional (python) background, I'm thinking that the following snippet can be improved to be in a more julia-ish style:

(required packages: DSP, Plots, PyPlot)
# parameters
Ts = 0.02;
n = 0:(100 / Ts);

f0 = 5;

dt = 0.001;
t = 0:dt:10;

# sampling
x = sin.(2 * pi * f0 * Ts * n); # target signal to sample

# reconstruct (need improvement)
rectangular_reconstr(i) = x[floor(Int, i * (length(n) / length(t)) + 1)]
x_recon_sinc = [rectangular_reconstr(e) for e in 1:(length(t)-1)]


I'm concerned about this list comprehension. Essentially, create a function that maps indices from (sampled) -> reconstructed is the whole idea here. If you were to do other kinds of interpolation (via spline, triangular or whatever), you can even access all the elements of the sampled array.

Is there any better alternative than this loop-comprehension version?

• You can get a 5-fold improvement in performance by using a const in place of length(n) / length(t) in your function, thus avoiding a recalculation of that ratio for every invocation. Because your method simply replicates the data points in the middle of x point by point, you can get an additional improvement by simply interleaving the middle values and concatenating with x[1] and x[5000] as follows: vcat(x[1], [x[2:5000] x[2:5000]]'[:], x[5001]). The [x[2:5000] x[2:5000]]'[:] does the interleave. Benchmark means are 2.227 ms, 444.37 μs, and 277.84 μs, respectively. Jun 25, 2019 at 4:21
• @EdwardCarney That interleaving would implicitly only render this feasible for a reconstruction frequency that is only 2 times the sampling frequency. Can you do a dynamic interleaving with n arrays/vectors? Jun 25, 2019 at 10:18