简体   繁体   中英

Matlab's sparse(i,j,s,m,n) equivalent in R

I'm working with R.

I have a matrix structure but stored in three lists IND1, IND2, and VAL, each of the same length N; I need to store the values in VAl in a matrix MAT such that:

for each i in 1 to N:
    MAT[IND1(i), IND2(i)] == VAL(i)

As you can guess the final size of MAT is not necessarily NxN, but I do know what the size must be (call it m if you need to know the size, since for me it must be a square matrix).

Matlab has a nice function to create a sparse matrix that does exactly this, but i need to accomplish this in the language R, hopefully without loops, does anyone know if this can be done and would please tell me how. Thanks in advance.

PS: I've tried the obvious:

MAT <- matrix(nrow=m, ncol=m)
MAT[IND1, IND2] <- VAL

but I get a weird result (all rows have the same repeated value)

DWin is right - the Matrix package is the way to go. However, if you have a lot of data, I have found that the replacement type of value substitution can get hung up or take a long time. A better way might be to make a class sparseMatrix object and then convert to class matrix if needed. Ex.

set.seed(1)
n=50
x <- sample(seq(100), n)
y <- sample(seq(100), n)
z <- runif(n)
cbind(x,y,z)

library(Matrix)
s.mat <- sparseMatrix(i=x, j=y, x=z)
dim(s.mat)
image(s.mat)

#convert to a class matrix if needed
mat <- as.matrix(s.mat)
mat[which(mat==0)] <- NaN

在此输入图像描述

The Matrix package offers a variety of sparse matrix classes. After a sparse matrix object is created you would load the values in precisely the manner you describe above:

library(Matrix)
?Matrix

... will get you started. By the way, the code for loading a dense matrix in the manner you illustrated would be:

M <- matrix(NA, nrow=max(c(IND1,IND2)), ncol=max(c(IND1,IND2)) ) # could use higher numbers
M[ cbind(IND1, IND2) ] <- VAL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM