function [grad,res]=gradientnn(M,x,t,ww,layer_size);
% M   - input- # data examples
%(x,t)- input- Training data pairs
%ww- filter for all layers
% t   - input- # observed data

layer_num=numel(layer_size); %layer number include the input and output

aa{1}=x;

% Do forward propagation
for iter =1:layer_num-1 %%%----- N (in book) ------%%%
    zz{iter}=ww{iter}*aa{iter};
    aa{iter+1}=1./(1+exp(-zz{iter}));
end
residual=aa{layer_num}-t;       
res=sqrt(residual*residual')/M;  % Residual

in=residual;
%size(in)
% Implement backpropagation
for iter=layer_num-1:-1:1
      g=1./(1+exp(-zz{iter}));
      dg=g.*(1-g);
      in=dg .* in;
      %size(in),size(aa{iter}')
      grad{iter}=in*aa{iter}';
      in=ww{iter}'*in;
end
