在 r 中递归地相乘 [英] Multiply recursiverly in r

查看:19
本文介绍了在 r 中递归地相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有以下矩阵和向量.

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. 

推荐答案

以下是如何递归:

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)

哪个会给你:

# [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

这篇关于在 r 中递归地相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆