1

x is the reference matrix for all the iterations. there are total 2 matrices.

matrix A
1   4   1   4
4   2   4   2
2   3   2   3
3   3   3   3

matrix B
1   4   1   4
4   2   4   2
2   3   2   3
3   3   3   3


matrix x
4   1   4   3
2   4   2   2
3   2   3   5
3   5   1   1

Here matrix A and B is same. We need a matrix multiplication in the below fasion:

C <- B %*% x
D <- C %*% x
E <- D %*% x 
F <- E %*% x 

x is the reference matrix for all the iterations. this multiplication is done for 15 times so need help in writting in a loop or function.

Uwe
  • 41,420
  • 11
  • 90
  • 134
Prad
  • 339
  • 1
  • 10
  • 2
    So you need a [recursive function](https://stackoverflow.com/questions/5273857/are-recursive-functions-used-in-r) basically – Sotos Dec 21 '17 at 08:42
  • yes Sotos should be multiplied 15. – Prad Dec 21 '17 at 08:42
  • 1
    Try `nm1 <- LETTERS[2:5]; for(i in 2:5) assign(LETTERS[i+1], get(LETTERS[i]) %*% x)` – akrun Dec 21 '17 at 08:45
  • 1
    Possible duplicate of [Matrix Multiplication using loop](https://stackoverflow.com/questions/47768767/matrix-multiplication-using-loop) – kath Dec 21 '17 at 09:08
  • @kath just checked that question, the reference matrix is it self the input that is A. but here in my question the input matrix is A and reference multiplication matrix is X so mine is the different question. – Prad Dec 21 '17 at 09:13
  • @akrun tried with your code was able to print B C D E, can you please explain me your code. – Prad Dec 21 '17 at 09:31
  • 1
    @pradnya I added only for 2:5 if you want it can be `for(i in 1:14) assign(LETTERS[1+1], get(LETTERS[i]) %*% X)` At each step, it assigns to an object, at the same time, it gets object created before and multipy with "X" – akrun Dec 21 '17 at 09:33

1 Answers1

2

If you only want the last matrix we can use a recursive function, as suggested by Sotos:

A <- matrix(runif(9), 3) 
X <- matrix(runif(9), 3) 

repmult <- function(A,x,reps)
{
  if(reps==0){
    return(A)
  }
  else
  {
    repmult(A%*%x,x,reps-1)
  }
}

repmult(A,X,15)

If you want all intermediate results in a list as well, we can modify the function from the answer on this SO question (although you may want to change its name):

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

Mpow(A,X,3)
Florian
  • 24,425
  • 4
  • 49
  • 80
  • i tried the above code: But the problem here is, i am only getting the direct anwser which is the 15th matrix. I want all the matrices like 1,2,3,4,5 ....upto 15. please help me. – Prad Dec 21 '17 at 09:26
  • Hi pradnya, I added a second function for that. – Florian Dec 21 '17 at 09:33