function [grad] = mixgrad_exp(net, x, t, post, varargin)
%mixgrad_exp   Evaluate gradient of error function for one expert network in a mixture of experts model trained by EM.
%
%	GRAD = MIXGRAD_EXP(NET, X, T, POST) takes an expert network data
%	structure NET (which is a GLM) 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 = MIXGRAD_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, mix, mixem, mixopt, glmfwd
%
%       Copyright: Perry Moerland

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

y = glmfwd(net, x);

% Compute deltas at expert network outputs

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
gw1  = x'*deltas_exp;
gb1  = sum(deltas_exp,1);
grad = [gw1(:)',gb1];
