
clear all
%% Datapoints

x=[1.4 1.6 0.05 1.7 1 0.05 0.3 -0.8 1.7]';
y=[-1.9 -2.3 1 -2.7 -1.2 0.8 0.6 2.7 -2.4]';

%% Initialization of the two consensus algorithms

% number of nodes
n=9;

% number of iterations of consensus
T=100;

% cell arrays: the element {i,k}, collects quantities of node i at iteration k
xgg=cell(n,T);
xgy=cell(n,T);

% xgg at iteration k is a 2x2 matrix
xggk=zeros(2,2);
% xgy at iteration k is a 2x1 vectors
xgyk=zeros(2,1);

% initialize th cell arrays with zero matrices/vectors
for i=1:n
    for k=1:T
        xgg{i,k}=xggk;
        xgy{i,k}=xgyk;
    end
end
% inizialization of xgg(0) and xgy(0)
for i=1:n
    gi=[x(i),1]';
    xgg{i,1}=gi*gi';
    xgy{i,1}=gi*y(i);
end

%% Consensus algorithms
%%%%%%%%%%%%%%%%%%%%%
% INSERT YOUR CODE HERE 
%%%%%%%%%%%%%%%%%%%%%%
% Define thw adjacency matrix of the digraph
% obtained using the Metropolis-Hasting model
%
% etc ...



%% Compute the least squares estimate in each node
%%%%%%%%%%%%%%%%%%%%%
% INSERT YOUR CODE HERE 
%%%%%%%%%%%%%%%%%%%%%%

%% Compare with the centralized least squares estimate

G=[x,ones(9,1)];
thCEN=inv(G'*G)*G'*y

% thCEN=[-2.1091; 1.0404]


%% Plot the updates of xgy
% to check visually that consensus is reached on this variable

figure(1);clf
hold on
% set a colormap
CM = jet(n);
for i=1:n
xgy_m=[xgy{i,:}];
plot(xgy_m(1,:),xgy_m(2,:),'color',CM(i,:),'LineWidth',2)
% Plot the initial state with a differnt marker
plot(xgy_m(1,1),xgy_m(2,1),'ro--','MarkerEdgeColor','k',...
                'MarkerFaceColor',CM(i,:),...
                'MarkerSize',10);
end
xlabel('{xgy_1}','FontSize',18)
ylabel('{xgy_2}','FontSize',18)
set(gca,'FontSize',13)
grid
hold off

