Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a diagonal matrix from a sparse Vector

Suppose x is defined as

x <- as(c(1,1,0,0,1,0), "sparseVector")

I want to create a diagonal matrix where the diagonal elements are given by the entries in x.

I tried Diagonal(x = x), but I get the following error.

Error in Diagonal(x = x) : 'x' has unsupported class "dsparseVector"
like image 846
shani Avatar asked Feb 04 '26 04:02

shani


1 Answers

I think you are looking for sparseMatrix. e.g.:

library(Matrix)

x <- c(1,1,0,0,1,0)
x <- sparseMatrix(i = seq(x), j = seq(x), x = x)
x
# 6 x 6 sparse Matrix of class "dgCMatrix"
#                 
# [1,] 1 . . . . .
# [2,] . 1 . . . .
# [3,] . . 0 . . .
# [4,] . . . 0 . .
# [5,] . . . . 1 .
# [6,] . . . . . 0

To treat zeros in the original vector as sparse elements:

x <- c(1,1,0,0,1,0)
x <- sparseMatrix(i = which(x!=0), j = which(x!=0), x = x[which(x!=0)], 
  dims = rep(length(x), 2))
x
# 6 x 6 sparse Matrix of class "dgCMatrix"
#                 
# [1,] 1 . . . . .
# [2,] . 1 . . . .
# [3,] . . . . . .
# [4,] . . . . . .
# [5,] . . . . 1 .
# [6,] . . . . . .
like image 61
Marc in the box Avatar answered Feb 05 '26 21:02

Marc in the box