# [R] simple matrix calculation

Petr Savicky savicky at cs.cas.cz
Thu Mar 29 08:48:36 CEST 2012

```On Wed, Mar 28, 2012 at 10:46:11PM +0200, Kehl Dániel wrote:
> Dear list-members,
>
> I have a 9-by-9 matrix lets call it A with first row a11, a12, a13,...,
> a19 etc.
> I also have a vector of length 3 (B).
> I want to construct a matrix of size 3x3 in the following way:
> - divide matrix A to 9 3x3 blocks
> - first is
>         a11, a12, a13
>         a21, a22, a23
>         a31, a32, a33
> - I want to get rowSums of this A1 matrix
> - Multiply A1*B and get a scalar, the first element of my new 3x3 matrix.

Hi.

Try the following, which is based on the solution by Ted Harding.

# some input
A <- matrix(1:81, nrow=9, ncol=9)
B <- 7:5

# compute the 3 x 3 matrix
C <- diag(3)[rep(1:3, each=3), ]
D <- cbind(rbind(B, 0, 0), rbind(0, B, 0), rbind(0, 0, B))
R1 <- D %*% A %*% C

# compare with another approach
E <- A * matrix(B, nrow=9, ncol=9) # component wise product
C <- diag(3)[rep(1:3, each=3), ]
R2 <- t(C) %*% E %*% C

max(abs(R1 - R2)) # [1] 0

Hope this helps.

Petr Savicky.

```