Matlab convolution "same" to numpy.convolve

I noticed that when I use conv (a, b, 'same') in matlab, it will return M of length 200, but when I use numpy.convolve (a, b, 'same'), it will return N of length 200, but shifted by one element compared to M (N [1:] will be the same as M [0: -1], and M [-1] will not be in N, N [0] not in M), as I can i fix it?

I can cut the first element from N, but is there a way to get the last element of M without any problems?

+4
source share
1 answer

I assume the length of the shorter input array is even. In this case, there is ambiguity in how it should be handled when the method is the same. Matlab and numpy seem to have accepted various conventions.

There is an example of using the β€œsame” method on the Matlab documentation web page ( http://www.mathworks.com/help/matlab/ref/conv.html ):

> u = [-1 2 3 -2 0 1 2];
> v = [2 4 -1 1];
> w = conv(u,v,'same')

w =

    15     5    -9     7     6     7    -1

The first term, 15, is equal (1)*(0) + (-1)*(-1) + (4)*(2) + (2)*(3), and the last term -1 is equal (1)*(1) + (-1)*(2) + (4)*(0) + (2)*(0). You can interpret this as a complement uas [0 -1 2 3 -2 0 1 2 0 0], and then use the "real" method.

With numpy:

In [24]: u
Out[24]: array([-1,  2,  3, -2,  0,  1,  2])

In [25]: v
Out[25]: array([ 2,  4, -1,  1])

In [26]: np.convolve(u, v, 'same')
Out[26]: array([ 0, 15,  5, -9,  7,  6,  7])

, 0, (1)*(0) + (-1)*(0) + (4)*(-1) + (2)*(2), 7 (1)*(0) + (-1)*(1) + (4)*(2) + (2)*(0). u [0, 0, -1, 2, 3, -2, 0, 1, 2, 0], "" .

" " p ( p ), "valid", , p (.. ), , 0. Matlab numpy .

Matlab " " , "" np.convolve. ,

In [45]: npad = len(v) - 1

In [46]: u_padded = np.pad(u, (npad//2, npad - npad//2), mode='constant')

In [47]: np.convolve(u_padded, v, 'valid')
Out[47]: array([15,  5, -9,  7,  6,  7, -1])

"", , Matlab 'same':

In [62]: npad = len(v) - 1

In [63]: full = np.convolve(u, v, 'full')

In [64]: first = npad - npad//2

In [65]: full[first:first+len(u)]
Out[65]: array([15,  5, -9,  7,  6,  7, -1])

. , , , .

, Matlab numpy .

+3

All Articles