Processing an ECG signal with a median filter

I have read in a couple of papers that the noise from an ECG signal can be removed via median filter. One such example I found was on stackoverflow, where multiple methods were suggested and one of them being the median filter. The following image is taken from the post on stackoverflow.

The main idea of the median filter is to run through the signal entry by entry, replacing each entry with the median of neighboring entries. The pattern of neighbors is called the "window", which slides, entry by entry, over the entire signal.

What I do not understand is, why doesn't the QRS complex get removed as well? When I tried it using matlab, the bigger I set the window, the better the signal got filtered, should't it be the opposite?

• There is a optimum size for the window, if you set the window size very large (about 500) certainly you will get bad results. – Mohammad M Aug 19 '17 at 8:06
• The pattern of neighbors is not called window. Window is the same as a neighborhood. – Mohammad M Aug 19 '17 at 8:14

Median filter is a highly highly nonlinear filter (it re-orders the sample positions!). The output of the median filter at a position $n$ is the median of the values that reside in the window scope; i.e., it's the value that resides in the middle when the samples are sorted in order. Hence median filtering requires sorting for each computation. This makes it quite slow as well (a deailed answer actually depends on the architecture...)