%% SAR Lez. Classificatori discriminativi lineari

clear all;
close all;

n_points = 300;
mu1 = [5,5]';
Sigma1= [0.2,0.15;0.15,0.3];
x1 = mvnrnd(mu1,Sigma1,n_points);

mu2 = [1,1]';
Sigma2= [0.2,0.15;0.15,0.2];
x2 = mvnrnd(mu2,Sigma2,n_points);

label = [ones(n_points,1);ones(n_points,1).*-1];

h1=figure; set(gcf, 'name', 'classificatore lineare'); 
x2i = -x2;
x=[ones(n_points, 1), x1;ones(n_points, 1)*-1, x2i]';
w{1}=randn(3,1);%w e' della forma [b w(1) w(2)];
scatter(x1(:,1),x1(:,2)); hold on; scatter(x2(:,1),x2(:,2)); axis equal
distanza = -w{1}(1)/norm(w{1}(2:3));
angolo = atan(w{1}(3)/w{1}(2));  % in radianti
[px(1),py(1)] = pol2cart(angolo,distanza);
orto = angolo+pi/2;
versore = w{1}(2:3)./norm(w{1}(2:3));
quiver(px(1),py(1),versore(1),versore(2));   
lineLength = 5;
px(2) = px(1) + lineLength * cos(orto);
py(2) = py(1) + lineLength * sin(orto);
px(3) = px(1) - lineLength * cos(orto);
py(3) = py(1) - lineLength * sin(orto);
plot(px,py);
hold off

    

for k = 2:50
    rho(k)=1/k;
    res=w{k-1}'*x;
    bad = res<0;
    w{k}= w{k-1}+rho(k).*sum(x(:,bad),2);
    scatter(x1(:,1),x1(:,2)); hold on; scatter(x2(:,1),x2(:,2)); axis equal
    distanza = -w{k}(1)/norm(w{k}(2:3));
    angolo = atan(w{k}(3)/w{k}(2)); % in radianti
    [px(1),py(1)] = pol2cart(angolo,distanza);
    orto = angolo+pi/2;
    versore = w{k}(2:3)./norm(w{k}(2:3));
    quiver(px(1),py(1),versore(1),versore(2));
    lineLength = 5;
    px(2) = px(1) + lineLength * cos(orto);
    py(2) = py(1) + lineLength * sin(orto);
    px(3) = px(1) - lineLength * cos(orto);
    py(3) = py(1) - lineLength * sin(orto);
%     plot_x = linspace(min([x1(:,1);x2(:,1)]), max([x1(:,1);x2(:,1)]), 30);
%     plot_y = (-1/w{k}(3))*(w{k}(2)*plot_x + w{k}(1));
%     plot(plot_x, plot_y, 'k-', 'LineWidth', 2)
    plot(px,py)
    hold off
    pause(0.05)
end

    

