Does Matlab's integral function pass the integration variable to the function handle one scalar at a time or as a vector?

Hello,
My integrand function contains a sum that depends on the integration variable, as follows:
tau = 1;
T = 20;
q = integral(@(t) f(t,tau),0,T)
function y = f(t,tau)
N = 0:floor(t,tau)
for i = 1:length(N)
n = N(i);
y = y + g(n,mod(t,tau) + (n+1)*tau) - g(n,mod(t,tau) + n*tau);
end
Where g is some function.
I'm not sure if the integral function is handling it correctly, because if it passes a vector t, the sum will not iterate over the correct range.
I would really appreciate any insights!
Thanks!

 채택된 답변

Stephen23
Stephen23 2024년 6월 24일
편집: Stephen23 2024년 6월 24일
"Does Matlab's integral function pass the integration variable to the function handle one scalar at a time or as a vector?"
By default it assumes that the function is vectorized, i.e. accepts a vector and returns a vector of the same size. This is explained in the documentation: "for scalar-valued problems, the function y = fun(x) must accept a vector argument, x, and return a vector result, y."
If your function only accepts a scalar, then set the 'ArrayValued' option to true:
q = integral(@(t) f(t,tau), 0,T, 'ArrayValued',true)

댓글 수: 3

Or use the code as follows - thus make a loop over the elements in the t-vector.
tau = 1;
T = 20;
q = integral(@(t) f(t,tau),0,T)
function y = f(tarray,tau)
y = zeros(size(tarray));
for j = 1:numel(tarray)
t = tarray(j);
N = 0:floor(t,tau)
for i = 1:length(N)
n = N(i);
y(j) = y(j) + g(n,mod(t,tau) + (n+1)*tau) - g(n,mod(t,tau) + n*tau);
end
end
end
All that has been said is true. HOWEVER, I would add a caveat. If you are having problems with the integral, then there is some potential the problem lies in your function g, and in what you do. The use of mod makes your function highly non-smooth.
As such, I would strongly recommend you plot the function you are trying to integrate here. I would do so, but you don't supply g, so we cannot help you more.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Numerical Integration and Differentiation에 대해 자세히 알아보기

제품

릴리스

R2022b

태그

질문:

2024년 6월 24일

댓글:

2024년 6월 24일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by