text:
function varargout = Gain_Finder(varargin)
%GAIN_FINDER M-file for Gain_Finder.fig
%      GAIN_FINDER, by itself, creates a new GAIN_FINDER or raises the existing
%      singleton*.
%
%      H = GAIN_FINDER returns the handle to a new GAIN_FINDER or the handle to
%      the existing singleton*.
%
%      GAIN_FINDER('Property','Value',...) creates a new GAIN_FINDER using the
%      given property value pairs. Unrecognized properties are passed via
%      varargin to Gain_Finder_OpeningFcn.  This calling syntax produces a
%      warning when there is an existing singleton*.
%
%      GAIN_FINDER('CALLBACK') and GAIN_FINDER('CALLBACK',hObject,...) call the
%      local function named CALLBACK in GAIN_FINDER.M with the given input
%      arguments.
%
%      *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 Gain_Finder

% Last Modified by GUIDE v2.5 11-Feb-2010 14:51:57

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @Gain_Finder_OpeningFcn, ...
    'gui_OutputFcn',  @Gain_Finder_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 Gain_Finder is made visible.
function Gain_Finder_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   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = Gain_Finder_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;

set(handles.color_stable,'UserData',2);
set(handles.color_stable_blue,'Checked','on');

set(handles.color_boustable,'UserData',3);
set(handles.color_boustable_green,'Checked','on');

set(handles.color_unstable,'UserData',1);
set(handles.color_unstable_red,'Checked','on');
% --- Executes on selection change in tab_result.
function tab_result_Callback(hObject, eventdata, handles)
% hObject    handle to tab_result (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

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

% Hint: listbox 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 input_gedit_Callback(hObject, eventdata, handles)
% hObject    handle to input_gedit (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 input_gedit as text
%        str2double(get(hObject,'String')) returns contents of input_gedit as a double

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

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

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

% --- Executes during object creation, after setting all properties.
function intv_gedit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to intv_gedit (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 find.
function find_Callback(hObject, eventdata, handles)
% hObject    handle to find (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%============specify color for stable system================
switch get(handles.color_stable,'UserData')
    case 1
        stacol='red';
    case 2
        stacol='blue';
    case 3
        stacol='green';
    case 4
        stacol='yellow';
    case 5
        stacol='gray';
end
%===========================================================

%=========specify color for boundary stable system==========
switch get(handles.color_boustable,'UserData')
    case 1
        boustacol='red';
    case 2
        boustacol='blue';
    case 3
        boustacol='green';
    case 4
        boustacol='yellow';
    case 5
        boustacol='gray';
end
%===========================================================

%===========specify color for unstable system===============
switch get(handles.color_unstable,'UserData')
    case 1
        unstacol='red';
    case 2
        unstacol='blue';
    case 3
        unstacol='green';
    case 4
        unstacol='yellow';
    case 5
        unstacol='gray';
end
%===========================================================

set(handles.tab_result,'String','');

pstr=get(handles.input_gedit,'String');

if isempty(get(handles.input_gedit,'String'))
    errordlg('Equation not found','Equation Error');
    return
elseif isempty(findstr(pstr,'k'))
    errordlg('Variable of gain(k) is''nt exist','Equation Error');
    return
elseif isempty(get(handles.start_gedit,'String'))
    errordlg('Start gain value not found','Input Error');
    return

elseif isempty(get(handles.to_gedit,'String'))
    errordlg('End gain value not found','Input Error');
    return

elseif isempty(get(handles.intv_gedit,'String'))
    errordlg('Interval not found','Input Error');
    return

end

hwait=waitbar(0,'please wait...','CreateCancelBtn','cancel_exe');
setappdata(hwait,'abort',false);
syms k;
psym=sym(pstr);

start=str2double(get(handles.start_gedit,'String'));
interval=str2double(get(handles.intv_gedit,'String'));
to=str2double(get(handles.to_gedit,'String'));

res='';
b=1;

for i=start:interval:to
    if getappdata(hwait,'abort')
        waitbar(to,hwait,'caceling... 100%');
        delete(hwait);
        return;
    end
    pol=subs(psym,k,i);
    rot=fixz(double(solve(poly2strs(pol,'s'))),7);
    [num rep]=repeatv(rot);
    len=length(num);
    rhp=0;
    njw=0;
    nrjw=0;
    cen=0;
    for j=1:len
        if real(num(j))>0
            rhp=rhp+rep(j);
        elseif real(num(j))==0 && imag(num(j))~=0
            njw=njw+rep(j);
            if rep(j)>=2
                nrjw=nrjw+rep(j);
            end
        elseif num(j)==0
            cen=cen+rep(j);
        end
    end
    nrjw=nrjw/2;
    if rhp~=0 || nrjw>=2 || cen~=0
        res{b}=['',unstacol)...
            sprintf('k=%g',i) '      '...
            'system is unstable' ''];
        b=b+1;
    elseif rhp==0 && nrjw==0 && cen==0 && njw~=0
        res{b}=['',boustacol)...
            sprintf('k=%g',i) '      '...
            'system is boundary stable' ''];
        b=b+1;
    else
        res{b}=['',stacol)...
            sprintf('k=%g',i) '      '...
            'system is stable' ''];
        b=b+1;
    end

    if i>0
        waitbar(i/to,hwait,sprintf('please wait... %d%%',round((i/to)*100)));
    end
end
res{b}=' ';
set(handles.tab_result,'Enable','inactive');
set(handles.tab_result,'String',res);
set(handles.tab_result,'Value',b);
delete(hwait);

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

% --------------------------------------------------------------------
function color_default_Callback(hObject, eventdata, handles)
% hObject    handle to color_default (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_stable_red,'Checked','off');
set(handles.color_stable_blue,'Checked','off');
set(handles.color_stable_green,'Checked','off');
set(handles.color_stable_yellow,'Checked','off');
set(handles.color_stable_gray,'Checked','off');

set(handles.color_boustable_red,'Checked','off');
set(handles.color_boustable_blue,'Checked','off');
set(handles.color_boustable_green,'Checked','off');
set(handles.color_boustable_yellow,'Checked','off');
set(handles.color_boustable_gray,'Checked','off');

set(handles.color_unstable_red,'Checked','off');
set(handles.color_unstable_blue,'Checked','off');
set(handles.color_unstable_green,'Checked','off');
set(handles.color_unstable_yellow,'Checked','off');
set(handles.color_unstable_gray,'Checked','off');

set(handles.color_stable,'UserData',2);
set(handles.color_stable_blue,'Checked','on');

set(handles.color_boustable,'UserData',3);
set(handles.color_boustable_green,'Checked','on');

set(handles.color_unstable,'UserData',1);
set(handles.color_unstable_red,'Checked','on');
% --------------------------------------------------------------------
function color_stable_Callback(hObject, eventdata, handles)
% hObject    handle to color_stable (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

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

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

% --------------------------------------------------------------------
function color_stable_red_Callback(hObject, eventdata, handles)
% hObject    handle to color_stable_red (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_stable_red,'Checked','off');
set(handles.color_stable_blue,'Checked','off');
set(handles.color_stable_green,'Checked','off');
set(handles.color_stable_yellow,'Checked','off');
set(handles.color_stable_gray,'Checked','off');

set(handles.color_stable,'UserData',1);
set(handles.color_stable_red,'Checked','on');

% --------------------------------------------------------------------
function color_stable_blue_Callback(hObject, eventdata, handles)
% hObject    handle to color_stable_blue (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_stable_red,'Checked','off');
set(handles.color_stable_blue,'Checked','off');
set(handles.color_stable_green,'Checked','off');
set(handles.color_stable_yellow,'Checked','off');
set(handles.color_stable_gray,'Checked','off');

set(handles.color_stable,'UserData',2);
set(handles.color_stable_blue,'Checked','on');

% --------------------------------------------------------------------
function color_stable_green_Callback(hObject, eventdata, handles)
% hObject    handle to color_stable_green (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_stable_red,'Checked','off');
set(handles.color_stable_blue,'Checked','off');
set(handles.color_stable_green,'Checked','off');
set(handles.color_stable_yellow,'Checked','off');
set(handles.color_stable_gray,'Checked','off');

set(handles.color_stable,'UserData',3);
set(handles.color_stable_green,'Checked','on');

% --------------------------------------------------------------------
function color_stable_yellow_Callback(hObject, eventdata, handles)
% hObject    handle to color_stable_yellow (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_stable_red,'Checked','off');
set(handles.color_stable_blue,'Checked','off');
set(handles.color_stable_green,'Checked','off');
set(handles.color_stable_yellow,'Checked','off');
set(handles.color_stable_gray,'Checked','off');

set(handles.color_stable,'UserData',4);
set(handles.color_stable_yellow,'Checked','on');

% --------------------------------------------------------------------
function color_stable_gray_Callback(hObject, eventdata, handles)
% hObject    handle to color_stable_gray (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_stable_red,'Checked','off');
set(handles.color_stable_blue,'Checked','off');
set(handles.color_stable_green,'Checked','off');
set(handles.color_stable_yellow,'Checked','off');
set(handles.color_stable_gray,'Checked','off');

set(handles.color_stable,'UserData',5);
set(handles.color_stable_gray,'Checked','on');

% --------------------------------------------------------------------
function color_boustable_red_Callback(hObject, eventdata, handles)
% hObject    handle to color_boustable_red (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_boustable_red,'Checked','off');
set(handles.color_boustable_blue,'Checked','off');
set(handles.color_boustable_green,'Checked','off');
set(handles.color_boustable_yellow,'Checked','off');
set(handles.color_boustable_gray,'Checked','off');

set(handles.color_boustable,'UserData',1);
set(handles.color_boustable_red,'Checked','on');

% --------------------------------------------------------------------
function color_boustable_blue_Callback(hObject, eventdata, handles)
% hObject    handle to color_boustable_blue (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_boustable_red,'Checked','off');
set(handles.color_boustable_blue,'Checked','off');
set(handles.color_boustable_green,'Checked','off');
set(handles.color_boustable_yellow,'Checked','off');
set(handles.color_boustable_gray,'Checked','off');

set(handles.color_boustable,'UserData',2);
set(handles.color_boustable_blue,'Checked','on');

% --------------------------------------------------------------------
function color_boustable_green_Callback(hObject, eventdata, handles)
% hObject    handle to color_boustable_green (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_boustable_red,'Checked','off');
set(handles.color_boustable_blue,'Checked','off');
set(handles.color_boustable_green,'Checked','off');
set(handles.color_boustable_yellow,'Checked','off');
set(handles.color_boustable_gray,'Checked','off');

set(handles.color_boustable,'UserData',3);
set(handles.color_boustable_green,'Checked','on');

% --------------------------------------------------------------------
function color_boustable_yellow_Callback(hObject, eventdata, handles)
% hObject    handle to color_boustable_yellow (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_boustable_red,'Checked','off');
set(handles.color_boustable_blue,'Checked','off');
set(handles.color_boustable_green,'Checked','off');
set(handles.color_boustable_yellow,'Checked','off');
set(handles.color_boustable_gray,'Checked','off');

set(handles.color_boustable,'UserData',4);
set(handles.color_boustable_yellow,'Checked','on');

% --------------------------------------------------------------------
function color_boustable_gray_Callback(hObject, eventdata, handles)
% hObject    handle to color_boustable_gray (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_boustable_red,'Checked','off');
set(handles.color_boustable_blue,'Checked','off');
set(handles.color_boustable_green,'Checked','off');
set(handles.color_boustable_yellow,'Checked','off');
set(handles.color_boustable_gray,'Checked','off');

set(handles.color_boustable,'UserData',5);
set(handles.color_boustable_gray,'Checked','on');

% --------------------------------------------------------------------
function color_unstable_red_Callback(hObject, eventdata, handles)
% hObject    handle to color_unstable_red (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_unstable_red,'Checked','off');
set(handles.color_unstable_blue,'Checked','off');
set(handles.color_unstable_green,'Checked','off');
set(handles.color_unstable_yellow,'Checked','off');
set(handles.color_unstable_gray,'Checked','off');

set(handles.color_unstable,'UserData',1);
set(handles.color_unstable_red,'Checked','on');

% --------------------------------------------------------------------
function color_unstable_blue_Callback(hObject, eventdata, handles)
% hObject    handle to color_unstable_blue (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_unstable_red,'Checked','off');
set(handles.color_unstable_blue,'Checked','off');
set(handles.color_unstable_green,'Checked','off');
set(handles.color_unstable_yellow,'Checked','off');
set(handles.color_unstable_gray,'Checked','off');

set(handles.color_unstable,'UserData',2);
set(handles.color_unstable_blue,'Checked','on');

% --------------------------------------------------------------------
function color_unstable_green_Callback(hObject, eventdata, handles)
% hObject    handle to color_unstable_green (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_unstable_red,'Checked','off');
set(handles.color_unstable_blue,'Checked','off');
set(handles.color_unstable_green,'Checked','off');
set(handles.color_unstable_yellow,'Checked','off');
set(handles.color_unstable_gray,'Checked','off');

set(handles.color_unstable,'UserData',3);
set(handles.color_unstable_green,'Checked','on');

% --------------------------------------------------------------------
function color_unstable_yellow_Callback(hObject, eventdata, handles)
% hObject    handle to color_unstable_yellow (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_unstable_red,'Checked','off');
set(handles.color_unstable_blue,'Checked','off');
set(handles.color_unstable_green,'Checked','off');
set(handles.color_unstable_yellow,'Checked','off');
set(handles.color_unstable_gray,'Checked','off');

set(handles.color_unstable,'UserData',4);
set(handles.color_unstable_yellow,'Checked','on');

% --------------------------------------------------------------------
function color_unstable_gray_Callback(hObject, eventdata, handles)
% hObject    handle to color_unstable_gray (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.color_unstable_red,'Checked','off');
set(handles.color_unstable_blue,'Checked','off');
set(handles.color_unstable_green,'Checked','off');
set(handles.color_unstable_yellow,'Checked','off');
set(handles.color_unstable_gray,'Checked','off');

set(handles.color_unstable,'UserData',5);
set(handles.color_unstable_gray,'Checked','on');

% --------------------------------------------------------------------
function help_help_Callback(hObject, eventdata, handles)
% hObject    handle to help_help (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
hlpl1=sprintf('you can input Equation only poly(Coefficient of Equation(s)=0)');
hlpl2=sprintf('\n with variable ''k''(Gain)');
hlpl3=sprintf('\n---for example : [1 3 3 2 k]--- or [1 3*k 2 1 2*k 1]---');
hlpl4=sprintf('\ncaution : variable of Gain is lowercase(k) & not uppercase(K)');
hlpl5=sprintf('\nif input(poly equation) haven''t variable of Gain(k) then');
hlpl6=sprintf('\ngui give error message');
hlpl7=sprintf('\ndecrease interval==increase precision==long time process');
hlpt=strvcat(hlpl1,hlpl2,hlpl3,hlpl4,hlpl5,hlpl6,hlpl7);
helpdlg(hlpt,'Help:Input');

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

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

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

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

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

% --------------------------------------------------------------------
function help_demo_ex1_step1_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex1_step1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 3 3 2 k]');
set(handles.start_gedit,'String','-10');
set(handles.to_gedit,'String','10');
set(handles.intv_gedit,'String','1');

% --------------------------------------------------------------------
function help_demo_ex1_step2_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex1_step2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 3 3 2 k]');
set(handles.start_gedit,'String','0');
set(handles.to_gedit,'String','2');
set(handles.intv_gedit,'String','0.01');

% --------------------------------------------------------------------
function help_demo_ex2_step1_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex2_step1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 3*k 6 4 1]');
set(handles.start_gedit,'String','-10');
set(handles.to_gedit,'String','10');
set(handles.intv_gedit,'String','1');

% --------------------------------------------------------------------
function help_demo_ex2_step2_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex2_step2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 3*k 6 4 1]');
set(handles.start_gedit,'String','0');
set(handles.to_gedit,'String','8');
set(handles.intv_gedit,'String','0.1');

% --------------------------------------------------------------------
function help_demo_ex3_step1_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex3_step1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 0 5 0 k]');
set(handles.start_gedit,'String','-10');
set(handles.to_gedit,'String','10');
set(handles.intv_gedit,'String','1');

% --------------------------------------------------------------------
function help_demo_ex3_step2_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex3_step2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 0 5 0 k]');
set(handles.start_gedit,'String','0');
set(handles.to_gedit,'String','7');
set(handles.intv_gedit,'String','0.1');

% --------------------------------------------------------------------
function help_demo_ex4_step1_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex4_step1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 0 6 0 9 0 k]');
set(handles.start_gedit,'String','-10');
set(handles.to_gedit,'String','10');
set(handles.intv_gedit,'String','1');

% --------------------------------------------------------------------
function help_demo_ex4_step2_Callback(hObject, eventdata, handles)
% hObject    handle to help_demo_ex4_step2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String','[1 0 6 0 9 0 k]');
set(handles.start_gedit,'String','0');
set(handles.to_gedit,'String','4');
set(handles.intv_gedit,'String','0.1');

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

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

% --------------------------------------------------------------------
function cgmenuin_copy_Callback(hObject, eventdata, handles)
% hObject    handle to cgmenuin_copy (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
clipboard('copy',get(handles.input_gedit,'String'));

% --------------------------------------------------------------------
function cgmenuin_paste_Callback(hObject, eventdata, handles)
% hObject    handle to cgmenuin_paste (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.input_gedit,'String',clipboard('paste'));


text:
function y = log_sum_exp( x, dim )

%LOG_SUM_EXP    log(sum(exp(x))).
%   LOG_SUM_EXP(X) = LOG(SUM(EXP(X)).
%
%   When used in a CVX model, LOG_SUM_EXP(X) causes CVX's successive
%   approximation method to be invoked, producing results exact to within
%   the tolerance of the solver. This is in contrast to LOGSUMEXP_SDP,
%   which uses a single SDP-representable global approximation.
%
%   If X is a matrix, LOGSUMEXP_SDP(X) will perform its computations
%   along each column of X. If X is an N-D array, LOGSUMEXP_SDP(X)
%   will perform its computations along the first dimension of size
%   other than 1. LOGSUMEXP_SDP(X,DIM) will perform its computations
%   along dimension DIM.
%
%   Disciplined convex programming information:
%       LOG_SUM_EXP(X) is convex and nondecreasing in X; therefore, X
%       must be convex (or affine).

narginchk(1,2);
if ~isreal( x ),
    error( 'Argument must be real.' );
end
y = exp( x );
if nargin == 1,
    y = sum( y );
else
    y = sum( y, dim );
end
y = log( y );

% Copyright 2005-2016 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.

author: cvxr

repo: CVX

save_path: github-repos/MATLAB/cvxr-CVX


text:
function [gradient, delta] = gradchek(w, func, grad, varargin)
%GRADCHEK Checks a user-defined gradient function using finite differences.
%
%	Description
%	This function is intended as a utility for other netlab functions
%	(particularly optimisation functions) to use.  It enables the user to
%	check whether a gradient calculation has been correctly implmented
%	for a given function. GRADCHEK(W, FUNC, GRAD) checks how accurate the
%	gradient  GRAD of a function FUNC is at a parameter vector X.   A
%	central difference formula with step size 1.0e-6 is used, and the
%	results for both gradient function and finite difference
%	approximation are printed. The optional return value GRADIENT is the
%	gradient calculated using the function GRAD and the return value
%	DELTA is the difference between the functional and finite difference
%	methods of calculating the graident.
%
%	GRADCHEK(X, FUNC, GRAD, P1, P2, ...) allows additional arguments to
%	be passed to FUNC and GRAD.
%
%	See also
%	CONJGRAD, GRADDESC, HMC, OLGD, QUASINEW, SCG
%

%	Copyright (c) Ian T Nabney (1996-2001)

% Reasonable value for step size
epsilon = 1.0e-6;

func = fcnchk(func, length(varargin));
grad = fcnchk(grad, length(varargin));

% Treat
nparams = length(w);
deltaf = zeros(1, nparams);
step = zeros(1, nparams);
for i = 1:nparams
  % Move a small way in the ith coordinate of w
  step(i) = 1.0;
  fplus  = feval('linef', epsilon, func, w, step, varargin{:});
  fminus = feval('linef', -epsilon, func, w, step, varargin{:});
  % Use central difference formula for approximation
  deltaf(i) = 0.5*(fplus - fminus)/epsilon;
  step(i) = 0.0;
end
gradient = feval(grad, w, varargin{:});
fprintf(1, 'Checking gradient ...\n\n');
delta = gradient - deltaf;
fprintf(1, '   analytic   diffs     delta\n\n');
disp([gradient', deltaf', delta'])

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
 function ir_usage(mfile_name)
%function ir_usage(mfile_name)
%|
%| Show "usage" of a given mfile in a screen-friendly way then fail with error.
%| If mfile_name is not provided, then infer from "caller_name.m"
%|
%| 2016-08-07 Jeff Fessler, University of Michigan

if nargin < 1
	mfile_name = caller_name;
	if isempty(mfile_name)
		help(mfilename), error(mfilename)
		return
	end
end

more on
help(mfile_name)
more off

%evalin('caller', 'error(''test'')')
error([mfile_name ' usage'])
%fail(mfile_name)

author: JeffFessler

repo: mirt

save_path: github-repos/MATLAB/JeffFessler-mirt


text:
function [mi3] = km32mi3(km3)
% Convert volume from cubic kilometers to cubic miles.
% Chad Greene 2012
mi3 = km3*0.23991275858;

author: Sable

repo: mcbench-benchmarks


text:
% longitudinally_register_scans_multi_series.m
% dirName = 'L:\Aditya\SPIdemoProject\CERRfiles';
% filesC = {'05_19_2010.mat', '08_25_2010.mat', '02_09_2011.mat', '06_04_2011.mat',...
% '11_26_2011.mat', '03_17_2012.mat', '07_21_2012.mat'};

%dirName = '/mnt/RadShared2/Aditya/cerr_data';
dirS = dir(dirName);
dirS(1:2) = [];
fileNamesC = {dirS.name};

% Get accession numbers, dates, seried id's of all files
[mrnC,remC] = strtok(fileNamesC,'~');
[accessionC,remC] = strtok(remC,'~');
[seriesC,remC] = strtok(remC,'~');
[dateC,remC] = strtok(remC,'~');

% Sort filesC by exam dates
[~,indSortV] = sort(datenum(dateC,'yyyymmdd'));
dateAllV = datenum(dateC,'yyyymmdd');
dateAllV = dateAllV(indSortV);
fileNamesC = fileNamesC(indSortV);
accessionC = accessionC(indSortV);
seriesC = seriesC(indSortV);
dateC = dateC(indSortV);

% Group Scans by accession number
[dateV, indV, uniqueIndexV] = unique(dateAllV);
dateC = dateC(indV);

for i=1:length(dateV)
    scanLesions{i} = [];
    scanXDims{i} = [];
    scanYDims{i} = [];
    scanZDims{i} = [];
    scanFileNames{i} = [];
end

% Find and Record Lesions, scan dates and scan uids on all Scans
for i=1:length(fileNamesC)
    filename = fullfile(dirName,fileNamesC{i});

    planC = loadPlanC(filename,tempdir);
    [planC, isUIDCreated] = updatePlanFields(planC);
    planC = quality_assure_planC(filename, planC, isUIDCreated);
    indexS = planC{end};
    seriesDescription = planC{indexS.scan}.scanInfo(1).DICOMHeaders.SeriesDescription;
    if ~strncmp('CORONAL', seriesDescription,7) && ...
            ~strncmp('SAGITTAL', seriesDescription,8)
        scanNum = 1;
        lesionS = findLesions(scanNum,planC);
        scanLesions{uniqueIndexV(i)} = [scanLesions{uniqueIndexV(i)} lesionS];
        planC = segmentLesions(planC,lesionS);
        planC = save_planC(planC,[],'passed',filename);
        scanFileNames{uniqueIndexV(i)} = [scanFileNames{uniqueIndexV(i)}, {filename}];
        [xV,yV,zV] = getScanXYZVals(planC{indexS.scan},planC);
        scanXDims{uniqueIndexV(i)} = [scanXDims{uniqueIndexV(i)}; min(xV) max(xV)];
        scanYDims{uniqueIndexV(i)} = [scanYDims{uniqueIndexV(i)}; min(yV) max(yV)];
        scanZDims{uniqueIndexV(i)} = [scanZDims{uniqueIndexV(i)}; min(zV) max(zV)];
        filename
        seriesDescription
    else
        filename
        seriesDescription
    end
    scanNum = 1;
    scanDatesV(i) = datenum(planC{indexS.scan}.scanInfo(1).scanDate,'yyyymmdd');
    scanUIDc{i} = planC{indexS.scan}.scanUID;
end

% ---- Code to filter out same annotations. Bugy... use volume-matching in future.
% for scanNum = 1:length(scanLesions)
%     currentScanLesions = scanLesions{scanNum};
%     % Find lesions that are close to each other and combine them as one
%     hausdorffDistM = [];
%     meanDistM = [];
%     for lesionNum = 1:length(currentScanLesions)
%         xV = currentScanLesions(lesionNum).xV;
%         yV = currentScanLesions(lesionNum).yV;
%         zV = currentScanLesions(lesionNum).zV;
%         xyzLesion = [xV yV zV];
%         for remLes = 1:length(currentScanLesions)
%             xRemV = currentScanLesions(remLes).xV;
%             yRemV = currentScanLesions(remLes).yV;
%             zRemV = currentScanLesions(remLes).zV;
%             xyzMatchedLesion = [xRemV yRemV zRemV];
%             hausdorffDistC{scanNum}(lesionNum,remLes) = hausdorff(xyzLesion,xyzMatchedLesion);
%             meanDistC{scanNum}(lesionNum,remLes) = sqrt(sum((mean(xyzLesion)-mean(xyzMatchedLesion)).^2));
%         end
%     end
% end
%
% for scanNum = 1:length(scanLesions)
%     maskM = hausdorffDistC{scanNum} < 3 | meanDistC{scanNum} < 3;
%     lesionsToDeleteV = [];
%     for lesionNum = 1:length(scanLesions{scanNum})
%         indSameLesionV = find(maskM(lesionNum,:));
%         if length(indSameLesionV) > 1
%             [~,indToKeep] = min(sum(hausdorffDistC{scanNum}(indSameLesionV,indSameLesionV)));
%             lesionsToDeleteV = [lesionsToDeleteV setdiff(indSameLesionV,indSameLesionV(indToKeep))];
%         end
%     end
%     lesionsToDeleteV = unique(lesionsToDeleteV);
%     scanLesions{scanNum}(lesionsToDeleteV) = [];
% end

% Figure out the file that needs to be used for registration. Assume there
% exists a file that encompasses all lesions. e.g. whole BODY scan
for i=1:length(dateV)
    minXval = min(scanXDims{i}(:,1));
    minLocX = find(abs(scanXDims{i}(:,1)-minXval) < 0.005);
    minYval = min(scanYDims{i}(:,1));
    minLocY = find(abs(scanYDims{i}(:,1)-minYval) < 0.005);
    minZval = min(scanZDims{i}(:,1));
    minLocZ = find(abs(scanZDims{i}(:,1)-minZval) < 0.005);
    maxXval = max(scanXDims{i}(:,2));
    maxLocX = find(abs(scanXDims{i}(:,2)-maxXval) < 0.005);
    maxYval = max(scanYDims{i}(:,2));
    maxLocY = find(abs(scanYDims{i}(:,2)-maxYval) < 0.005);
    maxZval = max(scanZDims{i}(:,2));
    maxLocZ = find(abs(scanZDims{i}(:,2)-maxZval) < 0.005);
    fileIndex = intersect(intersect(intersect(intersect(intersect(minLocX,minLocY),minLocZ),maxLocX),maxLocY),maxLocZ);
    if ~isempty(fileIndex)
        filesC{i} = scanFileNames{i}{fileIndex};
    else
        filesC{i} = [];
    end
end

% Register scans
for i=1:length(filesC)-1
%     filename1 = fullfile(dirName,filesC{i});
%     filename2 = fullfile(dirName,filesC{i+1});
    filename1 = filesC{i};
    filename2 = filesC{i+1};
    scan1PlanC = loadPlanC(filename1,tempdir);
    indexSscan1 = scan1PlanC{end};
    scan1PlanC{indexSscan1.deform}(1:end) = [];
    scan2PlanC = loadPlanC(filename2,tempdir);
    indexSscan2 = scan2PlanC{end};
    scan2PlanC{indexSscan2.deform}(1:end) = [];
    % Create annotations mask from all scans at base date.
    baseMask3M = [];
    filesToCopy = find(~ismember(scanFileNames{i},filename1));
    scan1PlanC = copyStructsFromFilesToPlanC(scanFileNames{i}(filesToCopy), scan1PlanC);
    annotROIIndV = strncmp('Annotation ROI',...
        {scan1PlanC{indexSscan1.structures}.structureName},length('Annotation ROI'));
    annotStrV = find(annotROIIndV);
    if ~isempty(annotStrV)
        baseMask3M = getUniformStr(annotStrV,scan1PlanC);
    end

    % Create annotations mask from all scans at follow-up date.
    movMask3M = [];
    filesToCopy = find(~ismember(scanFileNames{i+1},filename2));
    scan2PlanC = copyStructsFromFilesToPlanC(scanFileNames{i+1}(filesToCopy), scan2PlanC);
    annotROIIndV = strncmp('Annotation ROI',...
        {scan2PlanC{indexSscan2.structures}.structureName},length('Annotation ROI'));
    annotStrV = find(annotROIIndV);
    if ~isempty(annotStrV)
        movMask3M = getUniformStr(annotStrV,scan2PlanC);
    end

    baseScanNum = 1;
    movScanNum = 1;
    algorithm = 'BSPLINE PLASTIMATCH';
    threshold_bone = 100;
    [scan1PlanC, scan2PlanC] = register_scans(scan1PlanC, scan2PlanC, baseScanNum, movScanNum, algorithm, baseMask3M, movMask3M, threshold_bone);
    scan1PlanC = save_planC(scan1PlanC,[],'passed',filename1);
    scan2PlanC = save_planC(scan2PlanC,[],'passed',filename2);
    clear scan1PlanC scan2PlanC
end

% Match Lesions
for i=1:length(filesC)-1
%     filename1 = fullfile(dirName,filesC{i});
%     filename2 = fullfile(dirName,filesC{i+1});
    filename1 = filesC{i};
    filename2 = filesC{i+1};
    scan1PlanC = loadPlanC(filename1,tempdir);
    scan2PlanC = loadPlanC(filename2,tempdir);
    %scan1PlanC = updatePlanFields(scan1PlanC);
    %scan2PlanC = updatePlanFields(scan2PlanC);
    % Quality assure
    %scan1PlanC = quality_assure_planC(filename1, scan1PlanC);
    %scan2PlanC = quality_assure_planC(filename2, scan2PlanC);

    baseScanNum = 1;
    movScanNum = 1;
    scan1LesionS = scanLesions{i}; %findLesions(baseScanNum,scan1PlanC);
    scan2LesionS = scanLesions{i+1}; %findLesions(movScanNum,scan2PlanC);
    try
        [lesionMapping{i}, scanLesions{i+1}] = matchLesions(scan1LesionS, scan2LesionS, baseScanNum, movScanNum, scan1PlanC, scan2PlanC);
    catch
        disp('error')
    end
    clear scan1PlanC scan2PlanC
end

lesionMappingOriginal = lesionMapping;

for scanNum = 1:length(scanLesions)
    lesionsToUse{scanNum} = 1:length(scanLesions{scanNum});
end

% % Find lesions that map to same lesion on the next scan and decide which one to retain
% for scanNum = 1:length(lesionMapping)
%     lesionMap = lesionMapping{scanNum};
%     lesionsToUse{scanNum} = 1:size(lesionMap,1);
%     nextLesionIndicesV = [];
%     for lesionNum = 1:size(lesionMap,1)
%         %if ~isnan(lesionMap(lesionNum,2))
%         if ~ismember(lesionNum,nextLesionIndicesV)
%             nextLesionIndices = find(lesionMap(:,2) == lesionMap(lesionNum,2));
%             nextLesionIndicesV = [nextLesionIndicesV nextLesionIndices'];
%             if length(nextLesionIndices) > 1
%                 [~,indToKeep] = min(lesionMap(nextLesionIndices,3));
%                 indToDelete = setdiff(nextLesionIndices,nextLesionIndices(indToKeep));
%                 %lesionMapping{scanNum}(indToDelete,:) = [];
%                 %scanLesions{scanNum}(indToDelete) = [];
%                 lesionsToUse{scanNum}(indToDelete) = [];
%             end
%         end
%     end
% end
% lesionsToUse{length(scanLesions)} = 1:length(scanLesions{end});

% Track Lesions
lesionStory = {}; % (indexed by lesionNum): Start Scan, End Scan, lesion indices on scans from start:end
lesionsCountedFor = {}; % (indexed by ScanNum): LesionNums
for lesionNum=1:length(scanLesions)
    lesionsCountedFor{lesionNum} = [];
end
for scanNum = 1:length(scanLesions)
    currentScanLesions = scanLesions{scanNum};
    lesionsToIgnore = lesionsCountedFor{scanNum};
    for lesionNum = lesionsToUse{scanNum}
        if ismember(lesionNum, lesionsToIgnore)
            continue;
        end
        lesionsCountedFor{scanNum} = lesionNum;
        lesionHistoryV = lesionNum;
        currentLesionNum = lesionNum;
        endScanNum = scanNum;
        for longitScanNum = scanNum:length(scanLesions)-1
            currentLesionmap = lesionMapping{longitScanNum};
            currentLesionNum = currentLesionmap(currentLesionNum,2);
            if isnan(currentLesionNum)
                break;
            end
            endScanNum = longitScanNum + 1;
            lesionsCountedFor{endScanNum} = [lesionsCountedFor{endScanNum} currentLesionNum];
            lesionHistoryV = [lesionHistoryV currentLesionNum];
        end
        lesionStory{end+1} = [scanNum endScanNum lesionHistoryV];
    end
end

save('local_vars.mat','lesionStory','scanLesions','scanUIDc','fileNamesC','dateV','dateAllV')

return;

% Generate Longitudinal Images for lesions
absolutePathForImageFiles = '/mnt/RadShared2/Aditya/SPIdemoProject';
for lesionNum = 1:length(lesionStory)
    currentLesionStory = lesionStory{lesionNum};
    startScan = currentLesionStory(1);
    endScan = currentLesionStory(2);
    longitLesionNumsV = currentLesionStory(3:end);
    scanCount = 1;
    currentLesionLongitLenV = [];
    for scanNum = startScan:endScan
        currentLesionNum = longitLesionNumsV(scanCount);
        xV = scanLesions{scanNum}(currentLesionNum).xV;
        yV = scanLesions{scanNum}(currentLesionNum).yV;
        zV = scanLesions{scanNum}(currentLesionNum).zV;
        if isempty(scanLesions{scanNum}(currentLesionNum).assocAnnotUID)
            annotColor = 'y';
        else
            annotColor = 'r';
        end
        [~,fileIndex] = ismember(scanLesions{scanNum}(currentLesionNum).assocScanUID,scanUIDc);
        lenV = [];
        for segNum = 1:2:length(xV)
            x1 = xV(segNum);
            y1 = yV(segNum);
            z1 = zV(segNum);
            x2 = xV(segNum+1);
            y2 = yV(segNum+1);
            z2 = zV(segNum+1);
            lenV = [lenV sqrt((x1-x2)^2+(y1-y2)^2)];
        end
        currentLesionLongitLenV = [currentLesionLongitLenV max(lenV)];

        % Load scan, go to slice and take snapshot of annotation
        %cerrFileName = fullfile(dirName,filesC{fileIndex});
        cerrFileName = fullfile(dirName,fileNamesC{fileIndex});
        write_annotation_images_to_disk(absolutePathForImageFiles,cerrFileName,scanNum,[xV(:) yV(:) zV(:)],lesionNum,annotColor)

        scanCount = scanCount + 1;
    end
    longitLen{lesionNum} = currentLesionLongitLenV;
end

% Generate Report for each lesion
optS.format = 'html';
% optS.figureSnapMethod = 'getframe';
optS.showCode = false;
optS.codeToEvaluate = '';
optS.outputDir = fullfile(absolutePathForImageFiles,'report');
optS.maxHeight = 300;
optS.maxWidth = 300;
file = publish('publish_results.m',optS);

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
% FIT_CUBIC_BEZIER Fit a cubic bezier spline (G1 continuous) to an ordered list
% of input points in any dimension, according to "An algorithm for automatically
% fitting digitized curves" [Schneider 1990].
%
%  Inputs:
%    d  #d by dim list of points along a curve to be fit with a cubic bezier
%      spline (should probably be roughly uniformly spaced). If d(0)==d(end),
%      then will treat as a closed curve.
%    error  maximum squared distance allowed
%  Output:
%    cubics #cubics list of 4 by dim lists of cubic control points
%

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
%% show_3dtensors(T1,...,Tn)
%
function show_3dtensors(varargin)
  n = nargin;
  % display(['Number of tensors: ' num2str(n)]);
  V = varargin{1};
  for i = 1:size(V,3)
    for j = 1:n
      T = varargin{j};
      if(isa(T,'tensor'))
        T = double(T);
      end
      switch(n)
        case 1
          imshow(T(:,:,i),[],'InitialMagnification','fit');
        case {2,3}
          subplot(1,n,j), imshow(T(:,:,i),[],'InitialMagnification','fit');
        case 4
          subplot(2,2,j), imshow(T(:,:,i),[],'InitialMagnification','fit');
        case {5,6}
          subplot(2,3,j), imshow(T(:,:,i),[],'InitialMagnification','fit');
        case {8}
          subplot(2,4,j), imshow(T(:,:,i),[],'InitialMagnification','fit');
        case {7,9}
          subplot(3,3,j), imshow(T(:,:,i),[],'InitialMagnification','fit');
        otherwise
          error('Not supported operation!');
      end
    end
    pause(0.01);
  end
end

author: andrewssobral

repo: lrslibrary


text:
% teststat - EEGLAB statistical testing function
%
% Statistics are critical for inference testing in Science. It is thus
% primordial to make sure than all the statistics implemented are
% robust and at least bug free. Statistical function using complex
% formulas are inherently prone to bugs. EEGLAB functions are all the
% more prone to bugs given that they only use complex Matlab code to
% avoid loops and speed up computation.
%
% This test function does not guarantee that EEGLAB statistical functions
% are bug free. It does assure though that bugs are unlikely and minor
% if they are present.
%
% This function test 3 things.
%
% * First, it checks that for vector inputs the EEGLAB functions return
%   the same output as other reference functions from the Matlab statistical
%   toolbox or from other packages tested against the SPSS software for
%   repeated measure ANOVA (rm_anova2 function).
%
% * Second, it checks that array inputs with different number of dimensions
%   (from 1 to 3) the EEGLAB function return the same output.
%
% * Third, it checks that the permutation and bootstrap methods shuffle
%   the data properly by running multiple tests.

% Copyright (C) 2006 Arnaud Delorme
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

function teststat;

% testing paired t-test
% ---------------------
a = { rand(1,10) rand(1,10)+0.5 };
[t df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[h p tmp stats] = ttest(a{1}, a{2});
fprintf('Statistics paired statcond    t-value %2.2f df=%d p=%0.4f\n', t, df, pvals);
fprintf('Statistics paired ttest func. t-value %2.2f df=%d p=%0.4f\n', stats.tstat, stats.df, p);
assertsame([t stats.tstat], [df stats.df], [pvals p]);
disp('--------------------');

% testing unpaired t-test
% -----------------------
[t df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[h p tmp stats] = ttest2(a{1}, a{2});
fprintf('Statistics paired statcond     t-value %2.2f df=%d p=%0.4f\n', t, df, pvals);
fprintf('Statistics paired ttest2 func. t-value %2.2f df=%d p=%0.4f\n', stats.tstat, stats.df, p);
assertsame([t stats.tstat], [df stats.df], [pvals p]);
disp('--------------------');

% testing paired 1-way ANOVA
% --------------------------
a = { rand(1,10) rand(1,10) rand(1,10)+0.2; rand(1,10) rand(1,10)+0.2 rand(1,10) };
[F df pvals surog] = statcond(a(1,:), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
z = zeros(10,1); o = ones(10,1); t = ones(10,1)*2;
stats = rm_anova2(  [ a{1,1}';a{1,2}';a{1,3}'], repmat([1:10]', [3 1]), [o;o;o], [z;o;t], {'a','b'});
fprintf('Statistics 1-way paired statcond        F-value %2.2f df1=%d df2=%d p=%0.4f\n', F, df(1), df(2), pvals);
fprintf('Statistics 1-way paired rm_avova2 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{3,5}, stats{3,3}, stats{6,3}, stats{3,6});
assertsame([F stats{3,5}], [df(1) stats{3,3}], [df(2) stats{6,3}], [pvals stats{3,6}]);
disp('--------------------');

% testing paired 2-way ANOVA
% --------------------------
[F df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
z = zeros(10,1); o = ones(10,1); t = ones(10,1)*2;
stats = rm_anova2(  [ a{1,1}';a{1,2}';a{1,3}';a{2,1}';a{2,2}';a{2,3}' ], ...
            repmat([1:10]', [6 1]), [o;o;o;z;z;z], [z;o;t;z;o;t], {'a','b'});
fprintf('Statistics 2-way paired statcond        F-value %2.2f df1=%d df2=%d p=%0.4f\n', F{3}, df{3}(1), df{3}(2), pvals{3});
fprintf('Statistics 2-way paired rm_avova2 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{4,5}, stats{4,3}, stats{7,3}, stats{4,6});
assertsame([F{3} stats{4,5}], [df{3}(1) stats{4,3}], [df{3}(2) stats{7,3}], [pvals{3} stats{4,6}]);
disp('--------------------');

% testing 1-way unpaired ANOVA
% ----------------------------
[F df pvals surog] = statcond(a(1,:), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[p stats] = anova1( [ a{1,1}' a{1,2}' a{1,3}' ],{}, 'off');
fprintf('Statistics 1-way unpaired statcond     F-value %2.2f df1=%d df2=%d p=%0.4f\n', F, df(1), df(2), pvals);
fprintf('Statistics 1-way unpaired anova1 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{2,5}, stats{2,3}, stats{3,3}, stats{2,6});
assertsame([F stats{2,5}], [df(1) stats{2,3}], [df(2) stats{3,3}], [pvals stats{2,6}]);
disp('--------------------');

% testing 2-way unpaired ANOVA
% ----------------------------
[F df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[p stats] = anova2( [ a{1,1}' a{1,2}' a{1,3}'; a{2,1}' a{2,2}' a{2,3}' ], 10, 'off');
fprintf('Statistics 2-way paired statcond       F-value %2.2f df1=%d df2=%d p=%0.4f\n', F{3}, df{3}(1), df{3}(2), pvals{3});
fprintf('Statistics 1-way unpaired anova2 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{4,5}, stats{4,3}, stats{5,3}, stats{4,6});
assertsame([F{3} stats{4,5}], [df{3}(1) stats{4,3}], [df{3}(2) stats{5,3}], [pvals{3} stats{4,6}]);
disp('--------------------');

% testing different dimensions in statcond
% ----------------------------------------
a = { rand(1,10)      rand(1,10)+0.5      rand(1,10)};
b = { rand(10,10)     rand(10,10)+0.5     rand(10,10)};     b{1}(4,:)     = a{1}; b{2}(4,:)     = a{2}; b{3}(4,:)     = a{3};
c = { rand(5,10,10)   rand(5,10,10)+0.5   rand(5,10,10)};   c{1}(2,4,:)   = a{1}; c{2}(2,4,:)   = a{2}; c{3}(2,4,:)   = a{3};
d = { rand(2,5,10,10) rand(2,5,10,10)+0.5 rand(2,5,10,10)}; d{1}(1,2,4,:) = a{1}; d{2}(1,2,4,:) = a{2}; d{3}(1,2,4,:) = a{3};
[t1 df1 pvals1] = statcond(a(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t2 df2 pvals2] = statcond(b(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t3 df3 pvals3] = statcond(c(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t4 df4 pvals4] = statcond(d(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
fprintf('Statistics paired statcond t-test dim1 t-value %2.2f df=%d p=%0.4f\n', t1, df1, pvals1);
fprintf('Statistics paired statcond t-test dim2 t-value %2.2f df=%d p=%0.4f\n', t2(4), df2, pvals2(4));
fprintf('Statistics paired statcond t-test dim3 t-value %2.2f df=%d p=%0.4f\n', t3(2,4), df3, pvals3(2,4));
fprintf('Statistics paired statcond t-test dim4 t-value %2.2f df=%d p=%0.4f\n', t4(1,2,4), df4, pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t2 df2 pvals2] = statcond(b(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t3 df3 pvals3] = statcond(c(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t4 df4 pvals4] = statcond(d(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
fprintf('Statistics unpaired statcond t-test dim1 t-value %2.2f df=%d p=%0.4f\n', t1, df1, pvals1);
fprintf('Statistics unpaired statcond t-test dim2 t-value %2.2f df=%d p=%0.4f\n', t2(4), df2, pvals2(4));
fprintf('Statistics unpaired statcond t-test dim3 t-value %2.2f df=%d p=%0.4f\n', t3(2,4), df3, pvals3(2,4));
fprintf('Statistics unpaired statcond t-test dim4 t-value %2.2f df=%d p=%0.4f\n', t4(1,2,4), df4, pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
fprintf('Statistics paired statcond anova 1-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1, df1(1), df1(2), pvals1);
fprintf('Statistics paired statcond anova 1-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2(4), df2(1), df2(2), pvals2(4));
fprintf('Statistics paired statcond anova 1-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3(2,4), df3(1), df3(2), pvals3(2,4));
fprintf('Statistics paired statcond anova 1-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4(1,2,4), df4(1), df4(2), pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
fprintf('Statistics unpaired statcond anova 1-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1, df1(1), df1(2), pvals1);
fprintf('Statistics unpaired statcond anova 1-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2(4), df2(1), df2(2), pvals2(4));
fprintf('Statistics unpaired statcond anova 1-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3(2,4), df3(1), df3(2), pvals3(2,4));
fprintf('Statistics unpaired statcond anova 1-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4(1,2,4), df4(1), df4(2), pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
a(2,:) = a; a{1} = a{1}/2;
b(2,:) = b; b{1} = b{1}/2;
c(2,:) = c; c{1} = c{1}/2;
d(2,:) = d; d{1} = d{1}/2;
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
fprintf('Statistics paired statcond anova 2-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1{3}, df1{3}(1), df1{3}(2), pvals1{3});
fprintf('Statistics paired statcond anova 2-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2{3}(4), df2{3}(1), df2{3}(2), pvals2{3}(4));
fprintf('Statistics paired statcond anova 2-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3{3}(2,4), df3{3}(1), df3{3}(2), pvals3{3}(2,4));
fprintf('Statistics paired statcond anova 2-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4{3}(1,2,4), df4{3}(1), df4{3}(2), pvals4{3}(1,2,4));
assertsame([t1{3} t2{3}(4) t3{3}(2,4) t4{3}(1,2,4)], [df1{3}(1) df2{3}(1) df3{3}(1) df4{3}(1)], [df1{3}(2) df2{3}(2) df3{3}(2) df4{3}(2)], [pvals1{3} pvals2{3}(4) pvals3{3}(2,4) pvals4{3}(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
fprintf('Statistics unpaired statcond anova 2-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1{3}, df1{3}(1), df1{3}(2), pvals1{3});
fprintf('Statistics unpaired statcond anova 2-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2{3}(4), df2{3}(1), df2{3}(2), pvals2{3}(4));
fprintf('Statistics unpaired statcond anova 2-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3{3}(2,4), df3{3}(1), df3{3}(2), pvals3{3}(2,4));
fprintf('Statistics unpaired statcond anova 2-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4{3}(1,2,4), df4{3}(1), df4{3}(2), pvals4{3}(1,2,4));
assertsame([t1{3} t2{3}(4) t3{3}(2,4) t4{3}(1,2,4)], [df1{3}(1) df2{3}(1) df3{3}(1) df4{3}(1)], [df1{3}(2) df2{3}(2) df3{3}(2) df4{3}(2)], [pvals1{3} pvals2{3}(4) pvals3{3}(2,4) pvals4{3}(1,2,4)]);
disp('--------------------');

% testing shuffling and permutation for bootstrap
% -----------------------------------------------
clear a;
m1 = [1:10];
m2 = [1:10]+100;
m3 = [1:10]+1000;
a{1} = { m1 m2 };
a{2} = { m1 m2 m3 };
a{3} = { [ zeros(9,10); m1] [ zeros(9,10); m2] };
a{4} = { [ zeros(9,10); m1] [ zeros(9,10); m2] [ zeros(9,10); m3] };
tmpa = zeros(9,8,10); tmpa(end,end,:) = m1;
tmpb = zeros(9,8,10); tmpb(end,end,:) = m2;
tmpc = zeros(9,8,10); tmpc(end,end,:) = m3;
a{5} = { tmpa tmpb };
a{6} = { tmpa tmpb tmpc };

for method = 1:2
    if method == 2, opt = {'arraycomp', 'off'}; else opt = {}; end
    for dim = 1:length(a)
        [sa1] = statcond(a{dim}, 'mode', 'bootstrap', 'verbose', 'off', 'paired', 'on',  'returnresamplingarray', 'on', opt{:}, 'naccu', 10);
        [sa2] = statcond(a{dim}, 'mode', 'perm'     , 'verbose', 'off', 'paired', 'on',  'returnresamplingarray', 'on', opt{:}, 'naccu', 10);
        [sa3] = statcond(a{dim}, 'mode', 'bootstrap', 'verbose', 'off', 'paired', 'off', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10);
        [sa4] = statcond(a{dim}, 'mode', 'perm'     , 'verbose', 'off', 'paired', 'off', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10);

        % select data
        nd = ndims(sa1{1});
        if nd == 2 && size(sa1{1},2) > 1
            for t=1:length(sa1),
                sa1{t} = sa1{t}(end,:);
                sa2{t} = sa2{t}(end,:);
                sa3{t} = sa3{t}(end,:);
                sa4{t} = sa4{t}(end,:);
            end
        elseif nd == 3
            for t=1:length(sa1),
                sa1{t} = squeeze(sa1{t}(end,end,:));
                sa2{t} = squeeze(sa2{t}(end,end,:));
                sa3{t} = squeeze(sa3{t}(end,end,:));
                sa4{t} = squeeze(sa4{t}(end,end,:));
            end
        elseif nd == 4
            for t=1:length(sa1),
                sa1{t} = squeeze(sa1{t}(end,end,end,:));
                sa2{t} = squeeze(sa2{t}(end,end,end,:));
                sa3{t} = squeeze(sa3{t}(end,end,end,:));
                sa4{t} = squeeze(sa4{t}(end,end,end,:));
            end
        end

        % for paired bootstrap, we make sure that the resampling has only shuffled between conditions
        % for instance [101 2 1003 104 ...] is an acceptable sequence
        if all(rem(sa1{1}(:)',10) == [1:9 0]) && all(rem(sa1{2}(:)',10) == [1:9 0])
            fprintf('Bootstrap paired dim%d resampling method %d Pass\n', dim, method);
        else  error('Bootstrap paired resampling Error');
        end
        % for paired permutation, in addition, we make sure that the sum across condition is constant
        % which is not true for bootstrap
        msa = meansa(sa2); msa = msa(:)-msa(1);
        if all(rem(sa1{1}(:)',10) == [1:9 0]) && all(rem(sa1{2}(:)',10) == [1:9 0]) && ...
            all(round(msa) == [0:9]') && length(unique(sa2{1})) == 10 && length(unique(sa2{2})) == 10
            fprintf('Permutation paired dim%d resampling method %d Pass\n', dim, method);
        else  error('Permutation paired resampling Error');
        end
        % for unpaired bootstrap, only make sure there are enough unique
        % values
        if length(unique(sa3{1})) > 3 && length(unique(sa3{2})) > 3
             fprintf('Bootstrap unpaired dim%d reampling method %d Pass\n', dim, method);
        else   error('Bootstrap unpaired reampling Error');
        end
        % for unpaired permutation, the number of unique values must be 10
        % and the sum must be constant (not true for bootstrap)
        if length(unique(sa4{1})) == 10 && length(unique(sa4{2})) == 10 && ( floor(mean(meansa(sa4))) == 55 || floor(mean(meansa(sa4))) == 372 )
             fprintf('Permutation unpaired dim%d reampling method %d Pass\n', dim, method);
        else   error('Permutation unpaired reampling Error');
        end

        disp('------------------------');
    end
end

% function to check
function assertsame(varargin)

for ind = 1:length(varargin)
    if length(varargin{1}) > 2
        for tmpi = 1:length(varargin{1})-1
            assertsame(varargin{1}(tmpi:tmpi+1));
        end
        return;
    else
        if (varargin{ind}(1)-varargin{ind}(2)) > abs(mean(varargin{ind}))*0.01
            error('Test failed');
        end
    end
end
disp('Test pass');

function [meanmat] = meansa(mat)

meanmat = zeros(size(mat{1}));
for index = 1:length(mat)
    meanmat = meanmat+mat{index}/length(mat);
end

function stats = rm_anova2(Y,S,F1,F2,FACTNAMES)
%
% function stats = rm_anova2(Y,S,F1,F2,FACTNAMES)
%
% Two-factor, within-subject repeated measures ANOVA.
% For designs with two within-subject factors.
%
% Parameters:
%    Y          dependent variable (numeric) in a column vector
%    S          grouping variable for SUBJECT
%    F1         grouping variable for factor #1
%    F2         grouping variable for factor #2
%    F1name     name (character array) of factor #1
%    F2name     name (character array) of factor #2
%
%    Y should be a 1-d column vector with all of your data (numeric).
%    The grouping variables should also be 1-d numeric, each with same
%    length as Y. Each entry in each of the grouping vectors indicates the
%    level # (or subject #) of the corresponding entry in Y.
%
% Returns:
%    stats is a cell array with the usual ANOVA table:
%      Source / ss / df / ms / F / p
%
% Notes:
%    Program does not do any input validation, so it is up to you to make
%    sure that you have passed in the parameters in the correct form:
%
%       Y, S, F1, and F2 must be numeric vectors all of the same length.
%
%       There must be at least one value in Y for each possible combination
%       of S, F1, and F2 (i.e. there must be at least one measurement per
%       subject per condition).
%
%       If there is more than one measurement per subject X condition, then
%       the program will take the mean of those measurements.
%
% Aaron Schurger (2005.02.04)
%   Derived from Keppel & Wickens (2004) "Design and Analysis" ch. 18
%

%
% Revision history...
%
% 11 December 2009 (Aaron Schurger)
%
% Fixed error under "bracket terms"
% was: expY = sum(Y.^2);
% now: expY = sum(sum(sum(MEANS.^2)));
%

stats = cell(4,5);

F1_lvls = unique_bc(F1);
F2_lvls = unique_bc(F2);
Subjs = unique_bc(S);

a = length(F1_lvls); % # of levels in factor 1
b = length(F2_lvls); % # of levels in factor 2
n = length(Subjs); % # of subjects

INDS = cell(a,b,n); % this will hold arrays of indices
CELLS = cell(a,b,n); % this will hold the data for each subject X condition
MEANS = zeros(a,b,n); % this will hold the means for each subj X condition

% Calculate means for each subject X condition.
% Keep data in CELLS, because in future we may want to allow options for
% how to compute the means (e.g. leaving out outliers > 3stdev, etc...).
for i=1:a % F1
    for j=1:b % F2
        for k=1:n % Subjs
            INDS{i,j,k} = find(F1==F1_lvls(i) & F2==F2_lvls(j) & S==Subjs(k));
            CELLS{i,j,k} = Y(INDS{i,j,k});
            MEANS(i,j,k) = mean(CELLS{i,j,k});
        end
    end
end

% make tables (see table 18.1, p. 402)
AB = reshape(sum(MEANS,3),a,b); % across subjects
AS = reshape(sum(MEANS,2),a,n); % across factor 2
BS = reshape(sum(MEANS,1),b,n); % across factor 1

A = sum(AB,2); % sum across columns, so result is ax1 column vector
B = sum(AB,1); % sum across rows, so result is 1xb row vector
S = sum(AS,1); % sum across columns, so result is 1xs row vector
T = sum(sum(A)); % could sum either A or B or S, choice is arbitrary

% degrees of freedom
dfA = a-1;
dfB = b-1;
dfAB = (a-1)*(b-1);
dfS = n-1;
dfAS = (a-1)*(n-1);
dfBS = (b-1)*(n-1);
dfABS = (a-1)*(b-1)*(n-1);

% bracket terms (expected value)
expA = sum(A.^2)./(b*n);
expB = sum(B.^2)./(a*n);
expAB = sum(sum(AB.^2))./n;
expS = sum(S.^2)./(a*b);
expAS = sum(sum(AS.^2))./b;
expBS = sum(sum(BS.^2))./a;
expY = sum(sum(sum(MEANS.^2))); %sum(Y.^2);
expT = T^2 / (a*b*n);

% sums of squares
ssA = expA - expT;
ssB = expB - expT;
ssAB = expAB - expA - expB + expT;
ssS = expS - expT;
ssAS = expAS - expA - expS + expT;
ssBS = expBS - expB - expS + expT;
ssABS = expY - expAB - expAS - expBS + expA + expB + expS - expT;
ssTot = expY - expT;

% mean squares
msA = ssA / dfA;
msB = ssB / dfB;
msAB = ssAB / dfAB;
msS = ssS / dfS;
msAS = ssAS / dfAS;
msBS = ssBS / dfBS;
msABS = ssABS / dfABS;

% f statistic
fA = msA / msAS;
fB = msB / msBS;
fAB = msAB / msABS;

% p values
pA = 1-fcdf(fA,dfA,dfAS);
pB = 1-fcdf(fB,dfB,dfBS);
pAB = 1-fcdf(fAB,dfAB,dfABS);

% return values
stats = {'Source','SS','df','MS','F','p';...
         FACTNAMES{1}, ssA, dfA, msA, fA, pA;...
         FACTNAMES{2}, ssB, dfB, msB, fB, pB;...
         [FACTNAMES{1} ' x ' FACTNAMES{2}], ssAB, dfAB, msAB, fAB, pAB;...
         [FACTNAMES{1} ' x Subj'], ssAS, dfAS, msAS, [], [];...
         [FACTNAMES{1} ' x Subj'], ssBS, dfBS, msBS, [], [];...
         [FACTNAMES{1} ' x ' FACTNAMES{2} ' x Subj'], ssABS, dfABS, msABS, [], []};

 return

author: sccn

repo: eeglab

save_path: github-repos/MATLAB/sccn-eeglab


text:
I = imreadRGB(fullfile('birds.jpg'));
imsz = [size(I,1), size(I,2)];

tic;
[P, S] = getProposals(I, net, param);
res = propOpt(P, S, param);

% scale bboxes to full size
res = bsxfun(@times, res, imsz([2 1 2 1])');

% optional window refining process
resRefine = refineWin(I, res, net, param);
toc

subplot(1,2,1)
imshow(I)
for i = 1:size(res,2)
    rect = res(:,i);
    rect(3:4) = rect(3:4)-rect(1:2) +1;
    rectangle('Position',rect,'linewidth',2,'edgecolor',[1 0 0]);
end
title('W/O Window Refining');

subplot(1,2,2)

imshow(I)
for i = 1:size(resRefine,2)
    rect = resRefine(:,i);
    rect(3:4) = rect(3:4)-rect(1:2) +1;
    rectangle('Position',rect,'linewidth',2,'edgecolor',[1 0 0]);
end
title(sprintf('With Window Refining\n for Small Objects'))

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


text:
function quadrule_test27 ( )

%*****************************************************************************80
%
%% TEST27 tests LEGENDRE_SET_LOG and SUM_SUB.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 October 2009
%
%  Author:
%
%    John Burkardt
%
  order_max = 20;
  test_num = 9;

  norder_test = [ 1, 2, 3, 4, 5, 6, 7, 8, 16 ];

  a = 0.0;
  b = 1.0;

  nsub = 1;

  xlo = 0.0;
  xhi = 1.0;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST27\n' );
  fprintf ( 1, '  LEGENDRE_SET_LOG sets up Gauss-Legendre quadrature\n' );
  fprintf ( 1, '    over [0,1] with weight function -LOG(X);\n' );
  fprintf ( 1, '  SUM_SUB carries it out.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  The integration interval is [%f, %f]\n', a, b );
  fprintf ( 1, '  Number of subintervals is %d\n', nsub );
  fprintf ( 1, '  Quadrature order will vary.\n' );
  fprintf ( 1, '  Integrand will vary.\n' );

  nfunc = func_set ( 'COUNT', 'DUMMY' );

  for ilo = 1 : 5 : nfunc

    ihi = min ( ilo + 4, nfunc );

    fprintf ( 1, '\n' );
    fprintf ( 1, '    ' );
    for i = ilo : ihi
      fprintf ( '%14s', fname(i) );
    end
    fprintf ( 1, '\n' );
    fprintf ( 1, '\n' );

    for test = 1 : test_num

      norder = norder_test(test);

      fprintf ( 1, '  %2d', norder );

      for i = ilo : ihi

        func_set ( 'SET', i );

        [ xtab, weight ] = legendre_set_log ( norder );

        result(i) = sum_sub ( @func, a, b, nsub, norder,  xlo, xhi, xtab, ...
          weight );

        fprintf ( 1, '  %12f', result(i) );

      end

      fprintf ( 1, '\n' );

    end

  end

  return
end

author: johannesgerer

repo: jburkardt-m