function [W_i] = w_matrix(id1,id2,year,w)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This function creates matrix of weights for predefined groups
%
%   id1: the firm (or firm destination) id
%   id2: the group id (e.g., sector)
%
% One component is cerated:
%   1. W_i is the matrix of weights
%
% The final matrices will be (T*G), where G = number of groups, and T is
% the number of time periods.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% From before and needed for 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% 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(id1);
[h1,h2,jj]=unique(year);

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

% Get weights aligned correctly

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

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NEW: for group analysis and looping
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Create a balanced matrix for group id's

G = zeros(N,T);
G(sub2ind([N T],ii,jj)) = id2;

g_min = min(id2);
g_max = max(id2);

W_i = zeros(T,g_max);

for i = g_min:g_max
    D1 = (G==i);            % Within group dummy
    W1 = D1.*W;
    w=(sum(W1)./sum(D1))';
    W_i(:,i) = w;
    clear D1 W1 w;
end


