resampling, interpolating matrix

前端 未结 8 1454
-上瘾入骨i
-上瘾入骨i 2020-12-17 22:02

I\'m trying to interpolate some data for the purpose of plotting. For instance, given N data points, I\'d like to be able to generate a \"smooth\" plot, made up of 10*N or s

8条回答
  •  庸人自扰
    2020-12-17 22:16

    Your question isn't entirely clear; you're trying to optimize the code you posted, right?

    Re-writing sinc like this should speed it up considerably. This implementation avoids checking that the math module is imported on every call, doesn't do attribute access three times, and replaces exception handling with a conditional expression:

    from math import sin, pi
    def sinc(x):
        return (sin(pi * x) / (pi * x)) if x != 0 else 1.0
    

    You could also try avoiding creating the matrix twice (and holding it twice in parallel in memory) by creating a numpy.array directly (not from a list of lists):

    def resampleMatrix(Tso, Tsf, o, f):
        retval = numpy.zeros((f, o))
        for i in xrange(f):
            for j in xrange(o):
                retval[i][j] = sinc((Tsf*i - Tso*j)/Tso)
        return retval
    

    (replace xrange with range on Python 3.0 and above)

    Finally, you can create rows with numpy.arange as well as calling numpy.sinc on each row or even on the entire matrix:

    def resampleMatrix(Tso, Tsf, o, f):
        retval = numpy.zeros((f, o))
        for i in xrange(f):
            retval[i] = numpy.arange(Tsf*i / Tso, Tsf*i / Tso - o, -1.0)
        return numpy.sinc(retval)
    

    This should be significantly faster than your original implementation. Try different combinations of these ideas and test their performance, see which works out the best!

提交回复
热议问题