R,在数组的每个点积分 [英] R, Integrate at each point of array
问题描述
我坚持要计算数组每个点的积分。这个想法首先是创建一个函数( Integrand)。然后,创建第二个函数( MyConvolve)来计算必要的积分。
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.
非常感谢您的帮助!
推荐答案
我不确定并尝试计算
,但如果要评估 MyConvolve(Integrand,s)
,则
其中 s
接受 SomeMatrix
中的所有值,
然后 apply
就足够了。 / p>
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 )
这篇关于R,在数组的每个点积分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!