結論
想要從numpy的矩陣或者ndarray中提取子矩陣還是使用np.ix_
函數最快。另外想不到ndarray速度比matrix要快一下。水平有限,多多斧正。
import numpy as np
# ndarray
mtx = np.random.random((300, 300))
a = [1,3,5,7,8,9,12,16,23,45,64,72,89]
b = [1,3,5,7,8,9,12,16,23,45,64,72,89]
# 矩陣
M = np.matrixlib.matrix(mtx)
indices = np.ix_(a,b)
c = M[indices]
c.shape
%timeit c = mtx[indices]
%timeit c = M[indices]
%timeit c = mtx[:, b][a, :]
%timeit c = mtx[a, :][:, b]
100000 loops, best of 3: 2.75 µs per loop
100000 loops, best of 3: 3.99 µs per loop
100000 loops, best of 3: 10.7 µs per loop
100000 loops, best of 3: 8.56 µs per loop