converting symbolic function to numerical representation for integration purpose

조회 수: 2 (최근 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?

채택된 답변

Walter Roberson
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개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by