user6508283
user6508283

Reputation:

Matrix Multiplication using loop

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.

Upvotes: 2

Views: 1506

Answers (1)

jogo
jogo

Reputation: 12559

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)

Upvotes: 3

Related Questions