I have a square matrix that is NxN (N is usually >500). It is constructed using a numpy array.
I need to extract a new matrix that has the i-th column and row removed from this matrix. The new matrix is (N-1)x(N-1).
I am currently using the following code to extract this matrix:
new_mat = np.delete(old_mat,idx_2_remove,0)
new_mat = np.delete(old_mat,idx_2_remove,1)
I have also tried to use:
row_indices = [i for i in range(0,idx_2_remove)]
row_indices += [i for i in range(idx_2_remove+1,N)]
col_indices = row_indices
rows = [i for i in row_indices for j in col_indices]
cols = [j for i in row_indices for j in col_indices]
old_mat[(rows, cols)].reshape(len(row_indices), len(col_indices))
But I found this is slower than using np.delete() in the former. The former is still quite slow for my application.
Is there a faster way to accomplish what I want?
Edit 1: It seems the following is even faster than the above two, but not by much:
new_mat = old_mat[row_indices,:][:,col_indices]
500x500, the time copying is usually negligible. For bigger matrices, I believe creating an empty array and copying 4 slices onto it should be fairly fast.500x500is on the small side. The largest would be in the50,000x50,000. Most cases I'm working with are probably around10,000x10,000. What do you think about the method in the edit? i.e.,new_mat = old_mat[row_indices,:][:,col_indices]sliceinstead of fancy index should be faster, but that needs to be benchmarked. Anyway, indexing twice is likely going to take twice much time, you might want to at least broadcast these two indexing together, likeold_mat[row_indices[:,None],col_indices].slicebefore, but i will take a look.old_mat[row_indices[:,None],col_indices]. It is sayingnew_mat = old_mat[row_idx[:,None],col_idx] TypeError: list indices must be integers or slices, not tuple