converting symbolic function to numerical representation for integration purpose

2 vues (au cours des 30 derniers jours)
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?

Réponse acceptée

Walter Roberson
Walter Roberson le 8 Mar 2021
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)

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by