在 Matlab 中向量化积分函数

vectorizing integral function in Matlab

我在 Matlab 中有如下函数:

function y = exact_func(q0,x)
q = q0/(1+x^2);
h_func = @(t) sech(t).^2;
fun = @(t) log(1+q*h_func(t));
y = integral(fun,-Inf,Inf)/(q*integral(h_func,-Inf,Inf));
end

它接受位置 x 和参数 q0 和 returns 一个标量。如何修改该函数,使其可以接受 x 的数组(一系列步骤)?最终,我想让这个函数适合一些数据(找到最合适的 q0,但是 Matlab 抱怨矩阵尺寸不一致,所以我认为这是因为我当前版本的函数只接受标量 x,不是向量 x.

您需要设置'ArrayValued' property to true for integral of an array valued function. Also there are some mistakes where you need to use element-wise operations。请参阅下面的固定代码:

q = q0 ./ (1 + x.^2);    
%       ↑       ↑     You need to use element-wise operations as indicated 
h_func = @(t) sech(t).^2;
fun = @(t) log(1 + q*h_func(t)); %---↓------↓ 
y = integral(fun,-Inf,Inf,'ArrayValued',1) ./ (q*integral(h_func,-Inf,Inf));