function [ beta_lambda ] = get_beta_lambda( param, analysis, excess_returns, factors, c_fac )
% auxiliary function for the two_pass regressions in a_T*g_T=0 setup:
% returns a K x N matrix of the form:
%                                                                                                                                             
% beta_lambda =
% beta^1_1 * lambda_1 ... beta^N_1 * lambda_1
%          .       .                .
%          .            .           .
% beta^1_K * lambda_K ... beta^N_K * lambda_K
%
% input is the two pass regression parameter vector of tje form as in
% functions get_g_T and get_a_T

N=size(excess_returns,2);
K=size(factors,2);

if analysis==2          % two-pass regression
    
    % betas come in a N*K column vector with the first K values to test
    % asset one, the next K to the second test asset and so on
    betas=param(N+1:N*(K+1));
    
    % The N*K vector is reshaped as an KxN matrix: the first column has
    % then the betas for the first asset, and so forth
    % the first row holds the beta values belonging to the first factor,
    % the second row for the second factor and so on: this is the lower
    % right corner of the a_T matrix
    betas_mat=reshape(betas,[K,N])';
    
    % now the lambdas
    lambda=param(N*(K+1)+1:size(param,1));
    
elseif analysis==7      % three-pass regression with mimicking portfolios
    
    % betas come in a N*K column vector with the first K values to test
    % asset one, the next K to the second test asset and so on
    betas=param(N+1:N*(c_fac+1));
    
    % The N*K vector is reshaped as an KxN matrix: the first column has
    % then the betas for the first asset, and so forth
    % the first row holds the beta values belonging to the first factor,
    % the second row for the second factor and so on: this is the lower
    % right corner of the a_T matrix
    betas_mat=reshape(betas,[c_fac,N])';
    
    % now the lambdas
    lambda=param(N*(c_fac+1)+1:N*(c_fac+1)+c_fac);
end

beta_lambda=betas_mat'.*repmat(lambda,[1 N]);

end

