function w = wta(x, w)
% WTA      -   Winner Takes All training algorithm
%
% INPUT
%   x      -   training patterns
%   w      -   initial weight
%
% OUTPUT
%   w       -   updated weight
%
% Andy Beirle
% Ricky Chan
% ECE 595C
% October 9, 2004

alpha = 0.5;

if nargin ~= 2
    x = [-1 0 1/sqrt(2);
          0 1 1/sqrt(2)];
    w = [ 0 -2/sqrt(5) -1/sqrt(5);
         -1  1/sqrt(5)  2/sqrt(5)];
end

[rowx, colx] = size(x);
[roww, colw] = size(w);
maxResult = 0;
maxIndex = 0;

figure(1)
plot(x(1,:), x(2,:), 'rx', w(1,:), w(2,:), 'bo')
title('Initial Weight')
axis([-max(max(abs(x)))-.25 max(max(abs(x)))+.25 -max(max(abs(x)))-.25 max(max(abs(x)))+.25])

% Looking for the index of the winning weight
for counter = 1:colx
    x(:,counter) = x(:,counter)/norm(x(:,counter));
    for counter2 = 1:colw        
        w(:,counter2) = w(:,counter2)/norm(w(:,counter2));    
        dotProduct = dot(w(:,counter2),x(:,counter));    
        if dotProduct > maxResult
            maxResult = dotProduct;
            maxIndex = counter2;
        end
    end
    % Updating the winning weight
    w(:,maxIndex) = w(:,maxIndex) + alpha*(x(:,counter) - w(:,maxIndex));
    % Scaling it to have a unit length
    w(:,maxIndex) = w(:,maxIndex)/norm(w(:,maxIndex)); 
end
 
% Plotting the result
figure(2)
plot(x(1,:), x(2,:), 'rx', w(1,:), w(2,:), 'bo')
title('Final Weight')
axis([-max(max(abs(x)))-.25 max(max(abs(x)))+.25 -max(max(abs(x)))-.25 max(max(abs(x)))+.25])