Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

broadcasting vector multiplication with a 3 vector and n vector in julia

I have a 3-vector c = [0.7, 0.5, 0.2] and I want to multiply it with everything in an n-vector x = rand((-1,1),n) such that I get a resulting n+2-vector y where y[i] == x[i]*c[3] + x[i-1]*c[2] + x[i-2]*c[1]

How should I do this in julia? I feel like there should be a way to broadcast the smaller 3 vector to all the values in the n vector. And for the edge cases, if i-1 or i-2 is out of bounds I just want zero for those components.

like image 569
Moose Avatar asked Dec 23 '22 16:12

Moose


1 Answers

If I understand your question correctly you want a convolution, with a twist that in a standard convolution the vector c would be reversed. You can use e.g. DSP.jl for this.

Is this what you want?

julia> using DSP

julia> c = [0.7, 0.5, 0.2]
3-element Array{Float64,1}:
 0.7
 0.5
 0.2

julia> conv([10, 100, 1000, 10000], reverse(c))
6-element Array{Float64,1}:
    1.9999999999996967
   25.0
  257.0000000000003
 2569.9999999999995
 5700.0
 6999.999999999998

You can also manually implement it using dot from the LinearAlgebra module like this:

julia> using LinearAlgebra

julia> x = [10, 100, 1000, 10000]
4-element Array{Int64,1}:
    10
   100
  1000
 10000

julia> y = [0;0;x;0;0]
8-element Array{Int64,1}:
     0
     0
    10
   100
  1000
 10000
     0
     0

julia> [dot(@view(y[i:i+2]), c) for i in 1:length(x)+2]
6-element Array{Float64,1}:
    2.0
   25.0
  257.0
 2570.0
 5700.0
 7000.0
like image 100
Bogumił Kamiński Avatar answered Apr 25 '23 10:04

Bogumił Kamiński