Alfredo_MF Alfredo_MF - 2 months ago 6
R Question

Multiply recursiverly in r

Having the following matrix and vector.

x<-matrix(c(1,4,7,
2,5,8,
3,6,9), nrow = 3)
w <- c(1,1,1)
res <- c()


What is the best way to multiply recursiverly till obtain a desire sum of the results as exemplified:

res[1]<-w %*%x[1,]
res[2]<-w %*%x[2,]
res[3]<-w %*%x[3,]
res[4]<-w %*%x[1,]
res[5]<-w %*%x[2,]

sum(res)>1000 #Multiply recursiverly till the sum of the results sum(res) goes further than 1000.

Answer

Here is how to do it recursively:

f <- function(x, w, res){
    if (sum(res)>1000)
        return(res)
    res <- c(res, x%*%w)
    f(x,w,res)
}

Call it with your pre-defined objects. That is:

f(x, w, res)

Which will give you:

# [1]  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6 15 24  6
# [62] 15 24  6 15 24  6 15 24