【问题标题】:How to delete parts of array efficiently如何有效地删除部分数组
【发布时间】:2012-05-30 21:14:23
【问题描述】:

我正在编写一个 numpy/cython 程序来计算小矩阵(很多)的小数。

我当前的函数看起来像(计算 mat wrt. to row ii, col jj):

cdef float minor(np.ndarray[DTYPE_t, ndim = 2] mat,int ii,int jj): 
    rows = range(mat.shape[0])
    col = range(mat.shape[0])
    del rows[ii]
    del col[jj]

    cdef np.ndarray[DTYPE_t, ndim = 2] rM = (mat[rows])[:,col]

    cdef float val =  (-1)**(ii+jj) * np.linalg.det(rM)

    return val

经过一点基准测试,这条线

cdef np.ndarray[DTYPE_t, ndim = 2] rM = (mat[rows])[:,col]

相当耗时。有没有更好的方法从二维数组中删除一行一列?

你的,

cp3028

【问题讨论】:

  • 您可能不会从 cython 获得太多加速,因为您严重依赖 C-API 调用并且您没有输入 rowscol。如果您从一开始就知道mat 的大小,则可以对行列式进行硬编码并构建rM

标签: numpy scipy cython


【解决方案1】:

看起来您正在从(mat[rows])[:,col] 复制内存,分配和复制是一个缓慢的过程。难道不能简单地对mat的块进行函数调用np.linalg.deg,而不是复制它并计算副本上的行列式吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-16
    • 2020-12-11
    • 2011-01-15
    • 2019-11-05
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2012-12-14
    相关资源
    最近更新 更多