converting symbolic function to numerical representation for integration purpose
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Randy Chen
am 8 Mär. 2021
Beantwortet: Walter Roberson
am 8 Mär. 2021
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 Kommentare
Akzeptierte Antwort
Walter Roberson
am 8 Mär. 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)
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Numerical Integration and Differentiation finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
