Search code examples
matlabmedian

Is there an efficient was to calculate a cyclical median in matlab?


I'm using matlab to mimic some c code that I've written so that I can replicate the result and plot it in matlab.

In c I am using an open source sliding median filter linked here.

I am currently using medfilt1 to mimic it in matlab, but there are two problems.

  1. It is SLOW! it would be ideal to have a similar filter in matlab, but I don't want to take the time to write one. If one does not exist, I'd like to at least be able to accomplish #2.

  2. medfilt1 does not wrap around.

    x = 1:5; medfilt1(x,3) % = 1 2 3 4 4

It calculates the first values like

median([0 1 2]) % = 1

This is because medfilt1 uses zeros to fill in when you get near the edges. I would like a way to change this so that the first value is calculated like

median([5 1 2]) % = 2

medfiltcirc(x,3) % = 2 2 3 4 4

UPDATE: For fun, I wrote a sliding filter in matlab, and it turned out to be about 4x slower than using medfilt1 with padarray. Using ordfilt2(padarray(x,[N/2 0],'circular'),N/2,ones(N,1)) proved to be even faster than medfilt1. I believe the only way to improve speed further would be to write a mex file.


Solution

  • another option is to use padarray before operating with the median filter:

    x = medfilt1(padarray(1:5,[0 1],'circular'));
    

    and take x(2:end-1) as the answer...

    to improve medfilt1 consider using ordfilt2 for example:

    x =  ordfilt2(1:5,2,[1 1 1]);
    

    this should buy you up to a factor of two, read more about it here, and do pay attention to the variable class used for A...