clear all
close all

N = 10;
T = 5;
r = 0.1;

s = 2308;
% s = 5346;

rng(s);

X = sign(randn(N,T) - 1);
Z = zeros(N+1,T);
Z(1:N,:) = X;
Z(N+1,:) = 1;
X = Z;

W = randn(N+1,N+1);
    
for i = 1:100

    err = 0;        
    for t = 1:T-1
        err = err + sum(abs(X(:,t+1) - sign(W*X(:,t))));
        W = W + r*(X(:,t+1) - sign(W*X(:,t))) * X(:,t)';   
    end    

    err_iter(i) = err;
end


Y = zeros(N+1,T);
Y(:,1) = X(:,1);
for t = 1:T-1
    Y(:,t+1) = sign(W*Y(:,t));
end

norm(X - Y)


figure('Position',[100 100 200 400]);
colormap(gray)
s = [N T];
xrange = [1 T]; % imagesc only needs the endpoints
yrange = [1 N];

dx = diff(xrange)/(s(2)-1);
dy = diff(yrange)/(s(1)-1);
xg = linspace(xrange(1)-dx/2,xrange(2)+dx/2,s(2)+1);
yg = linspace(yrange(1)-dy/2,yrange(2)+dy/2,s(1)+1);
hi = imagesc(xrange,yrange,X(1:N,:)); hold on;

hm = mesh(xg,yg,zeros(s+1));
hm.FaceColor = 'none';
hm.EdgeColor = 'k';
axis off;
axis equal;

