u_h=bias+amp;
u_l=bias-amp;

u_max=max(u);
%u_max=min(u_max.*1.5.^sign(u_max),u_h);
u_max=u_h;
u_min=min(u);
%u_min=max(u_min./1.5.^sign(u_min),u_l);
u_min=u_l;
%um=mean(u);
um=(u_max+u_min)/2;
r=max(u_max-um,um-u_min);
un=(u-meshgrid(um,1:size(u,1)))./meshgrid(r,1:size(u,1));

y_max=max(y);
y_max=y_max.*1.1.^sign(y_max);
y_min=min(y);
y_min=y_min./1.1.^sign(y_min);
%ym=mean(y);
ym=(y_max+y_min)/2;
s=max(y_max-ym,ym-y_min);
yn=(y-meshgrid(ym,1:size(y,1)))./meshgrid(s,1:size(y,1));

Q=size(u,1);
ui1=zeros(Q,4);
ui1(2:Q,1:2)=un(1:(Q-1),1:2);
ui1(3:Q,3:4)=un(1:(Q-2),1:2);
ui2=zeros(Q,4);
ui2(2:Q,1:2)=un(1:(Q-1),3:4);
ui2(3:Q,3:4)=un(1:(Q-2),3:4);
ui=[ui1'; ui2'];

%ui1=un(:,1:2);
%ui2=un(:,3:4);
%ui=[con2seq(ui1'); con2seq(ui2')];

% Network Architecture
NL=3;
net = network(2,NL);
net.biasConnect = ones(NL,1);
net.inputConnect = [1 0;0 1;0 0];
net.layerConnect = [0 0 0;1 0 0;1 1 0];
net.outputConnect = [0 0 1];
net.targetConnect = [0 0 1];

% Delays
%net.inputWeights{1,1}.delays=[1 2 3];
%net.inputWeights{2,2}.delays=[1 2 3];

% Simulation
net.inputs{1}.range = ones(4,1)*[-1 1];
net.inputs{2}.range = ones(4,1)*[-1 1];
net.layers{1}.size = 5;
net.layers{1}.transferFcn = 'tansig';
net.layers{2}.size = 5;
net.layers{2}.transferFcn = 'tansig';
net.layers{3}.size = 2;
net.layers{3}.transferFcn = 'purelin';

% Performance
net.performFcn = 'mse';

% Adaption
net.adaptfcn = 'adaptwb';
blf = 'learngdm';
net.inputWeights{1,1}.learnFcn = blf;
net.inputWeights{2,2}.learnFcn = blf;
for i=1:NL
  net.biases{i}.learnFcn = blf;
  net.layerWeights{i,:}.learnFcn = blf;
end

% Training
net.trainfcn = 'trainbfg';

% Initialization
net.initFcn = 'initlay';
for i=1:NL
  net.layers{i}.initFcn = 'initnw';
end
net = init(net);
net.trainParam.goal=1e-4;

% end Network

net=train(net,ui,yn');
%yi=con2seq(yn');
%net=train(net,ui,yi);

save nfir um r ym s net

ys=sim(net,ui)';
%ys=seq2con(sim(net,ui));
%ys=ys{1}';
plot(t,yn,'.',t,ys);
