Optimize the construction of a function for quadrature purposes

3 次查看(过去 30 天)
Hello,
I want to compute the integral of a function which is the linear combination of some known function family (here, Fourier functions):
MyInt = integral(@(t) myfun(t), 0, 2*pi);
My function myfun(t) is built as follows:
function Output = myfun(t)
Output = 0;
for p = 1:20
Output = Output + 1/p.*cos(p*t);
Output = Output + 1/(2*p).*sin(p*t);
end
I can't think of a way to vectorize what's above without the for loop? Can we do better?
Thank you

采纳的回答

Torsten
Torsten 2023-2-15
编辑:Torsten 2023-2-15
MyInt = integral(@myfun, 0, 2*pi)
MyInt = -5.5511e-16
function Output = myfun(t)
p = (1:20).';
Output = sum(1./p.*cos(p.*t) + 1./(2*p).*sin(p.*t),1);
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Numerical Integration and Differentiation 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by