Skip to content

Instantly share code, notes, and snippets.

@Bollegala
Last active February 17, 2017 23:29
Show Gist options
  • Save Bollegala/73d372d527f4f147d5183176d3ab86a4 to your computer and use it in GitHub Desktop.
Save Bollegala/73d372d527f4f147d5183176d3ab86a4 to your computer and use it in GitHub Desktop.
Demonstrates vector convolution
"""
This code shows how to perform convolution between two vectors.
Danushka Bollegala.
14-04-2016
"""
import numpy
def conv(u, v):
d = u.shape[0]
p = numpy.zeros(d, dtype=float)
for i in range(0, d):
#print i
for j in range(0, d):
#print j, i-j , u[j], v[i-j]
p[i] += u[j] * v[i-j]
return p
def pconv(u, v):
d = u.shape[0]
p = numpy.zeros(d, dtype=float)
for i in range(0, d):
for j in range(0, d):
p[i] += u[j] * v[j-i]
return p
def main():
# Lets first compute the convolution between two vectors u and v.
u = numpy.array([0, 6, 2, 10, 4])
v = numpy.array([1, 8, 4, 4, 0])
p = conv(u, v)
print p
p = conv(v, u)
print p
# This shows that vector convolution is commutative
# (which is bad because word order is ignored during composition)
# To overcome this, lets involute the second vector, before
# we compute its convolution with the first vector.
# This is known as periodic convolution (http://ltfat.sourceforge.net/doc/fourier/pconv.php)
p = pconv(u, v)
print p
p = pconv(v, u)
print p
pass
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment