function varargout = FUN_PLOTTER(varargin)
% FUN_PLOTTER MATLAB code for FUN_PLOTTER.fig
%      FUN_PLOTTER, by itself, creates a new FUN_PLOTTER or raises the existing
%      singleton*.
%
%      H = FUN_PLOTTER returns the handle to a new FUN_PLOTTER or the handle to
%      the existing singleton*.
%
%      FUN_PLOTTER('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in FUN_PLOTTER.M with the given input arguments.
%
%      FUN_PLOTTER('Property','Value',...) creates a new FUN_PLOTTER or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before FUN_PLOTTER_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to FUN_PLOTTER_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 FUN_PLOTTER

% Last Modified by GUIDE v2.5 13-Feb-2013 04:22:47

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @FUN_PLOTTER_OpeningFcn, ...
                   'gui_OutputFcn',  @FUN_PLOTTER_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 FUN_PLOTTER is made visible.
function FUN_PLOTTER_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 FUN_PLOTTER (see VARARGIN)

% Choose default command line output for FUN_PLOTTER
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = FUN_PLOTTER_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)
clc
warning off
% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global z thta
cla(handles.axes1)
reset(handles.axes1)
set(handles.axes1,'box','on')
set(handles.axes1,'xtick',[])
set(handles.axes1,'ytick',[])
z = 'sin(x)';
v = get(handles.checkbox2,'value');
if v == 1
    thta = 0:3*360;
    axes(handles.axes1)
    plot(thta,sind(thta),'linewidth',3)
    set(handles.text1,'string','SINE PLOT FROM 0 TO 6*PI')
    grid on
else
    msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')
    set(handles.text1,'string','')
    cla(handles.axes1)
    reset(handles.axes1)
    set(handles.axes1,'box','on')
    set(handles.axes1,'xtick',[])
    set(handles.axes1,'ytick',[])
    return
end

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global z thta
cla(handles.axes1)
reset(handles.axes1)
set(handles.axes1,'box','on')
set(handles.axes1,'xtick',[])
set(handles.axes1,'ytick',[])
z = 'cos(x)';
v = get(handles.checkbox2,'value');
if v == 1
    thta = 0:3*360;
    axes(handles.axes1)
    plot(thta,cosd(thta),'linewidth',3)
    set(handles.text1,'string','COSINE PLOT FROM 0 TO 6*PI')
    grid on
else
    msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')
    set(handles.text1,'string','')
    cla(handles.axes1)
    reset(handles.axes1)
    set(handles.axes1,'box','on')
    set(handles.axes1,'xtick',[])
    set(handles.axes1,'ytick',[])
    return
end

% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global z thta
cla(handles.axes1)
reset(handles.axes1)
set(handles.axes1,'box','on')
set(handles.axes1,'xtick',[])
set(handles.axes1,'ytick',[])
z = 'tan(x)';
v = get(handles.checkbox2,'value');
if v == 1
    thta = 0:3*360;
    axes(handles.axes1)
    plot(thta,tand(thta),'linewidth',3)
    set(handles.text1,'string','TANGENT PLOT FROM 0 TO 6*PI')
    grid on
else
    msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')
    set(handles.text1,'string','')
    cla(handles.axes1)
    reset(handles.axes1)
    set(handles.axes1,'box','on')
    set(handles.axes1,'xtick',[])
    set(handles.axes1,'ytick',[])
    return
end

% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global z thta
cla(handles.axes1)
reset(handles.axes1)
set(handles.axes1,'box','on')
set(handles.axes1,'xtick',[])
set(handles.axes1,'ytick',[])
z = 'cot(x)';
v = get(handles.checkbox2,'value');
if v == 1
    thta = 0:3*360;
    axes(handles.axes1)
    plot(thta,cotd(thta),'linewidth',3)
    set(handles.text1,'string','COTANGENT PLOT FROM 0 TO 6*PI')
    grid on
else
    msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')
    set(handles.text1,'string','')
    cla(handles.axes1)
    reset(handles.axes1)
    set(handles.axes1,'box','on')
    set(handles.axes1,'xtick',[])
    set(handles.axes1,'ytick',[])
    return
end

% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global z thta
cla(handles.axes1)
reset(handles.axes1)
set(handles.axes1,'box','on')
set(handles.axes1,'xtick',[])
set(handles.axes1,'ytick',[])
z = 'sec(x)';
v = get(handles.checkbox2,'value');
if v == 1
    thta = 0:3*360;
    axes(handles.axes1)
    plot(thta,secd(thta),'linewidth',3)
    set(handles.text1,'string','SECANT PLOT FROM 0 TO 6*PI')
    grid on
else
    msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')
    set(handles.text1,'string','')
    cla(handles.axes1)
    reset(handles.axes1)
    set(handles.axes1,'box','on')
    set(handles.axes1,'xtick',[])
    set(handles.axes1,'ytick',[])
    return
end

% --- Executes on button press in pushbutton6.
function pushbutton6_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global z thta
cla(handles.axes1)
reset(handles.axes1)
set(handles.axes1,'box','on')
set(handles.axes1,'xtick',[])
set(handles.axes1,'ytick',[])
z = 'csc(x)';
v = get(handles.checkbox2,'value');
if v == 1
    thta = 0:3*360;
    axes(handles.axes1)
    plot(thta,cscd(thta),'linewidth',3)
    set(handles.text1,'string','COSECANT PLOT FROM 0 TO 6*PI')
    grid on
else
    msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')
    set(handles.text1,'string','')
    cla(handles.axes1)
    reset(handles.axes1)
    set(handles.axes1,'box','on')
    set(handles.axes1,'xtick',[])
    set(handles.axes1,'ytick',[])
    return
end

% --- Executes on button press in pushbutton7.
function pushbutton7_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global z x
cla(handles.axes1)
reset(handles.axes1)
set(handles.axes1,'box','on')
set(handles.axes1,'xtick',[])
set(handles.axes1,'ytick',[])
z = 'log(t)';
v = get(handles.checkbox2,'value');
if v == 1
    x = 0:0.25:10;
    axes(handles.axes1)
    plot(x,log(x),'linewidth',3)
    set(handles.text1,'string','LOGRITHMIC PLOT FROM 0 TO 10')
    grid on
else
    msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')
    set(handles.text1,'string','')
    cla(handles.axes1)
    reset(handles.axes1)
    set(handles.axes1,'box','on')
    set(handles.axes1,'xtick',[])
    set(handles.axes1,'ytick',[])
    return
end

% --- Executes on button press in pushbutton8.
function pushbutton8_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global z x
cla(handles.axes1)
reset(handles.axes1)
set(handles.axes1,'box','on')
set(handles.axes1,'xtick',[])
set(handles.axes1,'ytick',[])
z = 'exp(t)';
v = get(handles.checkbox2,'value');
if v == 1
    x = 0:0.25:10;
    axes(handles.axes1)
    plot(x,exp(x),'linewidth',3)
    set(handles.text1,'string','EXPONENTIAL PLOT FROM 0 TO 10')
    grid on
else
    msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')
    set(handles.text1,'string','')
    cla(handles.axes1)
    reset(handles.axes1)
    set(handles.axes1,'box','on')
    set(handles.axes1,'xtick',[])
    set(handles.axes1,'ytick',[])
    return
end

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

% Hint: get(hObject,'Value') returns toggle state of checkbox2
set(handles.checkbox3,'value',0)
set(handles.edit1,'enable','inactive')
set(handles.edit2,'enable','inactive')
% --- Executes on button press in checkbox3.
function checkbox3_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox3
set(handles.checkbox2,'value',0)
set(handles.edit1,'enable','on')
set(handles.edit2,'enable','on')

function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (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 edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double

% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (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 edit2_Callback(hObject, eventdata, handles)
% hObject    handle to edit2 (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 edit2 as text
%        str2double(get(hObject,'String')) returns contents of edit2 as a double

% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit2 (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 edit3_Callback(hObject, eventdata, handles)
% hObject    handle to edit3 (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 edit3 as text
%        str2double(get(hObject,'String')) returns contents of edit3 as a double

% --- Executes during object creation, after setting all properties.
function edit3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit3 (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 pushbutton10.
function pushbutton10_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton10 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global z p1
v = get(handles.checkbox2,'value');
if v == 1
    msgbox('CAN NOT WORK ON DEFAULT RANGE','WARNING','warn','modal')
    return
end
v1 = get(handles.checkbox3,'value');
if v1 == 0
    msgbox('FIRST SET RANGE','WARNING','warn','modal')
    return
end
a = str2double(get(handles.edit1,'string'));
b = str2double(get(handles.edit2,'string'));
if a > b
    msgbox('MIN IS GR8ER THAN MAX','WARNING','warn','modal')
    set(handles.edit1,'string','')
    set(handles.edit2,'string','')
    return
end
fx2 = get(handles.edit3,'string');
z = fx2;
if isempty(fx2) || isempty(a) || isempty(b)
    msgbox('EITHER MAX OR MIN OR FUNCTION FIELD IS EMPTY OR INVALID','WARNING...','modal')
    set(handles.edit1,'string','')
    set(handles.edit2,'string','')
    set(handles.edit3,'string','')
    return
end
fx3 = inline(fx2);
p1 = a:0.25:b;
p2 = p1;
for l = 1:length(p2)
    mag(l) = fx3(p2(l));
end
axes(handles.axes1)
plot(p2,mag,'linewidth',3)
grid on
set(handles.text1,'string',strcat('PLOT OF ',fx2,' FROM RANGE ',num2str(a),' TO ',num2str(b)))

% --- Executes on button press in pushbutton11.
function pushbutton11_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton11 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global z thta x p1
d = z;
k = z;
switch k
    case 'sin(x)'
        fx = sym(k);
        n = str2double(inputdlg('INPUT ORDER OF DIFFRENTIATION','DY/DX'));
        if isnan(n)
            return
        end
        fx1 = diff(fx,n);
        for l = 1:length(thta)
            mag(l) = subs(fx1,deg2rad(thta(l)));
        end
        axes(handles.axes1)
        hold on
        plot(thta,mag,'r','linewidth',3)
        grid on
        %legend('sin\theta','d(sin\theta)/dx')
        set(handles.text1,'string','DIFFRENTIATION OF SIN(X) AND SIN(X)')
    case 'cos(x)'
        fx = sym(k);
        n = str2double(inputdlg('INPUT ORDER OF DIFFRENTIATION','DY/DX'));
        if isnan(n)
            return
        end
        fx1 = diff(fx,n);
        for l = 1:length(thta)
            mag(l) = subs(fx1,deg2rad(thta(l)));
        end
        axes(handles.axes1)
        hold on
        plot(thta,mag,'r','linewidth',3)
        grid on
        %legend('cos\theta','d(cos\theta)/dx')
        set(handles.text1,'string','DIFFRENTIATION OF COS(X) AND COS(X)')
    case 'tan(x)'
        fx = sym(k);
        fx1 = diff(fx);
        for l = 1:length(thta)
            mag(l) = subs(fx1,deg2rad(thta(l)));
        end
        axes(handles.axes1)
        hold on
        plot(thta,mag,'r','linewidth',3)
        grid on
        %legend('tan\theta','d(tan\theta)/dx')
        set(handles.text1,'string','DIFFRENTIATION OF TAN(X) AND TAN(X)')
    case 'cot(x)'
        fx = sym(k);
        fx1 = diff(fx);
        for l = 1:length(thta)
            mag(l) = subs(fx1,deg2rad(thta(l)));
        end
        axes(handles.axes1)
        hold on
        plot(thta,mag,'r','linewidth',3)
        grid on
        %legend('cot\theta','d(cot\theta)/dx')
        set(handles.text1,'string','DIFFRENTIATION OF COT(X) AND COT(X)')
    case 'sec(x)'
        fx = sym(k);
        fx1 = diff(fx);
        for l = 1:length(thta)
            mag(l) = subs(fx1,deg2rad(thta(l)));
        end
        axes(handles.axes1)
        hold on
        plot(thta,mag,'r','linewidth',3)
        grid on
        %legend('sec\theta','d(sec\theta)/dx')
        set(handles.text1,'string','DIFFRENTIATION OF SEC(X) AND SEC(X)')
    case 'csc(x)'
        fx = sym(k);
        fx1 = diff(fx);
        for l = 1:length(thta)
            mag(l) = subs(fx1,deg2rad(thta(l)));
        end
        axes(handles.axes1)
        hold on
        plot(thta,mag,'r','linewidth',3)
        grid on
        %legend('csc\theta','d(csc\theta)/dx')
        set(handles.text1,'string','DIFFRENTIATION OF CSC(X) AND CSC(X)')
    case 'log(t)'
        fx = sym(k);
        fx1 = diff(fx);
        r = x;
        for l = 1:length(r)
            mag(l) = subs(fx1,r(l));
        end
        axes(handles.axes1)
        hold on
        plot(r,mag,'r','linewidth',3)
        grid on
        %legend('log(x)','d(log(x))/dx')
        set(handles.text1,'string','DIFFRENTIATION OF LOG(X) AND LOG(X)')
    case 'exp(t)'
        fx = sym(k);
        fx1 = diff(fx);
        r = x;
        for l = 1:length(r)
            mag(l) = subs(fx1,r(l));
        end
        axes(handles.axes1)
        hold on
        plot(r,mag,'r','linewidth',1.5)
        grid on
        %legend('e^x','d(e^x)/dx')
        set(handles.text1,'string','DIFFRENTIATION OF EXP(X) AND EXP(X)')
    case d
        fx = sym(k);
        fx1 = diff(fx);
        r = p1;
        for l = 1:length(r)
            mag(l) = subs(fx1,r(l));
        end
        axes(handles.axes1)
        hold on
        plot(r,mag,'r','linewidth',1.8)
        grid on
        %legend(d,strcat('d(',d,')/dx'))
        set(handles.text1,'string',strcat('DIFFRENTIATION OF ',d,' AND ',d))
end

% --- Executes on button press in pushbutton12.
function pushbutton12_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton12 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global z thta x p1
d = z;
k = z;
switch k
    case 'sin(x)'
        fx = sym(k);
        fx1 = int(fx);
        for l = 1:length(thta)
            mag(l) = subs(fx1,deg2rad(thta(l)));
        end
        axes(handles.axes1)
        hold on
        plot(thta,mag,'g','linewidth',3)
        grid on
        %legend('sin\theta','d(sin\theta)/dx')
        set(handles.text1,'string','INTEGRATION OF SIN(X) AND SIN(X)')
    case 'cos(x)'
        fx = sym(k);
        fx1 = int(fx);
        for l = 1:length(thta)
            mag(l) = subs(fx1,deg2rad(thta(l)));
        end
        axes(handles.axes1)
        hold on
        plot(thta,mag,'g','linewidth',3)
        grid on
        %legend('cos\theta','d(cos\theta)/dx')
        set(handles.text1,'string','INTEGRATION OF COS(X) AND COS(X)')
    case 'tan(x)'
        fx = sym(k);
        fx1 = int(fx);
        for l = 1:length(thta)
            mag(l) = subs(fx1,deg2rad(thta(l)));
        end
        axes(handles.axes1)
        hold on
        plot(thta,mag,'g','linewidth',3)
        grid on
        %legend('tan\theta','d(tan\theta)/dx')
        set(handles.text1,'string','INTEGRATION OF TAN(X) AND TAN(X)')
    case 'cot(x)'
        fx = sym(k);
        fx1 = int(fx);
        for l = 1:length(thta)
            mag(l) = subs(fx1,deg2rad(thta(l)));
        end
        axes(handles.axes1)
        hold on
        plot(thta,mag,'g','linewidth',3)
        grid on
        %legend('cot\theta','d(cot\theta)/dx')
        set(handles.text1,'string','INTEGRATION OF COT(X) AND COT(X)')
    case 'sec(x)'
        fx = sym(k);
        fx1 = int(fx);
        for l = 1:length(thta)
            mag(l) = subs(fx1,deg2rad(thta(l)));
        end
        axes(handles.axes1)
        hold on
        plot(thta,mag,'g','linewidth',3)
        grid on
        %legend('sec\theta','d(sec\theta)/dx')
        set(handles.text1,'string','INTEGRATION OF SEC(X) AND SEC(X)')
    case 'csc(x)'
        fx = sym(k);
        fx1 = int(fx);
        for l = 1:length(thta)
            mag(l) = subs(fx1,deg2rad(thta(l)));
        end
        axes(handles.axes1)
        hold on
        plot(thta,mag,'g','linewidth',3)
        grid on
        %legend('csc\theta','d(csc\theta)/dx')
        set(handles.text1,'string','INTEGRATION OF CSC(X) AND CSC(X)')
    case 'log(t)'
        fx = sym(k);
        fx1 = int(fx);
        r = x;
        for l = 1:length(r)
            mag(l) = subs(fx1,r(l));
        end
        axes(handles.axes1)
        hold on
        plot(r,mag,'g','linewidth',3)
        grid on
        %legend('log(x)','d(log(x))/dx')
        set(handles.text1,'string','INTEGRATION OF LOG(X) AND LOG(X)')
    case 'exp(t)'
        fx = sym(k);
        fx1 = int(fx);
        r = x;
        for l = 1:length(r)
            mag(l) = subs(fx1,r(l));
        end
        axes(handles.axes1)
        hold on
        plot(r,mag,'g','linewidth',1.5)
        grid on
        %legend('e^x','d(e^x)/dx')
        set(handles.text1,'string','INTEGRATION OF EXP(X) AND EXP(X)')

     case d
        fx = sym(k);
        fx1 = int(fx);
        r = p1;
        for l = 1:length(r)
            mag(l) = subs(fx1,r(l));
        end
        axes(handles.axes1)
        hold on
        plot(r,mag,'g','linewidth',2.3)
        grid on
        %legend(d,strcat('d(',d,')/dx'))
        set(handles.text1,'string',strcat('INTEGRATION OF ',d,' AND ',d))
end

% --------------------------------------------------------------------
function CL_EAR_Callback(hObject, eventdata, handles)
% hObject    handle to CL_EAR (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
cla(handles.axes1)
reset(handles.axes1)
set(handles.axes1,'box','on')
set(handles.axes1,'xtick',[])
set(handles.axes1,'ytick',[])
set(handles.edit1,'string','')
set(handles.edit2,'string','')
set(handles.edit3,'string','')
set(handles.checkbox2,'value',0)
set(handles.checkbox3,'value',0)

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

% --------------------------------------------------------------------
function CLEAR_AXES_Callback(hObject, eventdata, handles)
% hObject    handle to CLEAR_AXES (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
cla(handles.axes1)
reset(handles.axes1)
set(handles.axes1,'box','on')
set(handles.axes1,'xtick',[])
set(handles.axes1,'ytick',[])


function tapas_hgf_whichworld_plotTraj(r)
% Plots trajectories estimated by fitModel for the hgf_whichworld perceptual model
% Usage:  est = tapas_fitModel(responses, inputs); tapas_hgf_plotTraj(est);
%
% --------------------------------------------------------------------------------------------------
% Copyright (C) 2012-2013 Christoph Mathys, TNU, UZH & ETHZ
%
% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public
% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version). For further details, see the file
% COPYING or <http://www.gnu.org/licenses/>.

% Check whether we have a configuration structure
if ~isfield(r,'c_prc')
    error('tapas:hgf:ConfigRequired', 'Configuration required: before calling tapas_hgf_whichworld_plotTraj, tapas_hgf_whichworld_config has to be called.');
end

% Number of worlds
nw = r.c_prc.nw;

% Define colors
colors = [1 0 0; 0.67 0 1; 0 0.67 1; 0.67 1 0];

% Set up display
scrsz = get(0,'screenSize');
outerpos = [0.2*scrsz(3),0.2*scrsz(4),0.8*scrsz(3),0.8*scrsz(4)];
figure(...
    'OuterPosition', outerpos,...
    'Name','HGF trajectories');

% Number of trials
t = size(r.u,1);

% Optional plotting of standard deviations (true or false)
plotsd2 = true;
plotsd3 = true;

% Subplots
subplot(3,1,1);

if plotsd3 == true
    upper3prior = r.p_prc.mu3_0 +sqrt(r.p_prc.sa3_0);
    lower3prior = r.p_prc.mu3_0 -sqrt(r.p_prc.sa3_0);
    upper3 = [upper3prior; r.traj.mu(:,3)+sqrt(r.traj.sa(:,3))];
    lower3 = [lower3prior; r.traj.mu(:,3)-sqrt(r.traj.sa(:,3))];

    plot(0, upper3prior, 'ob', 'LineWidth', 1);
    hold all;
    plot(0, lower3prior, 'ob', 'LineWidth', 1);
    fill([0:t, fliplr(0:t)], [(upper3)', fliplr((lower3)')], ...
         'b', 'EdgeAlpha', 0, 'FaceAlpha', 0.15);
end
plot(0:t, [r.p_prc.mu3_0; r.traj.mu(:,3)], 'b', 'LineWidth', 2);
hold all;
plot(0, r.p_prc.mu3_0, 'ob', 'LineWidth', 2); % prior
xlim([0 t]);
title('Posterior expectation \mu_3 of log-volatility of tendency x_3', 'FontWeight', 'bold');
xlabel('Trial number');
ylabel('\mu_3');

subplot(3,1,2);
if plotsd2 == true
    for j=1:nw
    upper2prior = r.p_prc.mu2_0(j) +sqrt(r.p_prc.sa2_0(j));
    lower2prior = r.p_prc.mu2_0(j) -sqrt(r.p_prc.sa2_0(j));
    upper2 = [upper2prior; r.traj.mu(:,2,j)+sqrt(r.traj.sa(:,2,j))];
    lower2 = [lower2prior; r.traj.mu(:,2,j)-sqrt(r.traj.sa(:,2,j))];

    plot(0, upper2prior, 'o', 'Color', colors(j,:), 'LineWidth', 1);
    hold all;
    plot(0, lower2prior, 'o', 'Color', colors(j,:), 'LineWidth', 1);
    fill([0:t, fliplr(0:t)], [(upper2)', fliplr((lower2)')], ...
         colors(j,:), 'EdgeAlpha', 0, 'FaceAlpha', 0.15);
    end
end
for j=1:nw
    plot(0:t, [r.p_prc.mu2_0(j); r.traj.mu(:,2,j)], 'Color', colors(j,:), 'LineWidth', 2);
    hold all;
    plot(0, r.p_prc.mu2_0(j), 'o', 'Color', colors(j,:), 'LineWidth', 2); % prior
end
xlim([0 t]);
title('Posterior expectations \mu_2 of tendencies x_2', 'FontWeight', 'bold');
xlabel({'Trial number', ' '}); % A hack to get the relative subplot sizes right
ylabel('\mu_2');
hold off;

subplot(3,1,3);
for j=1:nw
    plot(0:t, [tapas_sgm(r.p_prc.mu2_0(j), 1); tapas_sgm(r.traj.mu(:,2,j), 1)], 'Color', colors(j,:), 'LineWidth', 2);
    hold all;
    plot(0, tapas_sgm(r.p_prc.mu2_0(j), 1), 'o', 'Color', colors(j,:), 'LineWidth', 2); % prior
end
plot(1:t, r.u(:,1), '.', 'Color', [0 0 0]); % inputs
if ~isempty(find(strcmp(fieldnames(r),'y'))) && ~isempty(r.y)
    y = r.y(:,1);
    if ~isempty(find(strcmp(fieldnames(r),'irr')))
        y(r.irr) = NaN; % weed out irregular responses
        plot(r.irr,  1.08.*ones([1 length(r.irr)]), 'x', 'Color', [1 0.7 0], 'Markersize', 11, 'LineWidth', 2); % irregular responses
    end
    if ~any(y>1) && ~any(y<0)
        plot(1:t, y, '.', 'Color', [1 0.7 0]); % responses
    else
        for j=1:nw
            plot(find(y==j), 1.08*ones([1 length(find(y==j))]), '.', 'Color', colors(j,:)); % responses
        end
    end
    title(['Response y, input u (black), and posterior probability of worlds s(\mu_2) for \kappa=', ...
           num2str(r.p_prc.ka), ', \omega=', num2str(r.p_prc.om), ', \vartheta=', num2str(r.p_prc.th)], ...
          'FontWeight', 'bold');
    ylabel('y, u, s(\mu_2)');
    axis([0 t -0.1 1.15]);
else
    title(['Input u (black) and posterior probability of worlds s(\mu_2) for m_3=', ...
           num2str(r.p_prc.m), ', \phi_3=', num2str(r.p_prc.phi), ', \kappa=', ...
           num2str(r.p_prc.ka), ', \omega=', num2str(r.p_prc.om), ', \vartheta=', num2str(r.p_prc.th)], ...
      'FontWeight', 'bold');
    ylabel('u, s(\mu_2)');
    axis([0 t -0.1 1.1]);
end
plot(1:t, 0.5, 'k');
xlabel('Trial number');
hold off;


function result = nsga2(opt, varargin)
% Function: result = nsga2(opt, varargin)
% Description: The main flowchart of of NSGA-II. Note:
%   All objectives must be minimization. If a objective is maximization, the
%   objective should be multipled by -1.
%
% Syntax:
%   result = nsga2(opt): 'opt' is generated by function nsgaopt().
%   result = nsga2(opt, param): 'param' can be any data type, it will be
%       pass to the objective function objfun().
%
%   Then ,the result structure can be pass to plotnsga to display the
%   population:  plotnsga(result);
%
% Parameters:
%   opt : A structure generated by funciton nsgaopt().
%   varargin : Additional parameter will be pass to the objective functions.
%       It can be any data type. For example, if you call: nsga2(opt, param),
%       then objfun would be called as objfun(x,param), in which, x is the
%       design variables vector.
% Return:
%   result : A structure contains optimization result.
%
%         LSSSSWC, NWPU
%   Revision: 1.2  Data: 2011-07-26
%*************************************************************************

tStart = tic();
%*************************************************************************
% Verify the optimization model
%*************************************************************************
opt = verifyOpt(opt);

%*************************************************************************
% variables initialization
%*************************************************************************
nVar    = opt.numVar;
nObj    = opt.numObj;
nCons   = opt.numCons;
popsize = opt.popsize;

% pop : current population
% newpop : new population created by genetic algorithm operators
% combinepop = pop + newpop;
pop = repmat( struct(...
    'var', zeros(1,nVar), ...
    'obj', zeros(1,nObj), ...
    'cons', zeros(1,nCons),...
    'rank', 0,...
    'distance', 0,...
    'prefDistance', 0,...       % preference distance used in R-NSGA-II
    'nViol', 0,...
    'violSum', 0),...
    [1,popsize]);

% state: optimization state of one generation
state = struct(...
'currentGen', 1,...         % current generation number
'evaluateCount', 0,...      % number of objective function evaluation
'totalTime', 0,...          % total time from the beginning
'firstFrontCount', 0,...    % individual number of first front
'frontCount', 0,...         % number of front
'avgEvalTime', 0 ...        % average evaluation time of objective function (current generation)
);

result.pops     = repmat(pop, [opt.maxGen, 1]);     % each row is the population of one generation
result.states   = repmat(state, [opt.maxGen, 1]);   % each row is the optimizaiton state of one generation
result.opt      = opt;                              % use for output

% global variables
global STOP_NSGA;   %STOP_NSGA : used in GUI , if STOP_NSGA~=0, then stop the optimizaiton
STOP_NSGA = 0;

%*************************************************************************
% initialize the P0 population
%*************************************************************************
ngen = 1;
pop = opt.initfun{1}(opt, pop, opt.initfun{2:end});
[pop, state] = evaluate(opt, pop, state, varargin{:});
[opt, pop] = ndsort(opt, pop);

% state
state.currentGen = ngen;
state.totalTime = toc(tStart);
state = statpop(pop, state);

result.pops(1, :) = pop;
result.states(1)  = state;

% output
% plotnsga(result, ngen);
opt = callOutputfuns(opt, state, pop);

%*************************************************************************
% NSGA2 iteration
%*************************************************************************
while( ngen < opt.maxGen && STOP_NSGA==0)
    % 0. Display some information
	ngen = ngen+1;
    state.currentGen = ngen;
%     fprintf('\n\n************************************************************\n');
%     fprintf('*      Current generation %d / %d\n', ngen, opt.maxGen);
%     fprintf('************************************************************\n');

    % 1. Create new population
    newpop = selectOp(opt, pop);
    newpop = crossoverOp(opt, newpop, state);
    newpop = mutationOp(opt, newpop, state);
    [newpop, state] = evaluate(opt, newpop, state, varargin{:});

    % 2. Combine the new population and old population : combinepop = pop + newpop
    combinepop = [pop, newpop];

    % 3. Fast non dominated sort
    [opt, combinepop] = ndsort(opt, combinepop);

    % 4. Extract the next population
    pop = extractPop(opt, combinepop);

    % 5. Save current generation results
    state.totalTime = toc(tStart);
    state = statpop(pop, state);

    result.pops(ngen, :) = pop;
    result.states(ngen)  = state;

    % 6. plot current population and output
%     if( mod(ngen, opt.plotInterval)==0 )
%         plotnsga(result, ngen);
%     end
%     if( mod(ngen, opt.outputInterval)==0 )
%         opt = callOutputfuns(opt, state, pop);
%     end

end

% call output function for closing file
opt = callOutputfuns(opt, state, pop, -1);

% close worker processes
if( strcmpi(opt.useParallel, 'yes'))
    matlabpool close
end

toc(tStart);


function HRVparams = InitializeHRVparams(project_name)
%
%   settings = InitializeHRVparams('project_name')
%
%   OVERVIEW:
%       This file stores settings and should be configured before
%       each use of the PhysioNet Cardiovascular Signal Toolbox:
%       1.  Project Specific Input/Output Data type and Folders
%       2.  How much does the user trust the data
%       3.  Global Settings (Window Size) for signal segmentation
%       4.  Quality Threshold Settings
%       5.  Debug Settings
%       6.  SQI Settings
%       7.  Preprocess Settings
%       8. AF Detection Settings
%       9. Time Domain Analysis Settings
%       10. Frequency Domain Analysis Settings
%       11. SDANN and SDNNI Analysis Settings
%       12. PRSA Analysis Settings
%       13. Peak Detection Settings
%       14. Entropy  and Multiscale Entropy - MSE - Settings
%       15. Detrended Fluctuation Analysis - DFA - Settings
%       16. Poincar� plot - Settings
%       17. Heart Rate Turbulence (HRT) - Settings
%       18. Output Settings
%       19. Time of Process and Filename to Save Data
%
%   INPUT:
%       project_name = a string with the name of the project - this
%       will determine the naming convention of file folders
%
%   OUTPUT:
%       HRVparams - struct of various settings for the hrv_toolbox analysis
%
%   DEPENDENCIES & LIBRARIES:
%       PhysioNet Cardiovascular Signal Toolbox
%       https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox
%
%   REFERENCE:
%   Vest et al. "An Open Source Benchmarked HRV Toolbox for Cardiovascular
%   Waveform and Interval Analysis" Physiological Measurement (In Press), 2018.
%
%	REPO:
%       https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox
%   ORIGINAL SOURCE AND AUTHORS:
%       Adriana N. Vest
%       Giulia Da Poian
%       Dependent scripts written by various authors
%       (see functions for details)
%	COPYRIGHT (C) 2018
%   LICENSE:
%       This software is offered freely and without warranty under
%       the GNU (v3 or later) public license. See license file for
%       more information
%%

if isempty(project_name)
    project_name = 'none';
end

% Set up input options for a specific project
switch project_name
    % Define new project name and parameters
    case 'MyProjectName'                   % Update with your project name
        HRVparams.Fs = NaN;                % Spacify sampling frequency
        HRVparams.readdata = '';           % (Optional) Specify name for data input folder
        HRVparams.writedata = '';          % (Optional) Specify name for data output folder
        HRVparams.datatype = '';           % (Optional) Spacify Data type of input
        HRVparams.ext = '';                % (Optional) Spacify file extension of input (e.g., 'mat','qrs')

    % Existing demo projects
    case 'MVanalysis'                      % Morphological variability analysis ECG
        HRVparams.Fs = 1000;
        HRVparams.readdata = '';
        HRVparams.writedata = '';
        HRVparams.datatype = '';
        HRVparams.ext = '';
    case 'demo_NSR'      % Parameters for demo using MIT nsr data
        HRVparams.readdata = strcat('TestData', filesep, 'Physionet_nsr2db');
        HRVparams.writedata = strcat('OutputData', filesep, 'ResultsNSR');
        HRVparams.ext = 'ecg';
        HRVparams.Fs = 125;
    case 'demo_RRgen'
        HRVparams.writedata = strcat('OutputData', filesep, 'ResultsRRgen');
        HRVparams.Fs = 125;
        HRVparams.demo.length = 5*60*60;   % Length of demo RR intervals in seconds
        HRVparams.demo.pe = 0.0003;        % Probability of ectopy ~ 1 per hr
        HRVparams.demo.pn = 0.0048;        % Probability of noise ~ 16 per hr
        HRVparams.demo.seed = 1;           % Seed for RRGEN
    case 'demoICU'      % Parameters for ICU demo
        HRVparams.readdata = strcat('TestData');
        HRVparams.writedata = strcat('OutputData', filesep, 'ResultsICU');
        HRVparams.ext = 'mat';
        HRVparams.Fs = 128;
    case 'demoAF'      % Parameters for AF demo
        HRVparams.readdata = strcat('TestData');
        HRVparams.writedata = strcat('OutputData', filesep, 'ResultsAFData');
        HRVparams.ext = 'mat';
        HRVparams.Fs = 128;
    case 'demoHRT'      % Parameters for HRT demo
        HRVparams.readdata = strcat('TestData', filesep, 'Physionet_nsr2db');
        HRVparams.writedata = strcat('OutputData', filesep, 'ResultsHRT');
        HRVparams.Fs = 128;
    case 'demoPVC'      % Parameters for PVC demo
        HRVparams.readdata = strcat('TestData', filesep, 'mitdb-Arrhythmia');
        HRVparams.writedata = strcat('OutputData', filesep, 'ResultsPVC');
        HRVparams.Fs = 360;
    otherwise                  % Default
        HRVparams.Fs = NaN;                          % Spacify sampling frequency
        HRVparams.writedata = 'HRV_Output';          % (Optional) Specify name for data output folder

end

if  isempty(HRVparams.writedata)
    % Default data OUTPUT folder name based on project name
    HRVparams.writedata = strcat(project_name,'_Results');
    fprintf('New OUTPUT folder: "%s"\n', HRVparams.writedata)
    mkdir(HRVparams.writedata);          % Create output folder and
elseif ~exist([pwd filesep HRVparams.writedata], 'dir')
    fprintf('New OUTPUT folder: "%s"\n',HRVparams.writedata)
    mkdir(HRVparams.writedata);          % Create output folder and
end
addpath(genpath(HRVparams.writedata));   % Add folder to search path

%% 2. How much does the user trust the data:
% This setting determines how stringently filtered the data is prior to
% calculating HRV metrics. Raw ECG or Pulse data that has been labeled
% using a peak detector (like jqrs) would require the most stringent
% filtering, whereas RR interval data that has been reviewed by a human
% technician would require the least amount of filtering.

%   - qrs detection no beats labeled - most stringent filters
%   - automatic beat detection beat typed - moderately stringent filtered
%   - hand corrected - least filtered, maybe no filter

% EXPLAIN THE THRESHOLDS BETTER
% ADD THIS TO A DEMO

HRVparams.data_confidence_level = 1;
% 1 - raw data with automatic beat detection
% 2 - raw data with automatic beat detection, but beat typed (ie N, SV,etc)
% 3 - technician reviewed data

% * ^^^^ NOT YET IN USE ^^^^  *

%% 3. Global Settings (Window Size)

HRVparams.windowlength = 300;	      % Default: 300, seconds
HRVparams.increment = 30;             % Default: 30, seconds increment
HRVparams.numsegs = 5;                % Default: 5, number of segments to collect with lowest HR
HRVparams.RejectionThreshold = .20;   % Default: 0.2, amount (%) of data that can be rejected before a
                                      % window is considered too low quality for analysis
HRVparams.MissingDataThreshold = .15; % Default: 0.15, maximum percentage of data allowable to be missing
                                      % from a window .15 = 15%
%% 5. Debug Settings

HRVparams.rawsig = 0;           % Load raw signal if it is available for debugging
HRVparams.debug = 0;

%% 6. SQI Analysis Settings
HRVparams.sqi.LowQualityThreshold = 0.9; % Default: 0.9, Threshold for which SQI represents good data
HRVparams.sqi.windowlength = 10;         % Default: 10, seconds, length of the comparison window
HRVparams.sqi.increment = 1;             % Default: 1, seconds
HRVparams.sqi.TimeThreshold = 0.1;       % Default: 0.1, seconds
HRVparams.sqi.margin = 2;                % Default: 2, seconds, Margin time not include in comparison

%% 7. Preprocess Settings

HRVparams.preprocess.figures = 0;                   % Figures on = 1, Figures off = 0
HRVparams.preprocess.gaplimit = 2;                  % Default: 2, seconds; maximum believable gap in rr intervals
HRVparams.preprocess.per_limit = 0.2;               % Default: 0.2, Percent limit of change from one interval to the next
HRVparams.preprocess.forward_gap = 3;	            % Default: 3, Maximum tolerable gap at beginning of timeseries in seconds
HRVparams.preprocess.method_outliers = 'rem';       % Default: 'rem', Method of dealing with outliers
                                                    % 'cub' = replace outlier points with cubic spline method
                                                    % 'rem' = remove outlier points
                                                    % 'pchip' = replace with pchip method
HRVparams.preprocess.lowerphysiolim = 60/160;       % Default: 60/160
HRVparams.preprocess.upperphysiolim = 60/30;        % Default: 60/30
HRVparams.preprocess.method_unphysio = 'rem';       % Default: 'rem', Method of dealing with unphysiologically low beats
                                                    % 'cub' = replace outlier points with cubic spline method
                                                    % 'rem' = remove outlier points
                                                    % 'pchip' = replace with pchip method

% The following settings do not yet have any functional effect on
% the output of preprocess.m:
HRVparams.preprocess.threshold1 = 0.9 ;	        % Default: 0.9, Threshold for which SQI represents good data
HRVparams.preprocess.minlength = 30;            % Default: 30, The minimum length of a good data segment in seconds

%% 8. AF Detection Settings and PVC detection

HRVparams.af.on = 1;              % Default: 1, AF Detection On or Off
HRVparams.af.windowlength = 30;   % Default: 30, Set to include ~30 beats in each window
HRVparams.af.increment = 30;      % Default: 30, No overlap necessary in AF feat calc

HRVparams.PVC.qrsth = 0.1;        % Default: 0.1, threshold for qrs detection

%% 9. Time Domain Analysis Settings

HRVparams.timedomain.on = 1;             % Default: 1, Time Domain Analysis 1=On or 0=Off
HRVparams.timedomain.dataoutput = 0;     % 1 = Print results to .txt file
                                         % Anything else = utputs to return variables only
                                         % returned variables
HRVparams.timedomain.alpha = 50   ;      % Default: 50 ,In msec
HRVparams.timedomain.win_tol = .15;      % Default: .15, Maximum percentage of data allowable
                                         % to be missing from a window

%% 10. Frequency Domain Analysis Settings

HRVparams.freq.on = 1;              % Default: 1, Frequency Domain Analysis 1=On or 0=Off

ULF = [0 .0033];                    % Requires window > 300 s
VLF = [0.0033 .04];                 % Requires at least 300 s window
LF = [.04 .15];                     % Requires at least 25 s window
HF = [0.15 0.4];                    % Requires at least 7 s window

HRVparams.freq.limits = [ULF; VLF; LF; HF];
HRVparams.freq.zero_mean = 1;               % Default: 1, Option for subtracting the mean from the input data
HRVparams.freq.method = 'lomb';             % Default: 'lomb'
                                            % Options: 'lomb', 'burg', 'fft', 'welch'
HRVparams.freq.plot_on = 0;

% The following settings are for debugging spectral analysis methods
HRVparams.freq.debug_sine = 0;              % Default: 0, Adds sine wave to tachogram for debugging
HRVparams.freq.debug_freq = 0.15;           % Default: 0.15
HRVparams.freq.debug_weight = .03;          % Default: 0.03

% Lomb:
HRVparams.freq.normalize_lomb = 0;	        % Default: 0
                                            % 1 = Normalizes Lomb Periodogram,
                                            % 0 = Doesn't normalize

% Burg: (not recommended)
HRVparams.freq.burg_poles = 15;    % Default: 15, Number of coefficients
                                   % for spectral estimation using the Burg
                                   % method (not recommended)

% The following settings are only used when the user specifies spectral
% estimation methods that use resampling : 'welch','fft', 'burg'
HRVparams.freq.resampling_freq = 7;             % Default: 7, Hz
HRVparams.freq.resample_interp_method = 'cub';  % Default: 'cub'
                                                % 'cub' = cublic spline method
                                                % 'lin' = linear spline method
HRVparams.freq.resampled_burg_poles = 100;      % Default: 100

%% 11. SDANN and SDNNI Analysis Settings
HRVparams.sd.on = 1;                        % Default: 1, SD analysis 1=On or 0=Off
HRVparams.sd.segmentlength = 300;           % Default: 300, windows length in seconds

%% 12. PRSA Analysis Settings

HRVparams.prsa.on = 1;             % Default: 1, PRSA Analysis 1=On or 0=Off
HRVparams.prsa.win_length = 30;    % Default: 30, The length of the PRSA signal
                                   % before and after the anchor points
                                   % (the resulting PRSA has length 2*L)
HRVparams.prsa.thresh_per = 20;    % Default: 20%, Percent difference that one beat can
                                   % differ from the next in the prsa code
HRVparams.prsa.plot_results = 0;   % Default: 0
HRVparams.prsa.scale = 2;          % Default: 2, scale parameter for wavelet analysis (to compute AC and DC)
HRVparams.prsa.min_anch = 20;       % Default: 20, minimum number of anchors point required to create the "average signal"

%% 13. Peak Detection Settings

% The following settings are for jqrs.m

HRVparams.PeakDetect.REF_PERIOD = 0.250;   % Default: 0.25 (should be 0.15 for FECG), refractory period in sec between two R-peaks
HRVparams.PeakDetect.THRES = .6;           % Default: 0.6, Energy threshold of the detector
HRVparams.PeakDetect.fid_vec = [];         % Default: [], If some subsegments should not be used for finding the optimal
                                           % threshold of the P&T then input the indices of the corresponding points here
HRVparams.PeakDetect.SIGN_FORCE = [];      % Default: [], Force sign of peaks (positive value/negative value)
HRVparams.PeakDetect.debug = 0;            % Default: 0
HRVparams.PeakDetect.ecgType = 'MECG';     % Default : MECG, options (adult MECG) or featl ECG (fECG)
HRVparams.PeakDetect.windows = 15;         % Befautl: 15,(in seconds) size of the window onto which to perform QRS detection

%% 14. Entropy Settings
% Multiscale Entropy
HRVparams.MSE.on = 1;                      % Default: 1, MSE Analysis 1=On or 0=Off
HRVparams.MSE.windowlength = [];           % Default: [], windows size in hours, default perform MSE on the entire signal
HRVparams.MSE.increment = [];              % Default: [], window increment in hours
HRVparams.MSE.RadiusOfSimilarity = 0.15;   % Default: 0.15, Radius of similarity (% of std)
HRVparams.MSE.patternLength = 2;           % Default: 2, pattern length
HRVparams.MSE.maxCoarseGrainings = 20;     % Default: 20, Maximum number of coarse-grainings
HRVparams.MSE.method = 'fir';           % Default 'fir', method use to generate the coarse-grain
                                           %                time series  options 'fir', 'butter'
HRVparams.MSE.moment = 'mean';             % Default: 'mean', moment used to coarse-grain the time series
                                           %           options 'mean', 'variance'
HRVparams.MSE.constant_r = 1;              % Default: 1, 1 use r as function of std of original time
                                           %             series, 0 compute r as function of std at each scale

% SampEn an ApEn
HRVparams.Entropy.on = 1;                     % Default: 1, MSE Analysis 1=On or 0=Off
HRVparams.Entropy.RadiusOfSimilarity = 0.15;  % Default: 0.15, Radius of similarity (% of std)
HRVparams.Entropy.patternLength = 2;          % Default: 2, pattern length

%% 15. DFA Settings

HRVparams.DFA.on = 1;               % Default: 1, DFA Analysis 1=On or 0=Off
HRVparams.DFA.windowlength = [];    % Default [], windows size in hours, default perform DFA on the entair signal
HRVparams.DFA.increment = [];       % Default: [], window increment in hours
HRVparams.DFA.minBoxSize = 4 ;      % Default: 4, Smallest box width
HRVparams.DFA.maxBoxSize = [];      % Largest box width (default in DFA code: signal length/4)
HRVparams.DFA.midBoxSize = 16;      % Medium time scale box width (default in DFA code: 16)

%% 16. Poincar� plot

HRVparams.poincare.on = 1;     % Default: 1, Poincare Analysis 1=On or 0=Off

%% 17. Heart Rate Turbulence (HRT) - Settings

HRVparams.HRT.on = 1;                        % Default: 1, HRT Analysis 1=On or 0=Off
HRVparams.HRT.BeatsBefore = 2;               % Default: 2, # of beats before PVC
HRVparams.HRT.BeatsAfter = 16;               % Default: 16, # of beats after PVC and CP
HRVparams.HRT.GraphOn = 0;                   % Default: 0, do not plot
HRVparams.HRT.windowlength = 24;             % Default 24h, windows size in hours
HRVparams.HRT.increment = 24;                % Default 24h, sliding window increment in hours
HRVparams.HRT.filterMethod = 'mean5before';  % Default mean5before, HRT filtering option

%% 18. Output Settings

HRVparams.gen_figs = 0;             % Generate figures
HRVparams.save_figs = 0;            % Save generated figures
if HRVparams.save_figs == 1
    HRVparams.gen_figs = 1;
end

% Format settings for HRV Outputs
HRVparams.output.format = 'csv';        % 'csv' - creates csv file for output
                                        % 'mat' - creates .mat file for output
HRVparams.output.separate = 1;          % Default : 1 = separate files for each subject
                                        %           0 = all results in one file
HRVparams.output.num_win = [];          % Specify number of lowest hr windows returned
                                        % leave blank if all windows should be returned
                                        % Format settings for annotations generated
HRVparams.output.ann_format = 'binary'; % 'binary'  = binary annotation file generated
                                        % 'csv'     = ASCII CSV file generated

%% 19. Filename to Save Data
HRVparams.time = datestr(now, 'yyyymmdd');              % Setup time for filename of output
HRVparams.filename = [HRVparams.time '_' project_name];

%% Export Parameter as Latex Table
% Note that if you change the order of the parameters or add parameters
% this might not work

ExportHRVparams(HRVparams);

end


%DstarPO D*-PO navigation class
%
% A concrete subclass of the Navigation class that implements the D*
% navigation algorithm; facilitates incremental replanning. This
% implementation of D* is intended for multiobjective optimization (MOO)
% problems - i.e. optimizes over several objectives/criteria - with the use
% of Pareto fronts (see Lavin paper).
%
% Methods::
% plan              Compute the cost map given a goal and map
% path              Compute a path to the goal
% visualize         Display the obstacle map (deprecated)
% plot              Display the obstacle map
% cost_get          Return the specified cost layer
% costmap_modify    Modify the costmap
% modify_cost       Modify the costmap (deprecated, use costmap_modify)
% costmap_get       Return the current costmap
% costmap_set       Set the current costmap
% distancemap_get   Set the current distance map
% display           Print the parameters in human readable form
% char              Convert to string
%
% Properties::
% TBD
%
% Example::
%        load map1              % load map
%        goal = [50,30];
%        start=[20,10];
%        ds = DstarPO(map);     % create navigation object
%        ds.plan(goal,1)        % create plan for specified goal
%        ds.path(start)         % animate path from this start location
% Example 2:
%       goal = [100;100];
%       start = [1;1];
%       ds = DstarPO(0);        % create Navigation object with random occupancy grid
%       ds.addCost(1,L);        % add 1st add'l cost layer L
%       ds.plan(goal,2);        % setup costmap for specified goal
%       ds.path(start);         % plan solution path start-goal, animate
%       P = as.path(start);     % plan solution path start-goal, return path
%
% Notes::
% - Obstacles are represented by Inf in the costmap.
%
% References::
% - The D* algorithm for real-time planning of optimal traverses,
%   A. Stentz, Tech. Rep. CMU-RI-TR-94-37, The Robotics Institute,
%   Carnegie-Mellon University, 1994.
% - A Pareto Optimal D* Search Algorithm for Multiobjective Path Planning,
%   A. Lavin.
% - Robotics, Vision & Control, Sec 5.2.2,
%   Peter Corke, Springer, 2011.
%
% Author::
% Alexander Lavin based on Dstar by Peter Corke
%
% See also Navigation, Dstar, DstarMOO, Astar, DXform.

% Copyright (C) 1993-2015, by Peter I. Corke, Alexander Lavin
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% This is an original algorithm written by Alexander Lavin.
% http://alexanderlavin.com

% Implementation notes:
%
% All the state is kept in the structure called d
% X is an index into the array of states.
% state pointers are kept as matlab array index rather than row,col format

classdef DstarPO < Navigation

    properties (SetAccess=private, GetAccess=private)

        costmap   % world cost map: obstacle = Inf
        G         % index of goal point
        N         % number of objectives

        % info kept per cell (state)
        b       % backpointer (0 means not set)
        t       % tag: NEW OPEN CLOSED

        cost_g       % path distance summation
        cost_h       % path heuristic (state to goal) cost
        cost_01      % add'l cost layer 01 (unused)
        cost_02      % add'l cost layer 02 (unused)
        cost_03      % add'l cost layer 03 (unused)
                     % add more cost layers if needed...

        priority
        tie

        % list of open states: 2xN matrix
        %   each open point is a column, row 1 = index of cell, row 2 = k
        openlist
        niter

        changed

        openlist_maxlen     % keep track of maximum length
        quiet

        % tag state values
        NEW = 0;
        OPEN = 1;
        CLOSED = 2;
    end

    methods

        % constructor
        function ds = DstarPO(world, varargin)
            %DstarPO.DstarPO D*-PO constructor
            %
            % DS = Dstar(MAP, OPTIONS) is a D* navigation object, and MAP is an
            % occupancy grid, a representation of a planar world as a
            % matrix whose elements are 0 (free space) or 1 (occupied).
            % The occupancy grid is coverted to a costmap with a unit cost
            % for traversing a cell.
            %
            % Options::
            % 'goal',G      Specify the goal point (2x1)
            % 'metric',M    Specify the distance metric as 'euclidean' (default)
            %               or 'cityblock'.
            % 'inflate',K   Inflate all obstacles by K cells.
            % 'quiet'       Don't display the progress spinner
            %
            % Other options are supported by the Navigation superclass.
            %
            % Notes::
            % - If MAP == 0 a random map is created.
            %
            % See also Navigation.Navigation.

            % invoke the superclass constructor
            ds = ds@Navigation(world, varargin{:});

            opt.quiet = false;
            opt = tb_optparse(opt, varargin);
            ds.quiet = opt.quiet;

            ds.occgrid2costmap(ds.occgrid);

            % init the D* state variables
            ds.reset();
            if ~isempty(ds.goal)
                ds.goal_change();
            end
            ds.changed = false;
        end

        function reset(ds)
            %DstarPO.reset Reset the planner
            %
            % DS.reset() resets the D* planner.  The next instantiation
            % of DS.plan() will perform a global replan.

            % build the matrices required to hold the state of each cell for D*
            ds.b = zeros(size(ds.costmap), 'uint32');     % backpointers
            ds.t = zeros(size(ds.costmap), 'uint8');      % tags
            ds.cost_g = Inf*ones(size(ds.costmap));       % path cost estimate
            ds.openlist = zeros(2,0);                     % the open list, one column per point

            ds.openlist_maxlen = -Inf;
        end

        function goal_change(ds)

            if isempty(ds.b)
                return;
            end
            goal = ds.goal;

            % keep goal in index rather than row,col format
            ds.G = sub2ind(size(ds.occgrid), goal(2), goal(1));
            ds.INSERT(ds.G, ds.projectCost(ds.G), 'goalset');
            ds.cost_g(ds.G) = 0;

            % new goal changes cost layers:
            ds.calcHeuristic(ds.occgrid, ds.goal);
        end

        function s = char(ds)
            %DstarPO.char Convert navigation object to string
            %
            % DS.char() is a string representing the state of the Dstar
            % object in human-readable form.
            %
            % See also Dstar.display, Navigation.char.

            % most of the work is done by the superclass
            s = char@Navigation(ds);

            % Dstar specific stuff
            if ~isempty(ds.costmap)
                s = char(s, sprintf('  costmap: %dx%d, open list %d', size(ds.costmap), numcols(ds.openlist)));
            else
                s = char(s, sprintf('  costmap: empty:'));
            end
        end

        function plot(ds, varargin)
            %DstarPO.plot Visualize navigation environment
            %
            % DS.plot() displays the occupancy grid and the goal distance
            % in a new figure.  The goal distance is shown by intensity which
            % increases with distance from the goal.  Obstacles are overlaid
            % and shown in red.
            %
            % DS.plot(P) as above but also overlays a path given by the set
            % of points P (Mx2).
            %
            % See also Navigation.plot.

            plot@Navigation(ds, 'distance', ds.cost_h, varargin{:});
        end

        % invoked by Navigation.step
        function n = next(ds, current)

            if ds.changed
                error('Cost map has changed, replan');
            end
            X = sub2ind(size(ds.costmap), current(2), current(1));
            X = ds.b(X);
            if X == 0
                n = [];
            else
                [r,c] = ind2sub(size(ds.costmap), X);
                n = [c;r];
            end
        end

        function plan(ds, goal, N)
            %DstarPO.plan Plan path to goal
            %
            % DS.plan() updates DS with a costmap of distance to the
            % goal from every non-obstacle point in the map.  The goal is
            % as specified to the constructor.
            %
            % DS.plan(GOAL) as above but uses the specified goal.
            %
            % Note::
            % - If a path has already been planned, but the costmap was
            %   modified, then reinvoking this method will replan,
            %   incrementally updating the plan at lower cost than a full
            %   replan.
            %
            % Inputs:
            %   goal: goal state coordinates
            %   N: number of optimization objectives; standard D* is 2
            %   (i.e. distance and heuristic)

            ds.N = N; % number of optimization objectives
            ds.openlist = zeros(ds.N+1,0);

            % Setup cost layers. If a
            % cost layer is goal-dependent, it's setup function needs to
            % also be called in DS.goal_change(). If more cost layers are
            % needed, add similar to DS.cost_01.

            % initializations first:
            ds.cost_g = zeros(size(ds.occgrid));
            ds.cost_h = zeros(size(ds.occgrid)); % filled after setting goal below
            % if add'l costs haven't been added with addCost()
            if isempty(ds.cost_01)
                ds.cost_01 = zeros(size(ds.occgrid));
            end
            if isempty(ds.cost_02)
                ds.cost_02 = zeros(size(ds.occgrid));
            end
            if isempty(ds.cost_03)
                ds.cost_03 = zeros(size(ds.occgrid));
            end

            if nargin > 1
                ds.goal = goal; % invokes superclass method set.goal()
            end
            % for replanning no goal is needed,
            if isempty(ds.goal)
                error('must specify a goal point');
            end

            % Setup cost layers DS.cost_g and DS.cost_h.
            % assign values to the distance cost layer, set as DS.costmap
            ds.occgrid2costmap(ds.occgrid);
            % assign values to the heuristic cost layer, set as DS.cost_h
            ds.calcHeuristic(ds.occgrid, ds.goal);
            % Additional cost layers are added by the user with the
            % DS.addCost() method

            % Cost priority/tiebreaker: cost_g (distance to node)
            ds.priority = ds.cost_g;
            ds.tie = 1; % first cost: cost_g

            ds.niter = 0;
            while true
                if ~ds.quiet && mod(ds.niter, 20) == 0
                    ds.spinner();
                end
                ds.niter = ds.niter + 1;

                if ds.PROCESS_STATE() < 0
                    break;
                end
                if ds.verbose
                    disp(' ')
                end
            end
            if ~ds.quiet
                fprintf('\r');
            end
            ds.changed = false;
        end

        function layer = cost_get(ds)
        %DstarPO.cost_get Get the specified cost layer
            layer = ds.cost_02;
        end

        function c = distancemap_get(ds)
        %DstarPO.distancemap_get Get the current distance map
        %
        % C = DS.distancemap_get() is the current distance map.  This map is the same size
        % as the occupancy grid and the value of each element is the shortest distance
        % from the corresponding point in the map to the current goal.  It is computed
        % by Dstar.plan.
        %
        % See also Dstar.plan.
            c = ds.cost_h; % heuristic
        end

        function c = costmap_get(ds)
        %DstarPO.costmap_get Get the current costmap
        %
        % C = DS.costmap_get() is the current costmap.  The cost map is the same size
        % as the occupancy grid and the value of each element represents the cost
        % of traversing the cell.  It is autogenerated by the class constructor from
        % the occupancy grid such that:
        % - free cell (occupancy 0) has a cost of 1
        % - occupied cell (occupancy >0) has a cost of Inf
        %
        % See also Dstar.costmap_set, Dstar.costmap_modify.

            c = ds.costmap;
        end

        function costmap_set(ds, costmap)
        %DstarPO.costmap_set Set the current costmap
        %
        % DS.costmap_set(C) sets the current costmap.  The cost map is the same size
        % as the occupancy grid and the value of each element represents the cost
        % of traversing the cell.  A high value indicates that the cell is more costly
        % (difficult) to traverese.  A value of Inf indicates an obstacle.
        %
        % Notes::
        % - After the cost map is changed the path should be replanned by
        %   calling DS.plan().
        %
        % See also Dstar.costmap_get, Dstar.costmap_modify.
            if ~all(size(costmap) == size(ds.occgrid))
                error('costmap must be same size as occupancy grid');
            end
            ds.costmap = costmap;
            ds.changed = true;
        end

        function costmap_modify(ds, point, newcost)
        %DstarPO.costmap_modify Modify cost map
        %
        % DS.costmap_modify(P, NEW) modifies the cost map at P=[X,Y] to
        % have the value NEW.  If P (2xM) and NEW (1xM) then the cost of
        % the points defined by the columns of P are set to the corresponding
        % elements of NEW.
        %
        % Notes::
        % - After one or more point costs have been updated the path
        %   should be replanned by calling DS.plan().
        % - Replaces modify_cost, same syntax.
        %
        % See also Dstar.costmap_set, Dstar.costmap_get.

            if numel(point) == 2
                % for case of single point ensure it is a column vector
                point = point(:);
            end
            if numcols(point) ~= numcols(newcost)
                error('number of columns in point must match columns in newcost');
            end
            for i=1:numcols(point)
                X = sub2ind(size(ds.costmap), point(2,i), point(1,i));
                ds.costmap(X) = newcost(i);
            end
            if ds.t(X) == ds.CLOSED
                ds.INSERT(X, ds.h(X), 'modifycost');
            end
            ds.changed = true;
        end

        function addCost(ds, layer, values)
        %DstarPO.addCost Add an additional cost layer
        %
        % DS.addCost(layer,values) adds the matrix specified by values as a
        % cost layer.
        % Inputs
        %   layer: 1, 2, or 3 to specify which cost layer to add
        %   values: normalized matrix the size of the environment (100x100)
            if size(values)~=size(ds.occgrid)
                display('Layer size does not match the environment')
                return
            end
            if max(max(values))~=1 || min(min(values))~=0
                display('Layer values are not normalized [0:1]')
                return
            end

            if layer==1
                ds.cost_01 = values;
            elseif layer==2
                ds.cost_02 = values;
            elseif layer==3
                ds.cost_03 = values;
            else
                display('Layer index out of range')
            end
        end

    end % public methods

    methods (Access=protected)

        function occgrid2costmap(ds, og, cost)
            if nargin < 3
                cost = 1;
            end
            ds.costmap = og;
            ds.costmap(ds.costmap==1) = Inf;      % occupied cells have Inf driving cost
            ds.costmap(ds.costmap==0) = cost;     % unoccupied cells have driving cost
        end

        function calcHeuristic(ds, grid, goal)
            ds.cost_h=zeros(size(grid));
            for ii=1:size(grid,1)
                for jj=1:size(grid,2)
                    ds.cost_h(ii,jj)=sqrt((ii-goal(1))^2+(jj-goal(2))^2);
                end
            end
        end

        % The main D* function as per the Stentz paper, comments Ln are the original
        % line numbers.
        function r = PROCESS_STATE(d)
            % States with the lowest cost value are removed from the
            % open list

            % Get Pareto optimal point off the open list
            [idx] = paretofront(normc(d.openlist(2:size(d.openlist,1),:)')); % w/ normalization
            front = d.openlist(:,idx);
            [k_old,col] = min(front(d.tie+1,:)); % d.tie specifies the row (cost_g) for tiebreaker
            X = front(1,col); % L1

            if isempty(X) % L2
                r = -1;
                return;
            end

            d.DELETE(X); % L3

            d.priority = d.cost_g; % updates priority cost layer

            if k_old < d.priority(X) % L4
                d.message('k_old < h(X):  %f %f\n', k_old, d.priority(X));
                for Y=d.neighbours(X) % L5
                    if (d.priority(Y) <= k_old) && (d.priority(X) > d.updateCosts(Y,X,0))  % L6
                        d.b(X) = Y;
                        d.updateCosts(X,Y,d.N); %L7
                    end
                end
            end

            % can we lower the path cost of any neighbours?
            if k_old == d.priority(X) % L8
                d.message('k_old == h(X): %f\n', k_old);
                for Y=d.neighbours(X) % L9
                    if (d.t(Y) == d.NEW) || ... % L10-12
                            ( (d.b(Y) == X) && (d.priority(Y) ~= d.updateCosts(Y,X,0)) ) || ...
                            ( (d.b(Y) ~= X) && (d.priority(Y) > d.updateCosts(Y,X,0)) )
                        % Update and project the costs:
                        d.updateCosts(Y,X,d.N);
                        objspace = d.projectCost(Y,X);
                        d.b(Y) = X;
                        d.INSERT(Y, objspace, 'L13'); % L13
                    end
                 end
            else % L14
                d.message('k_old > h(X)');
                for Y=d.neighbours(X) % L15
                    if (d.t(Y) == d.NEW) || ( (d.b(Y) == X) && (d.priority(Y) ~= d.updateCosts(Y,X,0)) )
                        d.updateCosts(Y,X,d.N);
                        objspace = d.projectCost(Y,X);
                        d.b(Y) = X;
                        d.INSERT(Y, objspace, 'L18'); % L18
                    else
                        if ( (d.b(Y) ~= X) && (d.priority(Y) > d.updateCosts(Y,X,0)) )
                            d.INSERT(X, d.projectCost(X), 'L21');                    % L21
                        else
                            if (d.b(Y) ~= X) && (d.priority(X) > d.updateCosts(Y,X,0)) && ...
                                    (d.t(Y) == d.CLOSED) && d.priority(Y) > k_old
                                d.INSERT(Y, d.projectCost(Y), 'L25');                % L25
                            end
                        end
                    end
                 end
            end

            r = 0;
            return;
        end % process_state

        function k_new = updateCosts(ds, a, b, obj)
            % NOTE: Only for costs that accumulate (i.e. sum) over the
            % path, and for dynamic costs.
            % E.g. the heuristic parameter DS.cost_h only needs updating
            % when the goal state changes; it's values are stored for each
            % cell.
            %
            % Location moving from state b to a.
            if nargout > 0
                k_new = ds.cost_g(b) + ds.dc(b,a);
                return
            end
            if obj == 0                        % just return what the new priority cost would be (k_new)
                return
            end
            if obj > 1                         % base case
                ds.cost_g(a) = ds.cost_g(b) + ds.dc(b,a);
                % (no heuristic update needed)
            end
            if obj > 2                         % w/ cost_01: elevation
                % (no elevation update needed)
            end
            if obj > 3                         % w/ cost_02: solar
                sV = [cos(ds.niter/100);sin(ds.niter/100)]; % rotates 1rad per 100 steps
                ds.cost_02(a) = dot(sV,ds.vc(b,a));
            end
            if obj > 4                         % w/ cost_03: risk
                % (no risk update needed)
            end
        end

        function pt = projectCost(ds, a, b)
            % Returns the projection of state a into objective space. If
            % specified, location is moving from b to a.
            switch nargin
                case 2
                    pt = [ds.cost_g(a);
                          ds.cost_h(a);
                          ds.cost_01(a);
                          ds.cost_02(a);
                          ds.cost_03(a);
                          ];
                case 3
                    pt = [ds.cost_g(b) + ds.dc(a,b);
                          ds.cost_h(a);
                          ds.cost_01(a);
                          ds.cost_02(a);
                          ds.cost_03(a);
                          ];
                otherwise
                    return
            end
        end

        function kk = k(ds, X)
            i = ds.openlist(1,:) == X;
            kk = ds.openlist(2, i);
        end

        function INSERT(ds, X, pt, where)
            % Add state X to the openlist with objective space values
            % specified by pt.

            % where is for diagnostic purposes only
            ds.message('insert (%s) %d = %f\n', where, X, pt);

            i = find(ds.openlist(1,:) == X);
            if length(i) > 1
                error('D*:INSERT: state in open list %d times', X);
            end

            if ds.t(X) == ds.NEW
                % add a new column to the open list
                ds.openlist = [ds.openlist [X; pt]];
            elseif ds.t(X) == ds.OPEN
%                 k_new = min( ds.openlist(2,i), h_new );
            elseif ds.t(X) == ds.CLOSED
                if pt(ds.tie) < ds.priority(X) % break tie w/ ds.tie index
                    % add a new column to the open list
                    ds.openlist = [ds.openlist [X; pt]];
                end
            end

            % keep track of the max length of the openlist:
            if numcols(ds.openlist) > ds.openlist_maxlen
                ds.openlist_maxlen = numcols(ds.openlist);
            end

            ds.t(X) = ds.OPEN;
        end

        function DELETE(ds, X)
            ds.message('delete %d\n', X);
            i = find(ds.openlist(1,:) == X);
            if length(i) ~= 1
                error('D*:DELETE: state %d doesnt exist', X);
            end
            ds.openlist(:,i) = []; % remove the column
            ds.t(X) = ds.CLOSED;
        end

        function kmin = GET_KMIN(ds)
            kmin = min(ds.openlist(2,:));
        end

        % return the distance of moving from state X to state Y
        function cost = dc(ds, X, Y)
            [r,c] = ind2sub(size(ds.costmap), [X; Y]);
            dist = sqrt(sum(diff([r c]).^2));
            dcost = (ds.costmap(X) + ds.costmap(Y))/2;

            cost = dist * dcost;
        end

        % return the robot unit vector; direction of moving from state X to state Y
        function vector = vc(ds, X, Y)
            [Xi,Xj] = ind2sub(size(ds.occgrid),X);
            [Yi,Yj] = ind2sub(size(ds.occgrid),Y);
            vector = [Yi-Xi;Yj-Xj];
            vector = vector/norm(vector);
%             slope = vector(2) / vector(1);
%             theta = dot([0,1],[vector])/(norm([0,1])*norm(vector));
        end

        % return index of neighbour states as a row vector
        function Y = neighbours(ds, X)
            dims = size(ds.costmap);
            [r,c] = ind2sub(dims, X);

            % list of 8-way neighbours
            Y = [r-1 r-1 r-1 r r  r+1 r+1 r+1; c-1 c c+1 c-1 c+1 c-1 c c+1];
            % only use neighbors w/in grid bounds...
            k = (min(Y)>0) & (Y(1,:)<=dims(1)) & (Y(2,:)<=dims(2));
            Y = Y(:,k);
            Y = sub2ind(dims, Y(1,:)', Y(2,:)')';
        end

    end % end of protected methods
end % classdef


function varargout = particleinB_E_gui(varargin)
% PARTICLEINB_E_GUI M-file for particleinB_E_gui.fig
%      PARTICLEINB_E_GUI, by itself, creates a new PARTICLEINB_E_GUI or raises the existing
%      singleton*.
%
%      H = PARTICLEINB_E_GUI returns the handle to a new PARTICLEINB_E_GUI or the handle to
%      the existing singleton*.
%
%      PARTICLEINB_E_GUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in PARTICLEINB_E_GUI.M with the given input arguments.
%
%      PARTICLEINB_E_GUI('Property','Value',...) creates a new PARTICLEINB_E_GUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before particleinB_E_gui_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to particleinB_E_gui_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 particleinB_E_gui

% Last Modified by GUIDE v2.5 17-Jun-2011 05:04:25

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @particleinB_E_gui_OpeningFcn, ...
                   'gui_OutputFcn',  @particleinB_E_gui_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 particleinB_E_gui is made visible.
function particleinB_E_gui_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 particleinB_E_gui (see VARARGIN)

% Choose default command line output for particleinB_E_gui
handles.output = hObject;

%close all;
%clear all;
clc;

set(handles.vx,'Value',0);
set(handles.vy,'Value',0);
set(handles.vz,'Value',0);

set(handles.x,'Value',-10);
set(handles.y,'Value',0);
set(handles.z,'Value',0);

set(handles.Bx,'Value',0);
set(handles.By,'Value',-6);
set(handles.Bz,'Value',0);
set(handles.Ex,'Value',0)
set(handles.Ey,'Value',0)
set(handles.Ez,'Value',2)

set(handles.q,'Value',1);
set(handles.m,'Value',5);

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = particleinB_E_gui_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 button press in start.
function start_Callback(hObject, eventdata, handles)
% hObject    handle to start (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.stop,'String','Stop!!');
guidata(hObject, handles);

v0 = [get(handles.vx,'Value'), get(handles.vy,'Value'), get(handles.vz,'Value') ]';   %initial velocity
B = [get(handles.Bx,'Value'), get(handles.By,'Value'), get(handles.Bz,'Value') ]';                                                %magnitude of B
E = [get(handles.Ex,'Value'), get(handles.Ey,'Value'), get(handles.Ez,'Value') ]';                                                %magnitude of B
m = get(handles.m,'Value');                                                        % mass
q = get(handles.q,'Value');                                                         % charge on particle
r0 = [get(handles.x,'Value'), get(handles.y,'Value'), get(handles.z,'Value') ]';    % initial position of particle
tspan = [0 70];

%to show B's direction
[x_q,y_q] = meshgrid(-15:12:15,-15:12:15);
z_q=10*ones(size(x_q));

u_q=B(1)*ones(size(x_q));
v_q=B(2)*ones(size(x_q));
w_q=B(3)*ones(size(x_q));
quiver3(x_q,y_q,z_q,u_q,v_q,w_q);
hold all;

% TO show electric field lines
z_q=-10*ones(size(x_q));

u_q=E(1)*ones(size(x_q));
v_q=E(2)*ones(size(x_q));
w_q=E(3)*ones(size(x_q));
quiver3(x_q,y_q,z_q,u_q,v_q,w_q);

legend('B','E');

% To draw axis and all
a_a = -15:0.1:15;
z_a = zeros(size(a_a));
plot3(a_a,z_a,z_a,'k','LineWidth',2);
plot3(z_a,a_a,z_a,'k','LineWidth',2);
plot3(z_a,z_a,a_a,'k','LineWidth',2);

% To set axis limits
%xlim([-15 15]);
%ylim([-15 15]);
%zlim([-15 15])

xlabel ('x axis');
ylabel ('y axis');
zlabel ('z axis');
title ('Particle in a magnetic field');

rotate3d(handles.axes,'on');

plot3(r0(1),r0(2),r0(3),'*m','MarkerSize',9,'LineWidth',2);

y0 = [r0; v0];
f = @(t,y) [y(4:6); (q/m)*cross(y(4:6),B)+E];
[t,y] = ode23t(f,tspan,y0);

%To show animation
for n=1:length(y)
    plot3(y(n,1),y(n,2),y(n,3),'--.r');
    pause(0.00001);

    z_z = get(handles.stop,'String');
    if z_z == 'Stoped'
        break;
    end

end

guidata(hObject, handles);

% --- Executes on slider movement.
function B_Callback(hObject, eventdata, handles)
% hObject    handle to B (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function m_Callback(hObject, eventdata, handles)
% hObject    handle to m (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.m,'Value');
set(handles.m_text,'String',num2str(a));
guidata(hObject, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function q_Callback(hObject, eventdata, handles)
% hObject    handle to q (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.q,'Value');
set(handles.q_text,'String',num2str(a));
guidata(hObject, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

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

% --- Executes on button press in stop.
function stop_Callback(hObject, eventdata, handles)
% hObject    handle to stop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.stop,'String','Stoped');
guidata(hObject, handles);

% --- Executes on slider movement.
function x_Callback(hObject, eventdata, handles)
% hObject    handle to x (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.x,'Value');
set(handles.x_text,'String',num2str(a));
guidata(hObject, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function y_Callback(hObject, eventdata, handles)
% hObject    handle to y (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.y,'Value');
set(handles.y_text,'String',num2str(a));
guidata(hObject, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function z_Callback(hObject, eventdata, handles)
% hObject    handle to z (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.z,'Value');
set(handles.z_text,'String',num2str(a));
guidata(hObject, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function vx_Callback(hObject, eventdata, handles)
% hObject    handle to vx (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.vx,'Value');
set(handles.vx_text,'String',num2str(a));
guidata(hObject, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function vy_Callback(hObject, eventdata, handles)
% hObject    handle to vy (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.vy,'Value');
set(handles.vy_text,'String',num2str(a));
guidata(hObject, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function vz_Callback(hObject, eventdata, handles)
% hObject    handle to vz (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.vz,'Value');
set(handles.vz_text,'String',num2str(a));
guidata(hObject, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function E_Callback(hObject, eventdata, handles)
% hObject    handle to E (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function Ex_Callback(hObject, eventdata, handles)
% hObject    handle to Ex (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.Ex,'Value');
set(handles.Ex_text,'String',num2str(a));
guidata(hObject, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function Ey_Callback(hObject, eventdata, handles)
% hObject    handle to Ey (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.Ey,'Value');
set(handles.Ey_text,'String',num2str(a));
guidata(hObject, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function Ez_Callback(hObject, eventdata, handles)
% hObject    handle to Ez (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.Ez,'Value');
set(handles.Ez_text,'String',num2str(a));
guidata(hObject, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function Bx_Callback(hObject, eventdata, handles)
% hObject    handle to Bx (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.Bx,'Value');
set(handles.Bx_text,'String',num2str(a));
guidata(hObject, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function By_Callback(hObject, eventdata, handles)
% hObject    handle to By (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.By,'Value');
set(handles.By_text,'String',num2str(a));
guidata(hObject, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function Bz_Callback(hObject, eventdata, handles)
% hObject    handle to Bz (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.Bz,'Value');
set(handles.Bz_text,'String',num2str(a));
guidata(hObject, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end