converting symbolic function to numerical representation for integration purpose
1 次查看(过去 30 天)
显示 更早的评论
Below are my codes attempting to compute numerical integrals using Lagrange polynomials
clear all
nvect=[5,15,30,50];
fcn=@(x) 1./(1+x.^2);
xs=sym('x');
int_exact=int(fcn(xs),xs,-5,5);
err=sym(zeros(length(nvect),1));
f = matlabFunction(fcn);
%a
for j=1:length(nvect)
n=nvect(j);
xj=linspace(-5,5,n+1);%-5+10/n(0:n);
xx = linspace(-5,5,1001); % points to plot approximation
intval=0;
for i=1:n+1
L_i=1;
for k=i:n+1
if k~=i
L_i=@(xs) (xs-xj(k))./(xj(i)-xj(k)).*L_i;
end
end
Li_int=int(L_i,xs,-5,5);
intval=intval+f(xj(i)).*Li_int;
end
err(j)=abs(int_exact-intval);
end
figure(100)
semilogy(nvect,err,'k','markersize',26)
However, I get the following error:
f = matlabFunction(fcn);
Undefined function 'matlabFunction' for input arguments of type 'function_handle'.
Error in hw_3 (line 9)
f = matlabFunction(fcn);
I just need to convert fcn to a numerical representation such that I can perform numerical integration. How should I change my code?
0 个评论
采纳的回答
Walter Roberson
2021-3-8
nvect=[5,15,30,50];
fcn=@(x) 1./(1+x.^2);
xs=sym('x');
int_exact=int(fcn(xs),xs,-5,5);
err=sym(zeros(length(nvect),1));
f = matlabFunction(fcn(xs));
%a
for j=1:length(nvect)
n=nvect(j);
xj=linspace(-5,5,n+1);%-5+10/n(0:n);
xx = linspace(-5,5,1001); % points to plot approximation
intval=0;
for i=1:n+1
L_i = @(xs) 1 * ones(size(xs));
for k=i:n+1
if k~=i
L_i=@(xs) (xs-xj(k))./(xj(i)-xj(k)).*L_i(xs);
end
end
Li_int = int(L_i(xs),xs,-5,5);
intval=intval+f(xj(i)).*Li_int;
end
err(j)=abs(int_exact-intval);
end
figure(100)
semilogy(nvect,err,'k','markersize',26)
0 个评论
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!