问题
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.
回答1:
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
回答2:
If you always have data on the same format then something along the lines
res <- min(floor(1000 / cumsum(rowSums(x)))) * cumsum(rowSums(x)) + cumsum(rowSums(x))
min(res[res>1000])
will give the answer to you without having to loop. Could be wrapped in a function to handle another value than 1000.
At least as how I understand your question
来源:https://stackoverflow.com/questions/39703542/multiply-recursiverly-in-r