function [Y,Z,neto,neth]=mlpnn(W,X)

%
% Multilayer (Two Layers) Morphological/Rank/Linear Neural Network;
%
% Inputs: W - Cell with the coeficients matrices; 
%             Each cell represent a layer; 
%         X - matrix with the input patterns as column;
%
% Output: y - Outputs of the network; 
%         Z - Outputs of the hidden layer; 
%      neto - Activation of the neurons in the output layer; 
%      neth - Activation of the neurons in the hidden layer; 
%

[N,K]=size(X);
J=size(W{1},1);
L=size(W{2},1);

for k=1:K
  % Hidden Layer...
  clear Ax;
  Ax=W{1}(:,3:N+2)+ones(J,1)*X(:,k)';
  Ax=sort(Ax',1);
  clear ind; ind=round(N-(N-1)./(1+exp(W{1}(:,2))));
  alphah(:,k)=Ax(ind+[0:N:(J-1)*N]');
  betah(:,k)=W{1}(:,N+3:2*N+3)*[X(:,k);1];
  neth(:,k)=W{1}(:,1).*alphah(:,k)+(1-W{1}(:,1)).*betah(:,k);
  Z(:,k)=tanh(neth(:,k));
  % Output Layer...
  clear Az;
  Az=W{2}(:,3:J+2)+ones(L,1)*Z(:,k)';
  Az=sort(Az',1);
  clear ind; ind=round(J-(J-1)./(1+exp(W{2}(:,2))));
  alphao(:,k)=Az(ind+[0:J:(L-1)*J]');
  betao(:,k)=W{2}(:,J+3:2*J+3)*[Z(:,k);1];
  neto(:,k)=W{2}(:,1).*alphao(:,k)+(1-W{2}(:,1)).*betao(:,k);
  Y(:,k)=tanh(neto(:,k));
end
  
  
  
