python - NumPy 是否有相当于 Matlab 缓冲区的功能?

标签 python matlab numpy buffer

我看到有一个array_splitsplit methods但是当您必须拆分长度不是 block 大小的整数倍的数组时,这些并不是很方便。此外,这些方法的输入是切片的数量而不是切片的大小。我需要更像 Matlab 的 buffer 的东西哪种方法更适合信号处理。

例如,如果我想将信号缓冲到大小为 60 的 block ,我需要这样做:np.vstack(np.hsplit(x.iloc[0:((len(x)//60) *60)], len(x)//60)) 这很麻烦。

最佳答案

我编写了以下例程来处理我需要的用例,但我没有实现/测试“underlap”。

请随时提出改进建议。

def buffer(X, n, p=0, opt=None):
    '''Mimic MATLAB routine to generate buffer array

    MATLAB docs here: https://se.mathworks.com/help/signal/ref/buffer.html

    Parameters
    ----------
    x: ndarray
        Signal array
    n: int
        Number of data segments
    p: int
        Number of values to overlap
    opt: str
        Initial condition options. default sets the first `p` values to zero,
        while 'nodelay' begins filling the buffer immediately.

    Returns
    -------
    result : (n,n) ndarray
        Buffer array created from X
    '''
    import numpy as np

    if opt not in [None, 'nodelay']:
        raise ValueError('{} not implemented'.format(opt))

    i = 0
    first_iter = True
    while i < len(X):
        if first_iter:
            if opt == 'nodelay':
                # No zeros at array start
                result = X[:n]
                i = n
            else:
                # Start with `p` zeros
                result = np.hstack([np.zeros(p), X[:n-p]])
                i = n-p
            # Make 2D array and pivot
            result = np.expand_dims(result, axis=0).T
            first_iter = False
            continue

        # Create next column, add `p` results from last col if given
        col = X[i:i+(n-p)]
        if p != 0:
            col = np.hstack([result[:,-1][-p:], col])
        i += n-p

        # Append zeros if last row and not length `n`
        if len(col) < n:
            col = np.hstack([col, np.zeros(n-len(col))])

        # Combine result with next row
        result = np.hstack([result, np.expand_dims(col, axis=0).T])

    return result

关于python - NumPy 是否有相当于 Matlab 缓冲区的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38453249/

相关文章:

python - 如何在 tensorflow 中将字典转换为张量

python - 我如何在 N 阶张量(ndarray)中根据自己的选择收缩 2 个指数

python - 如何在 Sphinx 文档和 nbsphinx 中嵌入 Plotly 图

Python - 简单的 TCP/IP S/C : Not all strings converted error for a print statement

python - 如何在网页中显示excel文件的值

matlab - 如何在 MATLAB 中计算特定数字?

matlab - 运行使用多个 MATLAB session 的脚本

matlab - 如何做一个频段?

python - 如何获取每行中 n 个最后/第一个 True 的 NumPy 数组

python - 使用 matplotlib 从 Python plot 获取数据然后保存到数组