function Z=gauss_chol_ex22(mu, C_N)
% C.E. Powell, MATH64082
% Computes one sample of Z \sim N(mu, C_N) using Cholesky factorisation, 
% where mu is a given mean vector of length N, and C_N is a given
% (valid) N x N covariance matrix.
%
% inputs: 
%        mu  - column vector of length N
%        C_N - valid covariance matrix, size N x N
% output:
%        Z - one sample from the required multivariate normal distribution.

xi=randn(size(mu));
R=chol(C_N);
Z=mu+R'*xi;

% For Example 2.2 ONLY: Plotting commands for Visualisation
% Commands below assume D=[0,1] x [0,1], and the 101 x 101 sample points
% x_i in D (mesh vertices) are ordered left to right bottom to top
% - EDIT OTHERWISE!

h=1/100; x=0:h:1; y=0:h:1;
contourf(x,y,reshape(Z,101,101),40); shading flat;
colormap jet; colorbar; xlabel('x'), ylabel('y');
title('Realisation of Z, visualised as a contourf plot')
figure(2); 
mesh(x,y,reshape(Z,101,101)); colormap jet; 
xlabel('x'), ylabel('y'); 
title('Realisation of Z, visualised as a mesh plot')
figure(3); imagesc(C_N); title ('Visualisation of the matrix C_N');