In [ ]:
function varargout = generator(varargin)
% GENERATOR MATLAB code for generator.fig
%      GENERATOR, by itself, creates a new GENERATOR or raises the existing
%      singleton*.
%
%      H = GENERATOR returns the handle to a new GENERATOR or the handle to
%      the existing singleton*.
%
%      GENERATOR('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in GENERATOR.M with the given input arguments.
%
%      GENERATOR('Property','Value',...) creates a new GENERATOR or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before generator_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to generator_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help generator

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @generator_OpeningFcn, ...
                   'gui_OutputFcn',  @generator_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before generator is made visible.
function generator_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to generator (see VARARGIN)

% Choose default command line output for generator
clc;

axes(handles.axes1);
set(handles.axes1,'Xtick',[],'Ytick',[],'Xlim',[0 1000]);
rectangle('Position',[0,0,(round(0))+1,20],'FaceColor','g');
text(480,10,[num2str(0),'%']);



handles.output = hObject;

% Update handles structure
guidata(hObject, handles);


% UIWAIT makes generator wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = generator_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure

varargout{1} = handles.output;



% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu1
contents = get(hObject,'Value');

prefer=handles.prefer;

set(handles.ed11,'String',prefer(contents,1))
set(handles.ed12,'String',prefer(contents,2))
set(handles.ed13,'String',prefer(contents,3))
set(handles.ed14,'String',prefer(contents,4))
set(handles.ed15,'String',prefer(contents,5))
set(handles.ed16,'String',prefer(contents,6))
set(handles.ed17,'String',prefer(contents,7))
set(handles.ed18,'String',prefer(contents,8))

        


% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end




function ed11_Callback(hObject, eventdata, handles)
% hObject    handle to ed11 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.generate,'Enable','off');
set(handles.save,'Enable','on');

% Hints: get(hObject,'String') returns contents of ed11 as text
%        str2double(get(hObject,'String')) returns contents of ed11 as a double


% --- Executes during object creation, after setting all properties.
function ed11_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ed11 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function ed12_Callback(hObject, eventdata, handles)
% hObject    handle to ed12 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.generate,'Enable','off');
set(handles.save,'Enable','on');

% Hints: get(hObject,'String') returns contents of ed12 as text
%        str2double(get(hObject,'String')) returns contents of ed12 as a double


% --- Executes during object creation, after setting all properties.
function ed12_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ed12 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function ed13_Callback(hObject, eventdata, handles)
% hObject    handle to ed13 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.generate,'Enable','off');
set(handles.save,'Enable','on');

% Hints: get(hObject,'String') returns contents of ed13 as text
%        str2double(get(hObject,'String')) returns contents of ed13 as a double


% --- Executes during object creation, after setting all properties.
function ed13_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ed13 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function ed14_Callback(hObject, eventdata, handles)
% hObject    handle to ed14 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.generate,'Enable','off');
set(handles.save,'Enable','on');

% Hints: get(hObject,'String') returns contents of ed14 as text
%        str2double(get(hObject,'String')) returns contents of ed14 as a double


% --- Executes during object creation, after setting all properties.
function ed14_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ed14 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function ed15_Callback(hObject, eventdata, handles)
% hObject    handle to ed15 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.generate,'Enable','off');
set(handles.save,'Enable','on');

% Hints: get(hObject,'String') returns contents of ed15 as text
%        str2double(get(hObject,'String')) returns contents of ed15 as a double


% --- Executes during object creation, after setting all properties.
function ed15_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ed15 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function ed16_Callback(hObject, eventdata, handles)
% hObject    handle to ed16 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.generate,'Enable','off');
set(handles.save,'Enable','on');

% Hints: get(hObject,'String') returns contents of ed16 as text
%        str2double(get(hObject,'String')) returns contents of ed16 as a double


% --- Executes during object creation, after setting all properties.
function ed16_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ed16 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function ed17_Callback(hObject, eventdata, handles)
% hObject    handle to ed17 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.generate,'Enable','off');
set(handles.save,'Enable','on');
% Hints: get(hObject,'String') returns contents of ed17 as text
%        str2double(get(hObject,'String')) returns contents of ed17 as a double


% --- Executes during object creation, after setting all properties.
function ed17_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ed17 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function ed18_Callback(hObject, eventdata, handles)
% hObject    handle to ed18 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.generate,'Enable','off');
set(handles.save,'Enable','on');

% Hints: get(hObject,'String') returns contents of ed18 as text
%        str2double(get(hObject,'String')) returns contents of ed18 as a double


% --- Executes during object creation, after setting all properties.
function ed18_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ed18 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in import.
function import_Callback(hObject, eventdata, handles)
% hObject    handle to import (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[file,filepath] = uigetfile({'*.xlsx'},'Select the Excel file');
copyfile(fullfile(filepath, file),'Template.xlsx');
filename = 'Template.xlsx';

[prefer,subject]=xlsread(filename,'C3:K100');
[dataprefer,datasubject]=xlsread(filename,'B3:K100');
%xlswrite('data.xlsx',dataprefer,['D3:K' (num2str(length(dataprefer)+2))]);
%xlswrite('data.xlsx',datasubject,['B3:C' (num2str(length(datasubject)+2))]);
xlswrite('data.xlsx',dataprefer,'D3:K100');
xlswrite('data.xlsx',datasubject,'B3:C100');

[~,type]=xlsread(filename,'B3:B100');
%prefer = xlsread(filename,'D3:K62');


set(handles.popupmenu1,'String',subject);

contents=get(handles.popupmenu1,'Value');

set(handles.ed11,'String',prefer(contents,1));
set(handles.ed12,'String',prefer(contents,2));
set(handles.ed13,'String',prefer(contents,3));
set(handles.ed14,'String',prefer(contents,4));
set(handles.ed15,'String',prefer(contents,5));
set(handles.ed16,'String',prefer(contents,6));
set(handles.ed17,'String',prefer(contents,7));
set(handles.ed18,'String',prefer(contents,8));

handles.prefer=prefer;
handles.filename=filename;
handles.subject=subject;
handles.type=type;

set(handles.popupmenu1,'Enable','on');
set(handles.generate,'Enable','on');

guidata(hObject,handles)





% --- Executes on button press in export.
function export_Callback(hObject, eventdata, handles)
% hObject    handle to export (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[outfile,outpath] = uiputfile({'*.xlsx'},'Select the Destination Folder');
copyfile('Template.xlsx',fullfile(outpath, outfile),'f');



% --- Executes on button press in save.
function save_Callback(hObject, eventdata, handles)
% hObject    handle to save (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

contents=get(handles.popupmenu1,'Value');

prefer=handles.prefer;
filename=handles.filename;
pre1=(str2num(get(handles.ed11,'String')));
pre2=(str2num(get(handles.ed12,'String')));
pre3=(str2num(get(handles.ed13,'String')));
pre4=(str2num(get(handles.ed14,'String')));
pre5=(str2num(get(handles.ed15,'String')));
pre6=(str2num(get(handles.ed16,'String')));
pre7=(str2num(get(handles.ed17,'String')));
pre8=(str2num(get(handles.ed18,'String')));

if ((pre1+pre2+pre3+pre4+pre5+pre6+pre7+pre8)==36)

    prefer(contents,1)=pre1;
    prefer(contents,2)=pre2;
    prefer(contents,3)=pre3;
    prefer(contents,4)=pre4;
    prefer(contents,5)=pre5;
    prefer(contents,6)=pre6;
    prefer(contents,7)=pre7;
    prefer(contents,8)=pre8;

    %xlswrite(filename,prefer,['D3:K' (num2str(length(prefer)+2))]);
    xlswrite(filename,prefer,'D3:K100');
    set(handles.generate,'Enable','on');
    set(handles.save,'Enable','off');
    
else
     msgbox('Invalid values! Please try again.','Invalid values','error');
end
handles.prefer=prefer;

guidata(hObject,handles)





% --- Executes on button press in generate.
function generate_Callback(hObject, eventdata, handles)
% hObject    handle to generate (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handlguies and user data (see GUIDATA)
%CostFunction=@(x) MyCost(x);
set(handles.generate,'Enable','off');

noS=length(handles.subject);
type=handles.type;
set(handles.axes1,'Xtick',[],'Ytick',[],'Xlim',[0 1000]);
Max_iteration=(str2num(get(handles.edit10,'String'))); % Maximum number of iterations
noP=30; % Number of particles
noV=noS*3;

w=2;              %Inirtia weight
wMax=0.9;         %Max inirtia weight
wMin=0.4;         %Min inirtia weight
c1=2;
c2=2;
Vmax=4;

FC1=10;
FD1=10;

Prefer=handles.prefer-1;




Velocity=zeros(noP,noV);%Velocity vector
Position=zeros(noP,noV);%Position vector

%////////Cognitive component///////// 
pBestScore=zeros(noP);
pBest=zeros(noP,noV);
%////////////////////////////////////

%////////Social component///////////
gBestScore=inf;
gBest=zeros(1,noV);
%///////////////////////////////////

ConvergenceCurve=zeros(1,Max_iteration); %Convergence vector

%Initialization
for i=1:size(Position,1) % For each particle
    while (FC1 > 3) || (FC2 > 6)|| (FC3 > 3)|| (FC4 > 3) 
        for j=1:size(Position,2) % For each variable
            if rand<=0.5
                Position(i,j)=0;
            else
                Position(i,j)=1;
            end
        end
    A = reshape((Position(i,:)),[3,noS])';
        Output=binaryVectorToDecimal(A);
    C1=Output(1:sum(count(type,"A")));
    C2=Output((sum(count(type,"A"))+1):sum(count(type,["A","B"])));
    C3=Output((sum(count(type,["A","B"]))+1):sum(count(type,["A","B","C"])));
    C4=Output((sum(count(type,["A","B","C"]))+1):noS);
    [MC1,FC1] = mode(C1);
    [MC2,FC2] = mode(C2);
    [MC3,FC3] = mode(C3);
    [MC4,FC4] = mode(C4);
    end
  
    FC1=10;
end
for i=1:noP
    pBestScore(i)=inf;
end

for l=1:Max_iteration

    %Calculate cost for each particle
    for i=1:size(Position,1) 
       
        A = reshape((Position(i,:)),[3,noS])';
        Output=binaryVectorToDecimal(A);
        for ii= 1:size(Prefer,1)
            j(ii,:) = find(Prefer(ii,:)==Output(ii,1));
        end
        x=j-1;
        fitness=sum(x);
       %fitness=CostFunction(Output);
        %fitness=CostFunction(Position(i,:))
        
        
        if(pBestScore(i)>fitness)
            pBestScore(i)=fitness;
            pBest(i,:)=Position(i,:);
        end
        if(gBestScore>fitness)
            gBestScore=fitness;
            gBest=Position(i,:);
        end
    end

    %update the W of PSO
    w=wMax-l*((wMax-wMin)/Max_iteration);
    %Update the Velocity and Position of particles
    for i=1:size(Position,1)
        while (FD1 > 3) || (FD2 > 6)|| (FD3 > 3)|| (FD4 > 3) 
        for j=1:size(Position,2) 
            %Equation (1)
            Velocity(i,j)=w*Velocity(i,j)+c1*rand()*(pBest(i,j)-Position(i,j))+c2*rand()*(gBest(j)-Position(i,j));
            
            if(Velocity(i,j)>Vmax)
                Velocity(i,j)=Vmax;
            end
            if(Velocity(i,j)<-Vmax)
                Velocity(i,j)=-Vmax;
            end  
            
            
                s=1/(1+exp(-Velocity(i,j)));   %S2 transfer function              
         
                if rand<s % Equation (4) and (8)
                    Position(i,j)=1;
                else
                    Position(i,j)=0;
                end
          
            
           
        end
        AA = reshape((Position(i,:)),[3,noS])';
        Output=binaryVectorToDecimal(AA);
    D1=Output(1:sum(count(type,"A")));
    D2=Output((sum(count(type,"A"))+1):sum(count(type,["A","B"])));
    D3=Output((sum(count(type,["A","B"]))+1):sum(count(type,["A","B","C"])));
    D4=Output((sum(count(type,["A","B","C"]))+1):noS);
    [MD1,FD1] = mode(D1);
    [MD2,FD2] = mode(D2);
    [MD3,FD3] = mode(D3);
    [MD4,FD4] = mode(D4);
        end
    FD1=10;
    end
    ConvergenceCurve(l)=gBestScore;
        axes(handles.axes1);
    cla(handles.axes1);
	rectangle('Position',[0,0,(round(1000*l/Max_iteration))+1,20],'FaceColor','g'); 
    text(480,10,[num2str(round(100*l/Max_iteration)),'%']);
 
end
AAA = reshape(gBest,[3,noS])';
Final=binaryVectorToDecimal(AAA)
gBestScore
E1=Output(1:sum(count(type,"A")));
    E2=Output((sum(count(type,"A"))+1):sum(count(type,["A","B"])));
    E3=Output((sum(count(type,["A","B"]))+1):sum(count(type,["A","B","C"])));
    E4=Output((sum(count(type,["A","B","C"]))+1):noS);
[ME1,FE1] = mode(E1);
[ME2,FE2] = mode(E2);
[ME3,FE3] = mode(E3);
[ME4,FE4] = mode(E4);

figure(2);
plot(ConvergenceCurve)
%xlswrite('data.xlsx',Final,2,['B2:B' (num2str(length(Final)+1))]);
xlswrite('data.xlsx',Final,2,'B2:B100');
run('table2.m')
set(handles.generate,'Enable','on');
guidata(hObject,handles)


% --- Executes on button press in cancel.
function cancel_Callback(hObject, eventdata, handles)
% hObject    handle to cancel (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

delete(handles.figure1)



function edit10_Callback(hObject, eventdata, handles)
% hObject    handle to edit10 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit10 as text
%        str2double(get(hObject,'String')) returns contents of edit10 as a double


% --- Executes during object creation, after setting all properties.
function edit10_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit10 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end