Search code examples
rintegral

the integrand has the sum of a vector


I need to integrate a function integrand. The function integrand is a product of A and B. A = 2/(upper-lower), and B is the sum of a vector depending on the input parameter.

if I have

 X = 7, 
 N = 50, 
 Ck # a vector of N elements,
 uk # a vector of N elements, 
 upper = 10, 
 lower = -10

and my R-code is as follow:

   integrand<-function(y)
   {
     df<-matrix(,nrow = N,ncol = 1);

     res<-NA;

     for(k in 1:N)
       df[k]<-Ck[k]*cos(y-lower)*uk[k]

     res<-2/(upper-lower)*sum(df);

     return(res)

    }

   integrate(function(x){integrand(x)},upper=X,lower = lower)$value

I got an error message after running the code:

 Error in integrate(function(x) { : 
 evaluation of function gave a result of wrong length

what is my mistake?

Additionally, if df[k]<-Ck[k]*(cos(y-lower)*uk[k]), may I write the code as:

 integrand<-function(y)
  {
    df <-Ck*cos((y - lower)*uk)

    2 * sum(df) / (upper - lower)
  }

 integrate(Vectorize(integrand),upper=X,lower = lower)$value

THANKS!


Solution

  • Use

    integrand <- function(y) {
      mat <- tcrossprod(Ck * uk, cos(y - lower))
      2 * colSums(mat) / (upper - lower)
    }
    

    Explanation:

    If you read the documentation of function integrate, you see that f must be a vectorized function (i.e. you give it a vector argument and it returns a vector of the same length).