Skip to content

Instantly share code, notes, and snippets.

@PhotonEE
Created November 27, 2013 07:39
Show Gist options
  • Save PhotonEE/7671999 to your computer and use it in GitHub Desktop.
Save PhotonEE/7671999 to your computer and use it in GitHub Desktop.
Javascript implementation of convolution function
// a function to calculate the convolution of two vectors
// or to multiply the two algebraic expressions.
/*
**
idea :
------
vec1 = [2,3,4]
vec2 = [1,2,3]
multiply vec2 by vec1[0] = 2 4 6
multiply vec2 by vec1[1] = - 3 6 9
multiply vec2 by vec1[2] = - - 4 8 12
-----------------------------------------------
add the above three = 2 7 14 17 12
the - above shows the displacement after each vector multiplication by element of another vector
**
*/
function conv(vec1, vec2){
var disp = 0; // displacement given after each vector multiplication by element of another vector
var convVec = [];
// for first multiplication
for (j = 0; j < vec2.length ; j++){
convVec.push(vec1[0] * vec2[j]);
}
disp = disp + 1;
for (i = 1; i < vec1.length ; i++){
for (j = 0; j < vec2.length ; j++){
if ((disp + j) !== convVec.length){
convVec[disp + j] = convVec[disp + j] + (vec1[i] * vec2[j])
}
else{
convVec.push(vec1[i] * vec2[j]);
}
}
disp = disp + 1;
}
return convVec;
}
/*
**
Usage:
------
vecA = [2,3,2,1]
vecB = [4,1,2,3]
ans = conv(vecA, vecB);
**
*/
@Squareys
Copy link

Slightly optimized version:

const convolve = (vec1, vec2) => {
    if (vec1.length === 0 || vec2.length === 0) {
        throw new Error('Vectors can not be empty!');
    }
    const volume = vec1;
    const kernel = vec2;
    /* Initialized to zero by default */
    const convVec = new Float32Array(volume.length + kernel.length);

    let i = 0;
    for (let j = 0; j < kernel.length; ++j) {
        convVec[j] = volume[0] * kernel[j];
    }

    for (i = 1; i < volume.length; ++i) {
        for (let j = 0; j < kernel.length; ++j) {
            convVec[i + j] += volume[i] * kernel[j];
        }
    }

    return convVec;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment