function Y_f=QR1_adjusted(tau,Xb)
% This function is based on: 
% "Mitchell, J., Poon, A., & Zhu, D. (2024). Constructing density forecasts from quantile regressions: Multimodality in macrofinancial dynamics. Journal of Applied Econometrics, 39(5), 790–812. https://doi.org/10.1002/jae.3049" 
% and the corresponding replication code. The file has been adjusted for use with Variational Bayes quantile regression in "Schröder, M.. Mixing it up: Inflation at risk", which is implemented in the function VBTVPQR.m in the corresponding
% replication code.
% Adjusted by Maximilian Schröder

[T]=size(Xb,1);
k=length(tau);% quantiles

%% In-Sample density fit

Q_fit=sort(Xb,2);


N=20000;% total sample size 
n=N/(k+1);
Y_f=zeros(T,N);
for j=2:k
    ind=(j-1)*n+1:j*n;
    Y_f(:,ind)=Q_fit(:,j-1)+sparse(1:T,1:T,Q_fit(:,j)-Q_fit(:,j-1))*rand(T,n);
end
sig_l=(Q_fit(:,2)-Q_fit(:,1))./(norminv(tau(2))-norminv(tau(1)));
mu_l=Q_fit(:,1)-sig_l*norminv(tau(1));
Y_f(:,1:n)=mu_l+sparse(1:T,1:T,sig_l)*norminv(tau(1)*rand(T,n));
sig_u=(Q_fit(:,k)-Q_fit(:,k-1))./(norminv(tau(k))-norminv(tau(k-1)));
mu_u=Q_fit(:,k)-sig_u*norminv(tau(k));
Y_f(:,k*n+1:end)=mu_u+sparse(1:T,1:T,sig_u)*norminv(tau(k)+(1-tau(k))*rand(T,n));