Reputation: 135
Might be a very silly question, but I cannot seem to find a proper way to create a sparse diagonal matrix in R. I've found the functions:
diag.spam()
spdiags()
and used them with library Matrix
and package spam
downloaded, but R did not seem to recognize these functions. Does anyone know a function or library I need to download?
I need it because I want to create diagonal matrices larger than 256 by 256.
Upvotes: 2
Views: 2183
Reputation: 135
Use bandSparse of the Matrix library.
to get an n-by-n matrix with m on its diagonal use, write:
bandSparse(n,n,0,list(rep(m, n+1)))
Upvotes: 1
Reputation: 226192
The Diagonal()
function in the Matrix
package. (Matrix
is a "recommended" package, which means it is automatically available when you install R.)
library(Matrix)
m <- Diagonal(500)
image(m)
Diagonal(n)
creates an n x n identity matrix. If you want to create a diagonal matrix with a specified diagonal x
, use Diagonal(x=<your vector>)
Upvotes: 7