[R] simple matrix calculation
Petr Savicky
savicky at cs.cas.cz
Thu Mar 29 15:55:30 CEST 2012
On Thu, Mar 29, 2012 at 03:13:25PM +0200, Petr Savicky wrote:
> On Thu, Mar 29, 2012 at 01:16:49PM +0200, Kehl Dániel wrote:
> > Dear David, Ted, Kjetil, Petr,
> >
> > thank you, you guys did a great job, I'll use your ideas in the future
> > for sure.
> > After I sent the question I figured a way, see below.
> >
> > x <- 1:81
> > b <- 1:3
> > Q <- matrix(x,9,9)
> > result <- matrix(matrix(colSums(matrix(t(Q),3)),,3,TRUE) %*% b,3,3)
>
> Hi.
>
> I am not sure, what was the exact definition of the required
> result matrix. The previous solutions yield a different result.
> Were they correct?
>
> A solution equivalent to the previous ones, but formatted similarly
> to the above is
>
> b <- 1:3
> Q <- matrix(1:81,9,9)
>
> tmp <- matrix(colSums(matrix(t(Q),3)),,3,TRUE)
> R3 <- matrix(c(b %*% matrix(tmp, nrow=3)), nrow=3)
>
> # compare with a previous solution
> E <- Q * matrix(b, nrow=9, ncol=9) # component wise product
> C <- diag(3)[rep(1:3, each=3), ]
> R2 <- t(C) %*% E %*% C
>
> max(abs(R2 - R3)) # [1] 0
One more approach using aperm().
b <- 1:3
Q <- matrix(1:81,9,9)
A <- Q
dim(A) <- c(9,3,3)
A <- aperm(A, perm=c(1, 3, 2))
dim(A) <- c(27, 3)
R4 <- matrix(c(b %*% matrix(rowSums(A), nrow=3)), nrow=3)
Petr Savicky.
More information about the R-help
mailing list