# Demo entry 6850742

Quiz 10

Submitted by anonymous on Jul 11, 2019 at 06:48
Language: Matlab. Code size: 1.2 kB.

```hold on
error(1)=LSM(3,'-g');
error(2)=LSM(5,'-r');
error(3)=LSM(9,'-b');
hold off
disp(error)

function [error]= LSM(order,color)
% training data 把向量全部写成列向量的格式
x_train=[1:1:10]';n_train=size(x_train,1);% Return the size of vector
y_train=sin(x_train)+rand(n_train,1);

% test data
x_test=[1.5:1:10]';n_test=size(x_test,1);
y_test=sin(x_test)+rand(n_test,1);

% Least Squares solution: an example for 2
A_train=Vandermonde(order,x_train);% the input vector must be column vector
X=inv(A_train'*A_train)*A_train'*y_train; % (A^TA)^{-1}A^Tb

% calculate error of test data
A_test=Vandermonde(order,x_test);
e=abs(y_test-A_test*X);
error=e'*e;

% visualization
x_plot=[1:0.1:10]';
y_plot=Vandermonde(order,x_plot)*X;
hold on
plot(x_train',y_train','b.')% blue is train data
plot(x_test',y_test','r.')% red is test data
plot(x_plot',y_plot',color,'linewidth',1)
text(7,2.3,'blue','color','blue','Fontsize',8)
text(7.5,2.3,'dots are train points','Fontsize',8)
hold off

function [value_v]=Vandermonde(order,points_v)
x=points_v; % the input vector must be column vector
poly_v=[];
A=[ones(length(points_v),1)];
for i=1:order
poly_v=x.^i;
A=[poly_v,A];
end
value_v=A;
end
```

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.