function f = mlp_cost(v,k,n1,x,y)
%
%  Calculates the value of the cost functional J (see (4.15) in 
%  the lecture notes), which measures the error of the MLP-network.
%
%  Input
%    v         entries of the weight matrices W_1 and W_2 
%              as one long vector. Matrix W_1 comes first and then W_2.
%    k         vector of parameters for sigmoid
%    n1        dimension of the hidden layer
%    x         input-vectors of the training data; 
%              one column is one vector
%    y         output-vectors of the training data
%
%  Output
%    f         value of the cost functional
%

[n0,NX] = size(x);
[n2,NY] = size(y);

if (NX~=NY)
   error('training inputs and outputs incompatible.');
end 

N = NX;
w1_dim = n1*(n0+1);
w2_dim = n2*(n1+1);
if (length(v)~=w1_dim+w2_dim)
   error('training data and weight matrices incompatible.');
end

%
% Reshape the weight matrices from the vector v
%
w1 = reshape(v(1:w1_dim),n1,n0+1);
w2 = reshape(v(w1_dim+1:w1_dim+w2_dim),n2,n1+1);

cof = 1/(2*N);
f = 0;
for i=1:N
   o = mlp_out(x(:,i),k,w1,w2);
   e = o - y(:,i);
   f = f + cof*e'*e;
end
