In: Advanced Math
Write a MATLAB code for discrete least squares trigonometric polynomial S3(x), using m = 4 for f(x) = e^x * cos(2x) on the interval [-pi, pi]. Compute the error E(S3).
%%Matlab code for least square trigonometric polynomial
clear all
close all
%function for actual data
fun1=@(x) exp(x).*cos(2*x);
%function for trigonometric least square
fun2=@(x,a0,a1,a2,a3,a4,a5,a6,a7,a8)
a0+a1.*cos(x)+a2.*sin(x)+a3.*cos(2*x)+a4.*sin(2*x)+a5.*cos(3*x)+a6.*sin(3*x)+a7.*cos(4*x)+a8.*sin(4*x);
%all data points
xx=linspace(-pi,pi);
yy=fun1(xx);
%plotting actual data
plot(xx,yy)
xlabel('x')
ylabel('f(x)')
%creating matrix for least square
for i=1:length(xx)
A(i,1)=1;
A(i,2)=cos(xx(i));
A(i,3)=sin(xx(i));
A(i,4)=cos(2*xx(i));
A(i,5)=sin(2*xx(i));
A(i,6)=cos(3*xx(i));
A(i,7)=sin(3*xx(i));
A(i,8)=cos(4*xx(i));
A(i,9)=sin(4*xx(i));
b(i,1)=yy(i);
end
%least square solution
cc=A\b;
fprintf('The coefficients are for least square
solution\n')
for i=1:9
fprintf('\t a%d=%f\n',i-1,cc(i))
end
%fitted data
yy1=fun2(xx,cc(1),cc(2),cc(3),cc(4),cc(5),cc(6),cc(7),cc(8),cc(9));
hold on
plot(xx,yy1)
legend('Actual data','fitted data','location','best')
fprintf('Error in Trigonometric least square solution is %f\n',
norm(yy-yy1))
box on
%%%%%%%%%%%%%%%% End of Code %%%%%%%%%%%%%%%%