Specify lag in numpy.correlate

前端 未结 3 552
执笔经年
执笔经年 2021-01-01 02:00

Matlab\'s cross-correlation function xcorr(x,y,maxlags) has an option maxlag, which returns the cross-correlation sequence over the lag range

3条回答
  •  天命终不由人
    2021-01-01 02:24

    matplotlib.xcorr has the maxlags param. It is actually a wrapper of the numpy.correlate, so there is no performance saving. Nevertheless it gives exactly the same result given by Matlab's cross-correlation function. Below I edited the code from maxplotlib so that it will return only the correlation. The reason is that if we use matplotlib.corr as it is, it will return the plot as well. The problem is, if we put complex data type as the arguments into it, we will get "casting complex to real datatype" warning when matplotlib tries to draw the plot.

    
    
    import numpy as np
    import matplotlib.pyplot as plt
    
    def xcorr(x, y, maxlags=10):
        Nx = len(x)
        if Nx != len(y):
            raise ValueError('x and y must be equal length')
    
        c = np.correlate(x, y, mode=2)
    
        if maxlags is None:
            maxlags = Nx - 1
    
        if maxlags >= Nx or maxlags < 1:
            raise ValueError('maxlags must be None or strictly positive < %d' % Nx)
    
        c = c[Nx - 1 - maxlags:Nx + maxlags]
    
        return c
    

提交回复
热议问题