user6508283
user6508283

Reputation:

Matrix Multiplication for loop of n number of months

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

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

this chain of multiplication taken places till 18 months. i have tried the below code: but not able to select which loop i should go for.

Matrix A:

2   3
4   2

Code:

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

b <- a
b

c = b %*% a
c

d <- c %*% b
d

e <- d %*% c
e

i am doing this multiplication manually till, i want to do it in chain loop fashion for 18 times.

Expected output:

a

      [,1] [,2]
[1,]    2    3
[2,]    4    2

b

      [,1] [,2]
[1,]    2    3
[2,]    4    2

c = b %*% a

c

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

d <- c %*% b

d

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

e <- d %*% c

e

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

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

Upvotes: 1

Views: 158

Answers (2)

Kushdesh
Kushdesh

Reputation: 1178

The multiplication results in Inf from 12th loop onward as the value become too large to be stored in R.

Following code will store the value in list matmull. Its first 2 elements are original value A and B. from 3rd element onward it has results of multiplications in the loop

A <- matrix(c(2L, 4L, 3L, 2L), 2, 2)
matmull <- rep(list(A), 20)
for(i in 1:18){
 matmull[[i+2]] <- matmull[[i]]%*%matmull[[i+1]]
}

Upvotes: 1

Gangesh Dubey
Gangesh Dubey

Reputation: 382

A for loop will help here

matA <- matrix(c(2,4,3,2), ncol=2,nrow=2)
output_var<- array(dim=c(2,2,18))
output_var[,,c(1:2)] <- matA
for (i in c(3:18))
{
  output_var[,,i] <- output_var[,,(i-1)]%*% output_var[,,(i-2)]
}
output_var

Upvotes: 1

Related Questions