function [result, msev]=neural_fitting(in, out, test)
% Solve an Input-Output Fitting problem with a Neural Network
% Script generated by NFTOOL
% Created Sun Sep 14 13:58:05 EDT 2014
%
% This script assumes these variables are defined:
%
%   in - input data.
%   out - target data.
train_num=30;

for i=1:train_num
    inputs = in';
    targets = out';
    
    % Create a Fitting Network
    hiddenLayerSize = 4;
    net = fitnet(hiddenLayerSize);
    
    % Choose Input and Output Pre/Post-Processing Functions
    % For a list of all processing functions type: help nnprocess
    net.inputs{1}.processFcns = {'removeconstantrows','mapminmax'};
    net.outputs{2}.processFcns = {'removeconstantrows','mapminmax'};
    
    
    % Setup Division of Data for Training, Validation, Testing
    % For a list of all data division functions type: help nndivide
    net.divideFcn = 'dividerand';  % Divide data randomly
    net.divideMode = 'sample';  % Divide up every sample
    net.divideParam.trainRatio = 80/100;
    net.divideParam.valRatio =20/100;
    net.divideParam.testRatio = 0/100;
    
    % For help on training function 'trainlm' type: help trainlm
    % For a list of all training functions type: help nntrain
    net.trainFcn = 'trainlm';  % Levenberg-Marquardt
    
    % Choose a Performance Function
    % For a list of all performance functions type: help nnperformance
    net.performFcn = 'mse';  % Mean squared error
    
    % Choose Plot Functions
    % For a list of all plot functions type: help nnplot
    net.plotFcns = {'plotperform','plottrainstate','ploterrhist', ...
        'plotregression', 'plotfit'};
    
    
    % Train the Network
    [net,tr] = train(net,inputs,targets);
    
    % Test the Network
    outputs = net(inputs);
    errors = gsubtract(targets,outputs);
    performance = perform(net,targets,outputs);
    
    % Recalculate Training, Validation and Test Performance
    trainTargets = targets .* tr.trainMask{1};
    valTargets = targets  .* tr.valMask{1};
    testTargets = targets  .* tr.testMask{1};
    trainPerformance = perform(net,trainTargets,outputs);
    ValPerformance(i) = perform(net,valTargets,outputs);
    testPerformance = perform(net,testTargets,outputs);
    
    train_index=isnan(valTargets);
    validex=train_index<1;
   
    
    val_gtruth=valTargets(validex);
    val_pre=outputs(validex);
     correlation(i)=corr(val_gtruth',val_pre','type','spear');
    
    valp=ValPerformance;
    figure(1)
    plot(1:i,valp)
    hold on 
    plot([1 i],[min(valp),min(valp)],'r-')
    hold off

%     subplot(2,1,2)
%     plot(1:i,1-correlation,'b-')
    
    
    t_result{i}=net(test');

end
[msev,index]=min(valp);
result=t_result{index};
% View the Network
%view(net)

% Plots
% Uncomment these lines to enable various plots.
%figure, plotperform(tr)
%figure, plottrainstate(tr)
%figure, plotfit(net,inputs,targets)
%figure, plotregression(targets,outputs)
%figure, ploterrhist(errors)
end
