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