
function [z] = OPdrawlatent(y,x,beta,delta)

% This function draws the latent variable z for the ordinal probit model
% Output
%--------------------------------------------------------------------------
% z         : Gibbs draw of latent response variable, a column vector
% Input
% y         : observed ordinal values, a column vector
% x         : covariate matrix including a column of ones
% beta      : Gibbs draw of beta, a column vector
% delta     : cut-points, a column vector
%--------------------------------------------------------------------------

J       = size(unique(y),1);
[n,~]   = size(x);
z       = zeros(n,1);

% Transforming the delta to original cut-points
% delta(j) = ln (gamma(j) - gamma(j-1))

expdelta        = exp(delta);
gammaCp         = zeros(size(expdelta,1)+1,1);

for j = 2:J-1
    gammaCp(j)  = sum(expdelta(1:j-1,1));
end
allgammaCp      = [-Inf; gammaCp; Inf];
sd = 1;

for i = 1:n
    xibeta = x(i,:)*beta;
    temp   = y(i);
    a      = allgammaCp(temp);
    b      = allgammaCp(temp+1);
    % z(i,1) = rnddtruncnorm(xibeta,sd,a,b);
    z(i,1) = rndtruncNormal(xibeta, sd^2,a,b);

end
    
end

