MATLAB: 1d Convolution using Matlab’s conv() function

matlab function

According to the documentation(https://www.mathworks.com/help/matlab/ref/conv.html),
len(output) = len(input) + len(kernel) - 1
So, I figured out
  • In case of conv(u,v,"full"):
len(pad) = len(kernel) - 1
For instance, according to Matlab commandline:
u = [1 2 1 3]
v = [2 0 1]
w = [2 4 3 8 1 3]
Coz,
len(w) = len(u) + len(v) - 1
= 4 + 3 - 1
= 6
len(pad) = len(v) - 1
= 3 - 1
= 2
So, according to calculation:
0 0 1 2 1 3 0 0
1 0 2
---------------
0 0 2 = 2
. . . . . .
. . . . . .
0 0 1 2 1 3 0 0
1 0 2
-------------------
3 0 0 = 3
  • In case of conv(u,v,"same"):
u = [1 2 1 3]
v = [2 0 1]
w = [4 3 8 1]
Coz,
len(w) = len(u)
= 4
len(pad) = floor(len(v) / 2)
= floor(3 / 2)
= 1
So, according to calculation:
0 1 2 1 3 0
1 0 2
-----------
0 0 4 = 4
. . . . . .
. . . . . .
0 1 2 1 3 0
1 0 2
---------------
1 0 0 = 1
But, the problem arises in case of the following example:
u = [1 2 1 3 1]
v = [2 0 1 0]
The following one is okay:
  • In case of conv(u,v,"full"):
w = [2 4 3 8 3 3 1 0]
len(w) = len(u) + len(v) - 1
= 5 + 4 - 1
= 8
len(pad) = len(v) - 1
= 4 - 1
= 3
So,
0 0 0 1 2 1 3 1 0 0 0
0 1 0 2
---------------------
0 0 0 2 = 2
. . . . .
. . . . .
0 0 0 1 2 1 3 1 0 0 0
0 1 0 2
---------------------------
0 0 0 0 = 0
But, the following one has issues:
  • In case of conv(u,v,"same"):
w = [3 8 3 3 1]
Coz,
len(w) = len(u)
= 5
len(pad) = floor(len(v) / 2)
= floor(4 / 2)
= 2
So, according to calculation:
0 0 1 2 1 3 0 0
0 1 0 2
---------------
0 0 0 4 = 4
0 0 1 2 1 3 0 0
0 1 0 2
---------------
0 1 0 2 = 3
0 0 1 2 1 3 0 0
0 1 0 2
---------------
0 2 0 6 = 8
0 0 1 2 1 3 0 0
0 1 0 2
-----------------
0 1 0 0 = 1
0 0 1 2 1 3 0 0
0 1 0 2
-------------------
0 3 0 0 = 3
I.e. output = [4 3 8 1 3] which doesn't match the Matlab output.
What is going on here?

Best Answer

Ba Ba Black Sheep wrote
len(pad) = floor(len(v) / 2)
Actually the above is wrong,
In case CONV using with of 'same' option, the 0-pad on the head (left) side of u is:
floor((length(v)-1)/2)
and on the tail (right) side of u is:
ceil((length(v)-1)/2) = floor(length(v)/2)
For v that has odd-length, both are equal. The the result is as if extracted from the FULL result with equal chopping both sides in order to have the same length than the first argument u.
For v that has even-length, the zero-pad has 1 less element on the left than on the right. Therefore the chop size (from FULL result) has 1-more element on the left than on the right.