Skip to content

Instantly share code, notes, and snippets.

@YoshiRi
Created April 7, 2017 15:49
Show Gist options
  • Save YoshiRi/a4707861066d6546f12e6d601c81fbb0 to your computer and use it in GitHub Desktop.
Save YoshiRi/a4707861066d6546f12e6d601c81fbb0 to your computer and use it in GitHub Desktop.
%% data
xhat = [ 1 2 3 4 1 2 3 4 -1 -2 -3 -4 -1 -2 -3 -4].';
yhat = [ 1 2 3 4 -1 -2 -3 -4 1 2 3 4 -1 -2 -3 -4].';
phat = [1 2 1 2 -1 5]; % a,b,c,d,e,f
Noise = 5*randn(16,1);
syms x y z
p = sym('p',[ 1 6]);
%% define function and error function
func = p(1) *x^2 + p(2)*y^2 +p(3)*x*y + p(4)*x+p(5)*y+p(6);
R = z - func;
S = R^2;
%% make data (observation)
zbuf = subs(func,{x,y},{xhat,yhat});
zhat = double(subs(zbuf,p,phat))+Noise;
%%
Jaco = jacobian(R,p);
Jacob = subs(Jaco,{x,y},{xhat,yhat});
SEF = subs(S,{x,y,z},{xhat,yhat,zhat});
r = subs(R,{x,y,z},{xhat,yhat,zhat});
iteration = 20;
vinit = phat.'*1.1;
v = vinit;
lambda = 1;
I = eye(size(Jacob,2));
for i = 1:iteration
J = double(subs(Jacob,p,v.'));
df = double(subs(r,p,v.'));
delta = - ( J.' * J + lambda * I)\J.' * df;
v = v + delta;
SOE = double(subs(SEF,p,phat));
SumOfError(i) = SOE.' * SOE;
end
display(v)
%% showing
figure(1);
plot3(xhat,yhat,zhat,'r+');
hold on;
ff = subs(func,p,phat);
ezsurf(ff,[-4,4,-4,4]);
hold off;
grid on;
view([-80 20])
%%
figure(2);
plot(SumOfError);
legend('Squared Error');
xlabel('iteration');
grid on;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment