Python Forum
Convolution "same" in Python doesn't work as Matlab - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: Convolution "same" in Python doesn't work as Matlab (/thread-30015.html)



Convolution "same" in Python doesn't work as Matlab - claw91 - Sep-30-2020

Hello, I'm trying to replicate Matlab's convolution aka conv function.

Matlab's conv works like this:

Quote:w = conv(u,v,shape) returns a subsection of the convolution, as specified by shape. For example, conv(u,v,'same') returns only the central part of the convolution, the same size as u.

I tried numpy convolve but documentation says it work differently, in fact:

numpy.convolve(a, v, mode) where:
- a(N,) array_like
- v(M,) array_like
- mode{‘full’, ‘valid’, ‘same’}

but the problem is that 'same' does NOT work as Matlab, in fact it says

Quote:Mode ‘same’ returns output of length max(M, N).

But I don't want the output to be of length max(M,N)!!! I want it to be same size as u as Matlab's.

Any idea how to do that?


RE: Convolution "same" in Python doesn't work as Matlab - DeaD_EyE - Sep-30-2020

If M < N, then max(M, N) == N

Why should M be bigger than N?

I use the convolve function to smooth graphs.
The array M should be smaller than N.


RE: Convolution "same" in Python doesn't work as Matlab - claw91 - Sep-30-2020

(Sep-30-2020, 12:22 PM)DeaD_EyE Wrote: If M < N, then max(M, N) == N

Why should M be bigger than N?

I use the convolve function to smooth graphs.
The array M should be smaller than N.

If M < N it for me it doesn't work

To give you some examples:

result = numpy.convolve(a, v, 'same')
case #1: a size (M) is 971, v size (N) is 601: Matlab's and Python's result is equal.

case #2: a size (M) is 451, v size (N) is 601: Matlab's and Python's result is NOT equal. The resulting array has 601 values - which is max(M,N) - but it should have 451 as in Matlab.

case #3: a size (M) is 59, v size (N) is 61: Matlab's and Python's result is NOT equal. The resulting array has 61 values - which is max(M,N) - but it should have 59 as in Matlab.


RE: Convolution "same" in Python doesn't work as Matlab - DeaD_EyE - Sep-30-2020

You can trim the second array to the same size of the first array.
The other options for mode aren't helpful.

How is matlab doing this?


RE: Convolution "same" in Python doesn't work as Matlab - claw91 - Oct-01-2020

(Sep-30-2020, 02:46 PM)DeaD_EyE Wrote: You can trim the second array to the same size of the first array.
The other options for mode aren't helpful.

How is matlab doing this?

What do you mean by "how is matlab doing this" ?

As in my previous post, Matlab's result of a 'same' convolution always has the same size of the first parameter array.