-1

Calling diag(x) is apparently very slow. Is there not a faster way to set up a diagonal matrix? It seems like a fairly easy operation, yet R takes forever.

Also, using the diagonal matrix later on in multiplications is also extremely slow. So if I wanted to use sparse matrices, is there a faster way to set up a diagonal sparse matrix?

wibeasley
  • 5,000
  • 3
  • 34
  • 62
Janus
  • 165
  • 4
  • 2
    we need more context, please. How big a matrix are you trying to set up? How slow is "takes forever"? How much memory do you have? Are you going to work with sparse matrices, in which case you should probably use `Matrix::Diagonal` ? – Ben Bolker Oct 23 '19 at 23:01
  • 1
    Related/duplicate: [How to create a diagonal matrix in R?](https://stackoverflow.com/q/7102117/914686) – Werner Oct 23 '19 at 23:12
  • I'm not sure this is an exact duplicate (but feel free to vote to close for that reason). Original version doesn't specifically ask about performance or ask for a sparse matrix (admittedly one of the *answers* uses `Matrix::diagonal`). Sure would be nice if we got more context though ... – Ben Bolker Oct 23 '19 at 23:29
  • If my answer solved your problem, you are encouraged to click the check-mark to accept it. – Ben Bolker Oct 26 '19 at 23:23

1 Answers1

2

I don't have any idea what "too slow" means, but

Matrix::Diagonal(n=100)

will produce a 100x100 (sparse) identity matrix, and

Matrix::Diagonal(x=1:100)

will produce a sparse diagonal matrix with entries 1, 2, ... 100

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453