Filling sparse matrices

33 views
Skip to first unread message

Jan-Ole Koslik

unread,
Jun 18, 2025, 3:33:05 AMJun 18
to TMB Users
Hi,

I want to initialize and fill a sparse matrix inside my likelihood function. 
I only need to fill value on the super- and subdiagonal.

I felt like the most elegant way would be
 A <- Matrix::Matrix(0, m, m) # m is integer
 A[cbind(1:(m-1), 2:m)] <- some advector of suitable length

but this gives
Error in .local(x, i, j, ..., value) :
  not-yet-implemented 'Matrix[<-' method

Alternatively I tried
  i_up   <- 1:(m - 1)
  i_down <- 2:m
  up_vals   <- ...
  down_vals <- ...
  i <- c(i_up, i_down)
  j <- c(i_up + 1, i_down - 1)
  x <- c(up_vals, down_vals) 
  Q <- Matrix::sparseMatrix(i = i, j = j, x = x, dims = c(m, m))

but this gives
Error in getClass(Class, where = topenv(parent.frame())) :
  “gTMatrix” is not a defined class

So my question is simply, at this point in time, is there a way to do this semi elegantly without a loop?

Cheers
  


Jan-Ole Koslik

unread,
Jun 18, 2025, 3:37:04 AMJun 18
to TMB Users
And obviously, I could also construct A as a dense matrix and afterwards convert to sparse using something like A <- as(A, "sparseMatrix") but I don't know if that is wasteful.

Kasper Kristensen

unread,
Jun 18, 2025, 4:23:01 AMJun 18
to TMB Users
I think this issue is explained under ?AD. Just wrap AD(.) around Matrix(0,m,m):

F <- MakeTape(function(x) {A <- AD(Matrix(0, 5, 5)); A[cbind(1:4, 2:5)] <- x; A}, 1:4)

Jan-Ole Koslik

unread,
Jun 24, 2025, 4:19:34 AMJun 24
to TMB Users
Thanks!
Reply all
Reply to author
Forward
0 new messages