[R] writing spdiags function for R

Ben Bolker bbolker at gmail.com
Fri Apr 13 22:09:52 CEST 2012


Ben Bolker <bbolker <at> gmail.com> writes:

> 
>   I'm not quite sure how to do it, but I think you should look
> at the ?band function in Matrix.  In combination with diag() of a 
> suitably truncated matrix, you should be able to extract bands
> of sparse matrices efficiently ...
> 


getband <- function(A,k) {
    n <- nrow(A)
    if (abs(k)>(n-1)) stop("bad band requested")
    if (k>0) {
        v <- seq(n-k) ## -seq((n-k+1),n)
        w <- seq(k+1,n)     ## -seq(n-k-1)
    } else if (k<0) {
        v <- seq(-k+1,n)
        w <- seq(n+k)
    } else return(diag(A))
    diag(band(A,k,k)[v,w,drop=FALSE])
}  
    
PS: I think this should extract the k^th off-diagonal
band in a way that should (?) work reasonably efficiently
with sparse matrices.  I have not tested it carefully,
nor benchmarked it.

  Ben Bolker



More information about the R-help mailing list