Message-ID: <E66794E69CFDE04D9A70842786030B9337E8A9@PA-MBX04.na.tibco.com>
Date: 2012-10-26T16:01:22Z
From: William Dunlap
Subject: matrix algebra for constructing a special matrix?
In-Reply-To: <5B2F2CD24AD2764D898AF5A7B9A2ABBF02C36BD3@hermes.demogr.mpg.de>
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
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Camarda, Carlo Giovanni
> Sent: Friday, October 26, 2012 8:13 AM
> To: r-help at stat.math.ethz.ch
> Subject: [R] matrix algebra for constructing a special matrix?
>
> Dear R-users,
>
> would it be a better way to construct the matrix below without using any for-loop or
> model.matrix? preferably with some matrix algebra?
>
> Thanks in advance,
> Carlo Giovanni Camarda
>
> ## dimensions
> m <- 3
> n <- 4
> mn <- m*n
> k <- m+n-1
>
> ## with a for-loop
> 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
> }
>
> ## using model.matrix
> ff <- factor(c(outer(m:1, seq(0,m), "+")))
> X1 <- matrix(model.matrix(~-1+ff), mn, k)
>
>
>
> ----------
> This mail has been sent through the MPI for Demographic ...{{dropped:10}}
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.