Reputation: 65
I need some help creating a function that evaluates a polynomial of the form:
With the arguments of vector x and coefficient vector. I need to use a for loop to calculate to polynomial sum, but not to calculate the different values of x. The last thing I need to do is do an error check if the coefficient vector's length is less than 2. Here's what I have tried:
directpoly<-function(x,coef) {
total=coef[1]
for(n in length(coef)) {
total<-total+coef[-1]*x^n-1
}
ifelse(length(coef)>2,"Vector is less than length 2")
}
I know that attempt is probably embarrassingly terrible but I'm very new to this program and very out of my depths, I've never coded in anything before. Thanks in advance.
Upvotes: 0
Views: 117
Reputation: 84599
x <- 3
coefs <- c(4,5,3,1)
n <- length coefs
result <- sum(coefs * x^(0:(n-1))
For the check:
if(n < 2){
stop("n must be > 1")
}
Upvotes: 2