% Example 6.5

% Use data generated from previous example.
% This will be the data matrix X, that has
% to be saved to the workspace from the
% genmix GUI.

% Need to get initial values of the 
% parameters.
piesin = [0.5, 0.5];
% The musin argument is a matrix of means,
% where each column is a p-D mean.
musin = [ones(2,1), -1*ones(2,1)];
% The varin argument is a 3-D array, where
% each page corresponds to one of the
% covariance matrices.
varin(:,:,1) = 2*eye(2);
varin(:,:,2) = eye(2);

% Now call the function.
[pie,mu,vars]=mbcfinmix(X,musin,varin,piesin,8);

% Results:
% pie =
%     0.7188    0.2812
% mu =
%     2.1528   -1.7680
%     2.1680   -2.2400
% vars(:,:,1) =
%     2.9582    1.1405
%     1.1405    0.7920
% vars(:,:,2) =
%     1.9860   -1.3329
%    -1.3329    1.4193

% Now create a surface for the density.
% Get a domain over which to evaluate
% the function.
x1 = linspace(-7,7,50);
x2 = linspace(-7,5,50);
[X1,X2] = meshgrid(x1,x2);
% The X1 and X2 are matrices. We need to
% put them as columns into another one.
dom = [X1(:), X2(:)];
% Now get the multivariate normal pdf at
% the domain values - for each component.
% The following function is from the
% Statistics Toolbox.
Y1 = mvnpdf(dom,mu(:,1)',vars(:,:,1));
Y2 = mvnpdf(dom,mu(:,2)',vars(:,:,2));
% Weight them and add to get the final function.
y = pie(1)*Y1 + pie(2)*Y2;
% Need to reshape the Y vector to get a matrix
% for plotting as a surface plot.
[m,n] = size(X1);
Y = reshape(y,m,n);
surf(X1,X2,Y)
axis([-7 7 -7 5 0 0.12])
xlabel('X_1'),ylabel('X_2')
zlabel('PDF')






