从 R 中的标量或矩阵计算多项式值的函数

Function to calculate value of polynomial from scalar or matrix in R

我需要帮助来创建函数(数学)来计算一些基本运算。事实上,我是一个初学者,我真的不知道该怎么做。 我的任务是制作函数,它可以从标量或矩阵中取多项式的值。

第一个示例多项式是 p1 = 1 + t,第二个多项式是 p2 = 1+ t + t^2

a <- matrix( c( 2, 0, 0, 1), 2, 2)

p1 <- c( 1, 1)
p2 <- c(1, 1, 1)

我的预期结果:

使用有条不紊的函数从标量计算多项式的值:

math( x1 = p1, x2 = 0)
output: 1
math( x1 = p1, x2 = 2)
output: 3
math( x1 = p2, x2 = 2)
output: 7
math( x1= p2, x2 = 1)
output: 3

使用有条不紊的函数从矩阵计算多项式的值:

math( x1 = p1, x2 = a)
     [,1] [,2]
[1,]    3    0
[2,]    0    2

math( x1= p2, x2 = a)

     [,1] [,2]
[1,]    7    0
[2,]    0    3
power <- function(grade,p){
  c=1
  b=0

  for (i in 1:grade) {
    b=p*b+p
    i=i+1

  }
return(c+b)}


math <- function(a,b){
 if(class(b)=="numeric"){
  return(power(a,b))

}
  if(class(b)=="matrix"){matrix= matrix(0,nrow(b),nrow(b))
  for (i in 1:nrow(matrix)) {
    matrix[i,i] <- power(a,b[i,i])
  }
    return(matrix)}}

抱歉,我以为问题只有2种情况,现在你可以使用函数power来调整它,grade是你的多项式的次数,c是常数,p是x的值 例如:p(x) : c+x+x^2+x^3

编辑:数学函数参数现在不同了,首先是多项式的次数,其次是标量或矩阵。例如:数学(2,2) = 7