How do i get aproximation of a function?

2 views (last 30 days)
Ciobanu Nicolae
Ciobanu Nicolae on 12 Apr 2021
Answered: Gargi Patil on 15 Apr 2021
I have the following function :
f (t) = 0.05*sin(1000*t)+0.5*cos(pi*t)-0.4*(10*t)
t are points distributed equidistantly between [0,1] for which i calculate values of f .
The following pairs (ti,f(ti)) are inputs for aproximation of function f with Lagrange and Least Squares.
This is what i tried, but doesn't seem to work, because i'm not sure if i'm doing f right
%Main function
t=linspace(0,1);
f = 0.05*sin(1000*t)+0.5*cos(pi*t)-0.4*sin(10*t);
lagrange(t,f); % returns coeficients of Lagrange polynomial of rank 1
least_squares(t,f) % returns coeficients of polynomial of rank n using least squares method
This is the lagrange function:
%Lagrange
function[L] = lagrange(x,y)
n = length(x);
lj= zeros(1,n)
Lj= zeros(n);
L=zeros(1,n);
jr=1:n;
for j=jr
mr=jr(jr~=j);%m-range 1<=m<=n, m~=j
lj=poly(x(mr));
mult=1/polyval(lj,x(j));
Lj(j,:)=mult*lj;
end
L=y*Lj;
X=-10:.1:10;
plot(x,y,'-*','linewidth',1,'markersize',5)
end
And the least_squares function:
function [yR] =least_squares(x,y)
stem(x,y);
a=[];
for i=1:length(x)
a=[a;x(i) 1];
end
c=a/y';
yR=c(1)*x+c(2);
plot(x,yR,"-*");
end

Answers (1)

Gargi Patil
Gargi Patil on 15 Apr 2021
Hi,
You can refer to the following thread for function approximation which includes a least squares method approach as well as Lagrange approximation:
You can also refer to the following link for other ways to approximate a function:

Categories

Find more on Polynomials in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!