2

I have a matrix multiplication problem in a chain format. I only have a input Matrix A, will save Matrix B <- Matrix A. Need to multiply in the below fashion

C = B * A
D = C * A
E = D * A

A is a reference matrix for all the multiplication for each month. this chain of multiplication taken places till 18 months.

Matrix A:

2   3
4   2

Code:

a = matrix( c(2, 3, 4, 2), nrow=2, ncol=2, byrow = TRUE) 
b <- a 
c <- b %*% a
d <- c %*% a
e <- d %*% a
f <- e %*% a
g <- f %*% a

Each time A is the reference matrix for future multiplication with the result. This repeated for 18 times.

I have to manually right the above multiplication for 18 times, so looking for a loop.

Expected Output:

c <- b %*% a

c

     [,1] [,2]
[1,]   16   12
[2,]   16   16

d <- c %*% a

d

     [,1] [,2]
[1,]   80   72
[2,]   96   80

e <- d %*% a

e

     [,1] [,2]
[1,]  448  384
[2,]  512  448

f <- e %*% a

f

     [,1] [,2]
[1,] 2432 2112
[2,] 2816 2432

so this should be repeated for 18 times. Please help. Thanks in Advance.

the logic is different in the earlier question posted.

user2554330
  • 37,248
  • 4
  • 43
  • 90
  • Do you need all matrices or only the last result? You can write your own function for this task. – jogo Dec 12 '17 at 09:11
  • 1
    all the 18 matrices –  Dec 12 '17 at 09:12
  • 1
    Possible duplicate of [Matrix Multiplication for loop of n number of months](https://stackoverflow.com/questions/47765860/matrix-multiplication-for-loop-of-n-number-of-months) – Ronak Shah Dec 12 '17 at 09:29
  • there are some changes in the multiplication of matrix. logic is different. –  Dec 12 '17 at 09:30

1 Answers1

3

You can do:

Mpow <- function(A, n) {
  if (n==1) return(list(A))
  L <- list(A)
  P <- A
  for (i in 2:n) {
    P <- P %*% A
    L[[i]] <- P
  }
  return(L)
}

a = matrix( c(2, 3, 4, 2), nrow=2, ncol=2, byrow = TRUE) 
Mpow(a, 1)
Mpow(a, 2)
Mpow(a, 18)

You will get a list of the powers of the matrix. The matrix f in the question is the last element of Mpow(a,5).
Here is short variant of the function:

Mpow <- function(A, n) {
  L <- list(A)
  if (n==1) return(L)
  P <- A
  for (i in 2:n) L[[i]] <- (P <- P %*% A)
  return(L)
}

Without defining a new function you can do:

n <- 5
Reduce('%*%', rep(list(a), n), accumulate=TRUE)
jogo
  • 12,469
  • 11
  • 37
  • 42