Search code examples
juliasignal-processingconvolution

Julia DSP: Convolution of discrete signals


Here is the problem. I want to write a convolution for two simple signals x[n]=0.2^n*u[n] and h[n]=u[n+2] for some values of n. This is how I implement it:

using Plots, DSP

x(n) = if n<0 0 else 0.2^n end
h(n) = if n<-2 0 else 1 end

n = -10:10
conv(h.(n),x.(n))

It doesn't work. Here is the error:

`float` not defined on abstractly-typed arrays; please convert to a more specific type

Any idea how may I fix it?


Solution

  • I ran it fine with a fresh REPL session:

    julia> using Plots, DSP
    [ Info: Precompiling Plots [91a5bcdd-55d7-5caf-9e0b-520d859cae80]
    [ Info: Precompiling DSP [717857b8-e6f2-59f4-9121-6e50c889abd2]
            
    julia> x(n) = if n<0 0 else 2^n end
    x (generic function with 1 method)
    
    julia> h(n) = if n<-2 0 else 1 end
    h (generic function with 1 method)
    
    julia> n = -10:10
    -10:10
    
    julia> conv(h.(n),x.(n))
    41-element Array{Int64,1}:
        0
        0
      
     (etc)
     
     1984
     1920
     1792
     1536
     1024
    
    julia> plot(conv(h.(n),x.(n)))
    (plots ok)
    

    If you change the 2 in 2^n to a float you need to specify Float64:

    julia>  x(n) = if n<0 0 else  0.2^n end
    x (generic function with 1 method)
    
    julia> conv(h.(n),Float64.(x.(n)))
    41-element Array{Float64,1}:
      0.0
      8.458842092382145e-17
      2.5376526277146434e-16
      4.229421046191072e-17
      2.1147105230955362e-16
           
       (etc)
       
      7.997440000004915e-5
      1.597440000003685e-5
      3.1744000002024485e-6
      6.144000000924524e-7
      1.0240000015600833e-7