Domanda

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!

È stato utile?

Soluzione

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 )
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top