简体   繁体   中英

vectorizing integral function in Matlab

I have the following function in 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

It accepts the position x and the parameter q0 and returns a scalar. How can I modify the function so that it can accept an array for x (a series of steps)? Ultimately, I want to fit this function to some data (to find the best fitted q0 , but then Matlab complains about matrix dimensions not agreeing, so I think that's because my current version of the function only accepts scalar x , not vector x .

You need to set 'ArrayValued' property to true for integral of an array valued function. Also there are some mistakes where you need to use element-wise operations . See the fixed code below:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM