R中稀疏矩阵对角线归零的内存有效方法

R中稀疏矩阵对角线归零的内存有效方法,r,sparse-matrix,R,Sparse Matrix,我想把R中稀疏矩阵的对角线归零。我的蛮力方法是显式地将其设置为零,但这似乎效率低下。有没有更有效的方法 require(Matrix) A <- as(rsparsematrix(nrow = 1e7, ncol = 1e7, nnz = 1e4), "sparseMatrix") diag(A) <- 0 A <- drop0(A) # cleaning up require(矩阵) A您可以很快找到非零条目: ij <- which(A !=

我想把R中稀疏矩阵的对角线归零。我的蛮力方法是显式地将其设置为零,但这似乎效率低下。有没有更有效的方法

require(Matrix)
A <- as(rsparsematrix(nrow = 1e7, ncol = 1e7, nnz = 1e4), "sparseMatrix")
diag(A) <- 0
A <- drop0(A)  # cleaning up
require(矩阵)

A您可以很快找到非零条目:

ij <- which(A != 0, arr.ind = TRUE)

# Subset to those on the diagonal:

ij <- ij[ij[,1] == ij[,2],,drop = FALSE]

# And set those entries to zero:

A[ij] <- 0

ij
rsparsematrix
函数非常简单。只需修改它,使其不选择任何对角线条目。使用
nrow=1e7,ncol=1e7,nnz=1e4
,它可能不会选择多于一个或两个。如果您的矩阵是方形的
dp@user2554330,谢谢,但这只是一个玩具示例,可能使用dgTMatrix格式并删除@i=@j处的条目?这并没有那么有效:如果您使用
Rprof(memory=TRUE)
打开内存分析,你会发现它确实分配了很多。
diag(A) <- 1
format(object.size(A), units = "Mb")
diag(A) <- 1
format(object.size(A), units = "Mb")
ij <- which(A != 0, arr.ind = TRUE)

# Subset to those on the diagonal:

ij <- ij[ij[,1] == ij[,2],,drop = FALSE]

# And set those entries to zero:

A[ij] <- 0
library(microbenchmark)
microbenchmark(A <- as(rsparsematrix(nrow = 1e7, ncol = 1e7, nnz = 1e4), "sparseMatrix"),
{A <- as(rsparsematrix(nrow = 1e7, ncol = 1e7, nnz = 1e4), "sparseMatrix"); diag(A) <- 0},
{A <- as(rsparsematrix(nrow = 1e7, ncol = 1e7, nnz = 1e4), "sparseMatrix");ij <- which(A != 0, arr.ind = TRUE);ij <- ij[ij[,1] == ij[,2],,drop = FALSE];A[ij] <- 0}, times = 10)