0

I'm stuck with computing the integral at each point of an array. The idea is first to create a function ("Integrand"). Then, create a second function ("MyConvolve") that computes the necessary integral.

Here's what I did up to now:

Integrand = function(s,x)
{ 1/4*(abs(x-s)<=1)*(abs(s)<=1) }

MyConvolve = function(func,data)
{ return( integrate(func, lower=-Inf, upper=Inf, data) ) }

Now, running the code with some array, I get an error message:

SomeMatrix = replicate(10, rnorm(10))
MyConvolve(Integrand, SomeMatrix)

Which ends up with the following error message:

Error in integrate(func, lower = -Inf, upper = Inf, data) :
evaluation of function gave a result of wrong length

I already tried vectorizing the function, but still ended up with error messages.

Thank you very much for your help!

RomainD
  • 301
  • 1
  • 2
  • 9
  • What do you mean by "computing the integral at each point of an array" (your array is 2-dimensional, but `integrate` computes integrals of univariate functions)? For instance, how would you compute it at one point? – Vincent Zoonekynd Apr 10 '13 at 10:34
  • Hi Vincent! Suppose I have a 10x10 matrix. Now I want my code to compute the integral (in my case the convolution product) for each single matrix entry. Hence, input a 10x10 matrix and get out a 10x10 matrix of the convolution products. Currently, the code is fine if I input a single point of evaluation. But multiple points of evaluation don't work. Thanks! – RomainD Apr 10 '13 at 11:24

1 Answers1

0

I am not sure I understand what you are trying to compute, but if you want to evaluate MyConvolve(Integrand,s), where s takes all the values in SomeMatrix, then apply is sufficient.

sapply( SomeMatrix, function(s) MyConvolve( Integrand, s )$value )

However, the dimensions of the matrix are lost. You can recover them as follows:

result <- SomeMatrix
result[] <- sapply( SomeMatrix, function(s) MyConvolve( Integrand, s )$value )
Vincent Zoonekynd
  • 31,893
  • 5
  • 69
  • 78
  • Thanks Vincent, this seems to be what I've been looking for! I tried sapply in several ways, but could not get it right. In case I'll experience some (unexpected) issues, I'll let you know. Have a great day! – RomainD Apr 10 '13 at 12:12