? stato filtrato un testo allegato il cui set di caratteri non era indicato... Nome: non disponibile URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20121026/fb15c10c/attachment.pl>
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
-----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.