Skip to content

matrix algebra for constructing a special matrix?

2 messages · Camarda, Carlo Giovanni, William Dunlap

#
I think f0 (from your code) and f1 give identical results

f0 <- function (m = 3, n = 4) 
{
   stopifnot(m>0, n>0)
    mn <- m * n
    k <- m + n - 1
    X <- matrix(0, mn, k)
    for (i in 1:n) {
        wr <- 1:m + (i - 1) * m
        wc <- rev(1:m + (i - 1))
        where <- cbind(wr, wc)
        X[where] <- 1
    }
    X
}

f1 <-
function (m = 3, n = 4) 
{
    stopifnot(m>0, n>0)
    whereInRow <- as.vector(outer(m:1, 0:(n - 1), `+`))
    mn <- m * n
    X <- matrix(0, mn, m + n - 1)
    X[cbind(1:mn, whereInRow)] <- 1
    X
}

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com