[R] simple matrix calculation

Petr Savicky savicky at cs.cas.cz
Thu Mar 29 15:13:25 CEST 2012


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

I believe that using dim(Q) <- c(3,3,3,3) and function
aperm() as suggested by David can simplify this approach.

Petr Savicky.



More information about the R-help mailing list