# Create dense matrix R
ncols <- 100;
R <- diag(rep(1, ncols));
for (i in 2:ncols)
R[i - 1, i] <- R[i, i - 1] <- 0.5;
# Create sparse matrix from dense matrix R
R.sparse <- glmmGS.SparseMatrix(R);
# Create sparse matrix from vectors of values, indices, and counts
# maximizing performance (requires O(ncols^2) workspace memory)
nz <- R != 0;
values <- c(R[nz]);
indices <- row(R)[nz] - 1L;
counts <- as.integer(c(0, cumsum(colSums(nz))));
R.sparse2 <- glmmGS.SparseMatrix(values, indices, counts);
# Create sparse matrix from vectors of values, indices, and counts
# allocating O(ncols) workspace memory
# 1) Set counts
counts <- integer(ncols + 1L);
count.total <- 0L;
counts[1] <- 0L;
for (j in 1:ncols)
{
nz <- which(R[, j] != 0);
count.total <- count.total + length(nz);
counts[j + 1] <- count.total;
}
# 2) Set values and indices
values <- double(count.total);
indices <- integer(count.total);
index <- 0L;
for (j in 1:ncols)
{
nz <- which(R[, j] != 0);
lnz <- length(nz);
kk <- index + 1:lnz;
values[kk] <- R[nz, j];
indices[kk] <- nz - 1L; # must be zero-based
index <- index + lnz;
}
# Build sparse matrix
R.sparse3 <- glmmGS.SparseMatrix(values, indices, counts);
Run the code above in your browser using DataLab