2
votes

I am trying to create a recursive function that will do matrix multiplication n times.

My code is the following:

R <- function(P, n){

  R(P, n-1) %*% P

}

I would expect when this function is called with n = 3 to perform

(P %*% P) %*% P.

Using an example:

> P
     [,1] [,2] [,3]
[1,]  0.6  0.1  0.3
[2,]  0.2  0.7  0.1
[3,]  0.3  0.3  0.4

However when I call the function I get an error message.

Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
Error during wrapup: evaluation nested too deeply: infinite recursion / options(expressions=)?

Could you explain to me why the function does not work and how the code should be amended?

1

1 Answers

1
votes

Every recursive function should have a threshold at which point the recursive calls will stop. Your defined function R does not have this condition as the triggered error also mentions that

evaluation nested too deeply: infinite recursion

So,

R <- function(P, n){
    if (n==1) return(P)
    R(P, n-1) %*% P 
}

should solve your problem. Given your example:

r1 <- (P %*% P) %*% P
r2 <- R(P,3)
all(r1==r2)
#[1] TRUE