Reputation: 59
Here is my integrand()
integrand<-function(x,vecC)
{
as.numeric((2/(b-a))*vecC%*%as.matrix(cos((x-hat.a)
*(seq(0,N-1,length=N)*pi/(b-a)))))
}
it can produce the value. For example, for
a<-1
b<-10
vecC<-t(as.matrix(rnorm(80)))
hat.a<--1.2
N<-80
I get
> integrand(1.4,vecC)
[1] -0.3635195
but I met problem when I run the following code for integration
> integrate(function(x){integrand(x,vecC)},upper = 3.4,lower = 1)$value
and the error message is
Error in integrate(function(x) { : evaluation of function gave a result of wrong length In addition: Warning message: In (x - hat.a) * (seq(0, N - 1, length = N) * pi/(b - a)) : longer object length is not a multiple of shorter object length
Upvotes: 1
Views: 65
Reputation: 1834
If you read the help page for integrate
you will see that the function passed to integrate
should return a vector.
So the solution to your error is to use Vectorize
like this
Define your function separately as
f <- function(x){integrand(x,vecC)}
Now define a vectorized version of this function like so
fv <- Vectorize(f,"x")
and then
integrate(fv,upper = 3.4,lower = 1)$value
will give you a result.
Upvotes: 2