-2

I need a help to create function (math) to count some basic operations. Indeed i am a beginner and i don't really know how to do it. My task is to make function, which can value of polynomial from scalar or matrix.

First example polynomial is p1 = 1 + t, second polynomial is p2 = 1+ t + t^2

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

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

My expected results:

The use of a methodical function to calculate the value of a polynomial from a scalar:

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

The use of a methodical function to calculate the value of a polynomial from a matrix:

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
President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
naxer15
  • 31
  • 5
  • Why are the off-diagonals zero if there is an intercept? Please show your own attempts. I might use something like `rowSums(outer(x2, cumsum(x1) - 1, "^"), dims = 2) `. – Roland Jan 24 '19 at 15:03
  • Maybe i don't get you. This is exacly the same example. https://stackoverflow.com/questions/54295131/depending-on-the-argument-or-polynomial-from-the-scalar-or-polynomial-from-the-m – naxer15 Jan 24 '19 at 15:34
  • Why does `math( x1 = p1, x2 = a)` return 3, 0, 0, 2 ? not 3, 1, 1, 2? – Darren Tsai Jan 24 '19 at 15:53
  • Please do not attempt to deface your question, this is not allowed by Stackoverflow rules. – President James K. Polk Jan 24 '19 at 17:01

1 Answers1

-1
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)}}

Sorry i thought the problem has only 2 cases, now you can use the function power to tune it, grade is the degree of your polynom, c is the constant, and p the value of x ex: p(x) : c+x+x^2+x^3

edit: math function arguments are different now, first is the degree of the polynom, second the scalar or matrix. ex: math(2,2) = 7

  • Thats nice :) Is it possible to transform a code in a way that i can use it more flexible. It means if i can use more scalars that just p1,p2 ? – naxer15 Jan 24 '19 at 15:47