Matlab是否有等效于numpy的缓冲区? [英] Is there a Matlab's buffer equivalent in numpy?

查看:76
本文介绍了Matlab是否有等效于numpy的缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到有一个array_splitsplit 方法,但是当您必须拆分长度不是数组大小的整数倍的数组时,这些方法不是很方便.而且,这些方法输入的是切片数而不是切片大小.我需要更类似于Matlab的 buffer 方法,该方法更适合信号处理.

I see there is an array_split and split methods but these are not very handy when you have to split an array of length which is not integer multiple of the chunk size. Moreover, these methods input is the number of slices rather than the slice size. I need something more like Matlab's buffer method which is more suitable for signal processing.

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

For example, if I want to buffer a signals to chunks of size 60 I need to do: np.vstack(np.hsplit(x.iloc[0:((len(x)//60)*60)], len(x)//60)) which is cumbersome.

推荐答案

我编写了以下例程来处理所需的用例,但尚未对"underlap"进行实施/测试.

I wrote the following routine to handle the use cases I needed, but I have not implemented/tested for "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

这篇关于Matlab是否有等效于numpy的缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆