function [grad] = mixmlpgrad_exp(net, x, t, post, varargin)
%mixmlpgrad_exp  Evaluate gradient of error function for one expert network in a gated experts model trained by EM.
%
%       GRAD = MIXMLPGRAD_EXP(NET, X, T, POST) takes an expert network data
%       structure NET (which is a MLP) together with a matrix X of input 
%       vectors and a matrix T of target vectors, the posterior
%       probabilities POST , and evaluates the gradient GRAD of the error function
%       with respect to the network weights. The error function is the
%       expert contribtion to the EM error fucntion.
%
%       GRAD = MIXMLPGRAD_EXP(NET, X, T, POST, SIGMA) if the 
%       conditional  density for the experts is an isotropic Gaussian (with 
%       one variance parameter for each expert), SIGMA contains these
%       variances. 
%
%       See also
%       mixgrad_em, mixmlp, mixmlpem, mixopt, mlpfwd
%
%       Copyright: Perry Moerland
 


% Check arguments for consistency
errstring = consist(net, 'mlp', x, t);
if ~isempty(errstring)
  error(errstring);
end

[y,z] = mlpfwd(net, x);

% Compute gradients at expert network outputs: put the answer in deltas

delout = y - t;
if size(varargin)
   s = varargin{1};
   deltas_exp = diag(sparse(post))*delout/s; 
else
   deltas_exp = diag(sparse(post))*delout;
end; 
 
% calculate gradients
grad = mlpbkp(net,x,z,deltas_exp);
