首页 > 代码库 > Polynomial Curve Fitting

Polynomial Curve Fitting

pcf.m

inputSamp = (0:0.1:1);result = sin(2*pi*inputSamp);gsNoise = randn(11,1)*0.1;observation = result + gsNoise;x=(0:0.01:1);y=sin(2*pi*x);%{figure;plot(inputSamp, observation, *, x, y, --r.);set(gca, XLim, [-0.2 1.2]);set(gca, YLim, [-1.5 1.5]);%}%Y = w0+w1*x+w2*(x^2)+.....theta = zeros(4,1);theta = CalcParameter(inputSamp,observation, theta);predVal = CalValue(x, theta);figure;plot(inputSamp, observation, *, x, y, --r., x, predVal, --g.);set(gca, XLim, [-0.2 1.2]);set(gca, YLim, [-1.5 1.5]);

CalcParameter.m

function theta = CalcParameter(inputSamp,observation, theta)MaxIteration = 8000;alpha = 1;m = length(theta);n = length(inputSamp);data = ones(m, n);data(1,:)=ones(1, n);for i = 2:m    data(i,:) = data(i-1,:).*inputSamp;endfor i = 1:MaxIteration    predVal = data*theta;    error = predVal - observation;    grad = data*error;    theta = theta  - alpha*grad/n;    er = mean(abs(error));    fprintf(Iter %d: error : %f\n, i, er);endend

CalValue.m

function predVal = CalValue(x, theta)m = length(theta);n = length(x);data = ones(n, m);for i = 2:m    data(:,i) = data(:,i-1).*x;endpredVal = data*theta;end

 

Polynomial Curve Fitting