clc;clear
x = (0:0.5:5)';
Y = [2*x.^3.1+250 2*x.^3.2+160 8*x.^2.2+80 2*x.^2.5 ];
Y = Y+(rand(size(Y))-0.5)*40;
colshape1 = {'rp';'ro';'r*';'rs';'rd';'rv';'r+';'rx'};
figure(1)
plot2(x,Y,colshape1);
p=polyfit2(x,Y,4);
Ynew = polyval2(p,x);
figure(2)
colshape2 = {'b-p';'b-o';'b-*';'b-s';'b-d';'b-v';'b-+';'b-x'};
plot2(x,Ynew,colshape2);
figure(3)
plot2(x,Y,colshape1);hold on
plot2(x,Ynew,colshape2);
function y = polyval2( p , x )
x = reshape(x,numel(x),1);
n = size(p,1);
A = repmat(x,1,n).^repmat(0:1:n-1,numel(x),1);
y = A*p;
end
function p =polyfit2( x,Y ,n)
x = reshape(x,numel(x),1);
A = repmat(x,1,n).^repmat(0:1:n-1,numel(x),1);
p = (A'*A)\(A'*Y);
end
function plot2(x,Y,cs)
clen = cell(size(Y,2),1);
for i = 1:1:size(Y,2)
plot(x,Y(:,i),cs{i,1})
clen{i,1} = ['line',num2str(i)];
hold on
end
legend(clen);
box off
end