function [VAR var sd] = var_growth(id,year,X,w)

% Create a balanced matrix of growth rates, where 0's fill in missing,
% which is ok b/c will sum over zeros and not count when taking averages

[h1,h2,ii]=unique(id);
[h1,h2,jj]=unique(year);

N=max(ii);
T=max(jj);

bigX=zeros(N,T);
bigX(sub2ind([N T],ii,jj))= X;

bigO=zeros(N,T);
bigO(sub2ind([N T],ii,jj))=1;
counts = sum(bigO,2);
mX =  sum(bigX,2)./sum(bigO,2);
demeanX = (bigX-repmat(mX,1,T)).*bigO;

% Demeaned matrix which is N,T and create a (T_n - 1) to divide by 

Y = reshape(demeanX,N,T);

t = counts - ones(size(counts,1),1);
tt = repmat(t,1,T);
TT = reshape(tt,N,T);

Y = Y./sqrt(TT);

% Get weights aligned correctly

W = zeros(N,T);
W(sub2ind([N T],ii,jj))= w;

% Create VAR = (W'Y)(Y'W)

y = W'*Y;
VAR = y*y';

var = diag(VAR);
sd = sqrt(var);


