% Solve a Pattern Recognition Problem with a Neural Network
% Script generated by Neural Pattern Recognition app
% Created 27-Apr-2025 16:30:28
%
% This script assumes these variables are defined:
%
%   Xd - input data.
%   Yd - target data.

rng(1);

temp=load('training_data.mat');
Xd=temp.temp.X;
Yd=temp.temp.Y;

x = Xd;
t = Yd;

% Choose a Training Function
% For a list of all training functions type: help nntrain
% 'trainlm' is usually fastest.
% 'trainbr' takes longer but may be better for challenging problems.
% 'trainscg' uses less memory. Suitable in low memory situations.
trainFcn = 'trainscg';  % Scaled conjugate gradient backpropagation.

% Create a Pattern Recognition Network
hiddenLayerSize = 10;
net = patternnet(hiddenLayerSize, trainFcn);

% Setup Division of Data for Training, Validation, Testing
net.divideParam.trainRatio = 70/100;
net.divideParam.valRatio = 15/100;
net.divideParam.testRatio = 15/100;

% Train the Network
[net,tr] = train(net,x,t);

% Test the Network
y = net(x);
e = gsubtract(t,y);
performance = perform(net,t,y);
tind = vec2ind(t);
yind = vec2ind(y);
percentErrors = sum(tind ~= yind)/numel(tind);

% View the Network
view(net)

% Plots
% Uncomment these lines to enable various plots.
%figure, plotperform(tr)
%figure, plottrainstate(tr)
%figure, ploterrhist(e)
% figure, plotconfusion(t,y)
%figure, plotroc(t,y)

xx=0:0.05:1;
yy=0:0.05:1;

X=zeros(length(xx),length(yy));
Y=X;
Fx=X;
Fy=X;

for i=1:length(xx)
    for j=1:length(yy)
        x1_val=xx(i);
        x2_val=yy(j);

        X(i,j)=x1_val;
        Y(i,j)=x2_val;

        F_temp=net([x1_val,x2_val]');
        Fx(i,j)=F_temp;
    end
end

contour(X,Y,Fx,[0.5 0.5 ],'LineWidth',3,'color','black','linestyle',':')
% hold on
% contour(X,Y,Fx,[0.7 0.7 ],'LineWidth',1.5,'color','black','linestyle',':')
hold on

N=length(Yd);
for i=1:N
        x_val=Xd(1,i);
        y_val=Xd(2,i);
        z_val=x_val+sqrt(-1)*y_val;

        if(Yd(i)>=0.95)
            plot(z_val,'o','color','red')
            hold on
        else
            plot(z_val,'x','color','blue')
            hold on
        end
 end


xlabel('x_1')
ylabel('x_2')

set(gca,'fontsize',16)
grid on
axis equal
set(gca,'xtick',0:0.2:1)
set(gca,'ytick',0:0.2:1)
hold off

drawnow

