converting symbolic function to numerical representation for integration purpose
    조회 수: 4 (최근 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!


