在 r 中递归相乘
Multiply recursiverly in r
具有以下矩阵和向量。
x<-matrix(c(1,4,7,
2,5,8,
3,6,9), nrow = 3)
w <- c(1,1,1)
res <- c()
什么是递归相乘的最佳方法直到获得所需的结果总和,例如:
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.
这是如何递归:
f <- function(x, w, res){
if (sum(res)>1000)
return(res)
res <- c(res, x%*%w)
f(x,w,res)
}
使用您预定义的对象调用它。即:
f(x, w, res)
哪个会给你:
# [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
如果您始终拥有相同格式的数据,那么可以采用类似的方式
res <- min(floor(1000 / cumsum(rowSums(x)))) * cumsum(rowSums(x)) + cumsum(rowSums(x))
min(res[res>1000])
无需循环即可给你答案。可以包装在一个函数中以处理除 1000 之外的另一个值。
至少我是这样理解你的问题的
具有以下矩阵和向量。
x<-matrix(c(1,4,7,
2,5,8,
3,6,9), nrow = 3)
w <- c(1,1,1)
res <- c()
什么是递归相乘的最佳方法直到获得所需的结果总和,例如:
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.
这是如何递归:
f <- function(x, w, res){
if (sum(res)>1000)
return(res)
res <- c(res, x%*%w)
f(x,w,res)
}
使用您预定义的对象调用它。即:
f(x, w, res)
哪个会给你:
# [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
如果您始终拥有相同格式的数据,那么可以采用类似的方式
res <- min(floor(1000 / cumsum(rowSums(x)))) * cumsum(rowSums(x)) + cumsum(rowSums(x))
min(res[res>1000])
无需循环即可给你答案。可以包装在一个函数中以处理除 1000 之外的另一个值。
至少我是这样理解你的问题的