text:
function varargout = metchgui_one(varargin)
%    alldata = metchgui_one(node,elem,points) or metchgui_one(volume,points,pface)
%
%    A GUI to register a point cloud to a mesh or volumetric image
%
%    author: Qianqian Fang <q.fang at neu.edu>
%    date: 12/16/2008
%
%   parameters:
%        node: node coordinate of the surface mesh (nn x 3)
%        elem: element list of the surface mesh (3 columns for
%              triangular mesh, 4 columns for cubic surface mesh)
%        points: the coordinates (3 columns for x/y/z) of the
%              point cloud which you want to register
%        pface:trianglular surface defined on the point cloud.
%              pface is optional; if presents, metch will display
%              a surface object instead of a point cloud.
%
%   the input can also be two parameters in form of metchgui_one(volume,points),
%    where volume is a 3D image (array).
%
%   outputs:
%        alldata: a structrure containing all processing outputs
%        the fields include:
%         .node: the input node
%         .elem: the input surface mesh elements
%         .volume: if the input volumetric image
%         .A0: the affine rotation for selected point pairs (after Initialize)
%         .b0: the affine translation for selected point pairs (after Initialize)
%         .A: the affine rotation for the point cloud (after Optimize)
%         .b: the affine translation for the point cloud (after Optimize)
%         .points: the input point cloud
%         .pointsinit: the point cloud after initialization
%         .pointsopt: the point cloud after optimization
%         .pointsproj: the point cloud after projecting to the surface
%         .initplot: the handle to the point cloud plot after init
%         .optplot: the handle to the point cloud plot after optimization
%         .projplot: the handle to the point cloud plot after projection
%
%   If user supplys an output variable, the GUI will not return until the
%   user hits the "close" button or close the window; if user does not
%   supply any output, the call will return immediately; any data user
%   intends to save, he has to click on "Save Session" button and provides
%   a mat-file file name. A single structure named "metchsession" will be
%   stored in this file.
%
%   example: (meshasphere/meshunitsphere are defined in iso2mesh http://iso2mesh.sf.net)
%
%       [noderef,faceref,elemref]=meshunitsphere(0.08,10);
%       [no,fc]=removeisolatednode(noderef(:,1:3),faceref(:,1:3));
%       [node,face,elem]=meshasphere([10 20 15],3,0.5,10);
%       [no2,fc2]=removeisolatednode(node(:,1:3),face(:,1:3));
%       alldata = metchgui(no,fc,no2);
%       % or alldata = metchgui(no,fc,no2,fc2);
%
%   Please find more information at http://iso2mesh.sf.net/cgi-bin/index.cgi?metch
%
%   this function is part of "metch" toobox, see COPYING for license

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @metchgui_one_OpeningFcn, ...
                   'gui_OutputFcn',  @metchgui_one_OutputFcn, ...
                   'gui_LayoutFcn',  @metchgui_one_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{:}, 'hasoutput');
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before metchgui_one is made visible.
function metchgui_one_OpeningFcn(hObject, eventdata, handles, varargin)
handles.hasoutput=0;
if(isempty(varargin))
    fprintf(1,'Metch GUI must be called with parameters:\nFormat: alldata = metchgui_one(node,elem,points,pface);\n');
    close(handles.MetchGUI);
    return;
end
if(ischar(varargin{end}) && strcmp(varargin{end},'hasoutput'))
        handles.hasoutput=1;
        varargin(end)=[];
end
handles.output = hObject;

set(handles.btAddMeshPt,'userdata',[handles.axMesh,handles.btAddMeshPt,handles.btAddCloudPt]);
set(handles.btAddCloudPt,'userdata',[handles.axMesh,handles.btAddCloudPt,handles.btAddMeshPt]);

% if uses supplied 2 input variables, assume a volume image and a point cloud
if(isnumeric(varargin{1}) && length(size(varargin{1}))==3)
       vol=varargin{1};
       pt=varargin{2};

       dat.volume=vol;
       dat.points=pt;

       slice=round(size(vol,3)/2);
       hs=imagesc(vol(:,:,slice),'parent',handles.axMesh);
       set(handles.slPos,'max',size(vol,3),'min',1,'value',slice);

       if(length(varargin)>=3)
       	 pface=varargin{3};
       	 dat.pface=pface;
	 trisurf(pface(:,1:3),pt(:,1),pt(:,2),pt(:,3),'parent',handles.axPoints);
       else
         %plot3(pt(:,1),pt(:,2),pt(:,3),'.','parent',handles.axPoints);
         ptcolor=(pt-repmat(min(pt),size(pt,1),1))./repmat(max(pt)-min(pt),size(pt,1),1);
         drawnow;
         scatter3(pt(:,1),pt(:,2),pt(:,3),3,ptcolor,'filled');
       end
       set(handles.MetchGUI,'userdata',dat);

       axis(handles.axMesh,'equal');
       axis(handles.axPoints,'equal');
       axis(handles.axMesh,'off');
       grid(handles.axPoints,'on');
       %axis(handles.axPoints,'off');

       set(handles.axMesh,'tag','axMesh');
       set(handles.axPoints,'tag','axPoints');
       set(handles.slPos,'visible','on');
       set(handles.lbZPos,'visible','on');
       rotate3d(handles.axPoints,'on');
       rotate3d(gcf,'on');
end

% if uses supplied 3 input variables, assume a surface mesh and a point cloud/surface
if(length(varargin)>=3 && length(size(varargin{1}))==2)
       node=varargin{1};
       elem=varargin{2};
       pt=varargin{3};

       dat.node=node;
       dat.elem=elem;
       dat.points=pt;
       if(length(varargin)>=4)
       	 pface=varargin{4};
       	 dat.pface=pface;
       end
       set(handles.MetchGUI,'userdata',dat);

       drawinit(handles,dat)
end
guidata(hObject, handles);

if(handles.hasoutput)
        uiwait(handles.MetchGUI);
end

%---------------------------------------------------------------------------
function drawinit(handles,dat)

node=dat.node;
elem=dat.elem;
pt=dat.points;

hs=trisurf(elem,node(:,1),node(:,2),node(:,3),'parent',handles.axMesh);
%set(hs,'linestyle','none');
%set(hs,'facecolor','b','facealpha',0.8);

%plot3(pt(:,1),pt(:,2),pt(:,3),'.','parent',handles.axPoints);
if(~isfield(dat,'pface'))
	ptcolor=(pt-repmat(min(pt),size(pt,1),1))./repmat(max(pt)-min(pt),size(pt,1),1);
	drawnow;
	scatter3(pt(:,1),pt(:,2),pt(:,3),3,ptcolor,'filled');
else
	trisurf(dat.pface,pt(:,1),pt(:,2),pt(:,3),'parent',handles.axPoints);
end
%hold(handles.axPoints,'on');
%plot3(pt(5:7,1),pt(5:7,2),pt(5:7,3),'ro','parent',handles.axPoints);

axis(handles.axMesh,'equal');
axis(handles.axPoints,'equal');
axis(handles.axMesh,'off');
%axis(handles.axPoints,'off');

set(handles.axMesh,'tag','axMesh');
set(handles.axPoints,'tag','axPoints');

if(~exist('OCTAVE_VERSION'))
  rotate3d(handles.axPoints,'on');
  rotate3d(handles.axMesh,'on');
end
rotate3d(gcf,'on');

%---------------------------------------------------------------------------
function varargout = metchgui_one_OutputFcn(hObject, eventdata, handles)
if(length(handles) && isfield(handles,'output') && isfield(handles,'hasoutput') && handles.hasoutput)
        handles.output=get(handles.MetchGUI,'userdata');
        varargout{1} =handles.output;
        close(handles.MetchGUI);
end
%---------------------------------------------------------------------------
function lbMesh_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%---------------------------------------------------------------------------
function lbPoints_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%---------------------------------------------------------------------------
function edit1_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%---------------------------------------------------------------------------
function edit2_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%---------------------------------------------------------------------------
function edit3_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%---------------------------------------------------------------------------
function isSelect_Callback(hObject, eventdata, handles)
if(get(hObject,'Value'))
        datacursormode(gcf,'on');
        set(datacursormode(gcf),'UpdateFcn',@myupdatefcn)
else
        datacursormode(gcf,'off');
        rotate3d(gcf,'on');
end

%---------------------------------------------------------------------------
% the respond function when there is a data-tip to popup
%---------------------------------------------------------------------------
function txt=myupdatefcn(empt,event_obj)
pos = get(event_obj,'Position');
idx=  get(event_obj,'DataIndex');

if(length(pos)==3)
  txt = {['x: ',num2str(pos(1))],...
         ['y: ',num2str(pos(2))],['z: ',num2str(pos(3))],['index:', num2str(idx)]};
elseif(length(pos)==2)
  txt = {['x: ',num2str(pos(1))],['y: ',num2str(pos(2))]};
end
targetup=get(get(event_obj,'Target'),'parent');
set(targetup,'userdata',struct('pos',pos,'idx',idx));
if(targetup==findobj('tag','axMesh'))
         set(findobj('tag','btAddMeshPt'),'enable','on');
         set(findobj('tag','btAddCloudPt'),'enable','off');
elseif(targetup==findobj('tag','axPoints'))
         set(findobj('tag','btAddMeshPt'),'enable','off');
         set(findobj('tag','btAddCloudPt'),'enable','on');
end

%---------------------------------------------------------------------------
function bInit_Callback(hObject, eventdata, handles)
mapto=get(handles.lbMesh,'userdata');
mapfrom=get(handles.lbPoints,'userdata');

maptoidx=get(handles.txMapTo,'userdata');
mapfromidx=get(handles.txMapFrom,'userdata');

if(length(mapto)<4 | length(mapfrom)<4)
        msgbox('You have to select >3 points from the point cloud plot and corresponding points from the mesh','Error','error');
        return;
end
[A,b]=affinemap(mapfrom,mapto)
dat=get(handles.MetchGUI,'userdata');
dat.A0=A;
dat.b0=b;

newpt=(A*dat.points'+repmat(b(:),1,size(dat.points,1)))';
dat.pointsinit=newpt;

hold(handles.axMesh,'on');
if(isfield(dat,'initplot'))
        delete dat.initplot;
        dat.initplot=0;
end
dat.initplot=plot3(newpt(:,1),newpt(:,2),newpt(:,3),'r.','parent',handles.axMesh);

dat.fromidx=mapfromidx;
dat.toidx=maptoidx;
set(handles.MetchGUI,'userdata',dat);

%---------------------------------------------------------------------------
function axPoints_ButtonDownFcn(hObject, eventdata, handles)
if(get(handles.btSelect,'value')==1)
        pp=getCursorInfo(datacursormode(gcf));
        str=[get(handles.lbPoints,'string');mat2str(pp.Position)];
        set(handles.lbPoints,'string',str);
end

%---------------------------------------------------------------------------
function addselectedpt(pos,idx,lb)
if(isempty(get(lb,'value')))
    set(lb,'value',1);
end
listpt=get(lb,'string');
listpt{end+1}=[num2str(idx) ':' mat2str(pos)];
set(lb,'string',listpt);
set(lb,'userdata',[get(lb,'userdata');pos]);

%---------------------------------------------------------------------------
function btAddMeshPt_Callback(hObject, eventdata, handles)
dat=get(handles.axMesh,'userdata');

dat0=get(handles.MetchGUI,'userdata');
if(isfield(dat0,'volume'))
    dat.pos(:,3)=get(handles.slPos,'value');
end

if(isfield(dat,'pos'))
    addselectedpt(dat.pos,dat.idx,handles.lbMesh);
    set(handles.txMapTo,'userdata',[get(handles.txMapTo,'userdata');dat.idx]);
	dat0.mapto=get(handles.lbMesh,'userdata');
    dat0.maptoidx=get(handles.txMapTo,'userdata');
    set(handles.MetchGUI,'userdata',dat0);
else
        msgbox('No point was selected. Please click on "Select" and select a point on the mesh or point cloud','Error','error');
        return;
end

%---------------------------------------------------------------------------
function btAddCloudPt_Callback(hObject, eventdata, handles)
dat=get(handles.axPoints,'userdata');
dat0=get(handles.MetchGUI,'userdata');
if(isfield(dat,'pos'))
    addselectedpt(dat.pos,dat.idx,handles.lbPoints);
    set(handles.txMapFrom,'userdata',[get(handles.txMapFrom,'userdata');dat.idx]);
	dat0.mapfrom=get(handles.lbPoints,'userdata');
    dat0.mapfromidx=get(handles.txMapFrom,'userdata');
    set(handles.MetchGUI,'userdata',dat0);
else
        msgbox('No point was selected. Please click on "Select" and select a point on the mesh or point cloud','Error','error');
        return;
end

%---------------------------------------------------------------------------
function btOptimize_Callback(hObject, eventdata, handles)
dat=get(handles.MetchGUI,'userdata');
if(isfield(dat,'A0') && isfield(dat,'b0')& isfield(dat,'node')& isfield(dat,'elem')& ...
   isfield(dat,'pointsinit')& isfield(dat,'toidx')& isfield(dat,'fromidx'))
        pmask=-1*ones(size(dat.pointsinit,1),1);
        pmask(dat.fromidx)=dat.toidx;
        if(isfield(dat,'A') && isfield(dat,'b'))
                [Anew,bnew,posnew]=regpt2surf(dat.node,dat.elem,dat.points,pmask,dat.A,dat.b,ones(12,1),10);
        else
                [Anew,bnew,posnew]=regpt2surf(dat.node,dat.elem,dat.points,pmask,dat.A0,dat.b0,ones(12,1),10);
        end
        dat.A=Anew;
        dat.b=bnew;
        dat.pointsopt=posnew;
        if(isfield(dat,'optplot') && dat.optplot)
                delete dat.optplot;
                dat.optplot=0;
        end
        dat.optplot=plot3(posnew(:,1),posnew(:,2),posnew(:,3),'g+','parent',handles.axMesh);
else
        msgbox('You have to select 4 points and click "Initialize" button first','Error','error');
        return;
end
set(handles.MetchGUI,'userdata',dat);

%---------------------------------------------------------------------------
function slPos_Callback(hObject, eventdata, handles)
dat=get(handles.MetchGUI,'userdata');
if(isfield(dat,'volume'))
        hold(handles.axMesh,'off');
        imagesc(dat.volume(:,:,round(get(hObject,'value'))),'parent',handles.axMesh);
        set(handles.axMesh,'tag','axMesh');
        set(handles.lbZPos,'string',num2str(round(get(hObject,'value'))));
end
set(handles.MetchGUI,'userdata',dat);

%---------------------------------------------------------------------------
function slPos_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

%--------------------------------------------------------------------------
function btProj_Callback(hObject, eventdata, handles)
dat=get(handles.MetchGUI,'userdata');
if(isfield(dat,'pointsopt'))
        if(isfield(dat,'projplot') && dat.projplot)
                delete dat.projplot;
                dat.projplot=0;
        end
        nv=nodesurfnorm(dat.node,dat.elem);
        [d2surf,cn]=dist2surf(dat.node,nv,dat.pointsopt);
        [dat.pointsproj dat.elemid dat.weight]=proj2mesh(dat.node,dat.elem,dat.pointsopt,nv,cn);
        hold(handles.axMesh,'on');
        dat.projplot=plot3(dat.pointsproj(:,1),dat.pointsproj(:,2),dat.pointsproj(:,3),'c.','parent',handles.axMesh);
else
        msgbox('You have to first select 4 points, then click "Initialize" and "Optimize" button','Error','error');
        return;
end
set(handles.MetchGUI,'userdata',dat);

%--------------------------------------------------------------------------
function btSaveRes_Callback(hObject, eventdata, handles)
[filename, pathname] = uiputfile('*.mat', 'Save Metch Workspace as');
mapto=get(handles.lbMesh,'userdata');
mapfrom=get(handles.lbPoints,'userdata');

maptoidx=get(handles.txMapTo,'userdata');
mapfromidx=get(handles.txMapFrom,'userdata');

metchsession=get(handles.MetchGUI,'userdata');
if(~isempty(mapto))    metchsession.mapto=mapto; end
if(~isempty(mapfrom))    metchsession.mapfrom=mapfrom; end
if(~isempty(maptoidx))    metchsession.maptoidx=maptoidx; end
if(~isempty(mapfromidx))    metchsession.mapfromidx=mapfromidx; end
fname=[pathname filename];
save(fname,'metchsession');

%--------------------------------------------------------------------------
function btLoadSession_Callback(hObject, eventdata, handles)
[filename, pathname] = uigetfile('*.mat', 'Load Metch Workspace from');
fname=[pathname filename];
load(fname);
handle.output=metchsession;
cla(handles.axMesh);
cla(handles.axPoints);
drawinit(handles,metchsession.node,metchsession.elem,metchsession.points);
%--------------------------------------------------------------------------
function btPlotResults_Callback(hObject, eventdata, handles)

function btClose_Callback(hObject, eventdata, handles)
guidata(hObject,handles);
uiresume;

function btHelp_Callback(hObject, eventdata, handles)
helpmsg={
'Metch GUI: A mesh/volume registration toolbox',
'',
'Author: Qianqian Fang <q.fang at neu.edu>',
'        Martinos Center for Biomedical Imaging',
'        Charlestown, MA 02129, USA',
'',
'== Description of the workflow ==',
'',
' 1. when the GUI pops up, it will display the mesh and the points,',
'    you can rotate both plots so that you can identify the matching ',
'    features',
' 2. switch on "Select" mode, then, click on a land-mark point on the point',
'    plot, when a data-tip shows up, click "Add Selected" button',
' 3. click on the corresponding position on the mesh, and click',
'    "Add Selected"      ',
' 4. repeat the above for at least 4 point pairs (you can select more);',
'    if you want to change views, switch off "Select" box and rotate;',
'    after rotation, switch on "Select" box again',
' 5. click "Initialize": this will create the initial mapping using the',
'    selected point pairs',
' 6. click "Optimize": this will fit the surface with the whole point cloud',
' 7. click "Proj2Mesh": this will project the fitted point clouds onto the',
'    mesh',
' 8. you can quit the GUI by hit "Close", your results will be saved to reg',
' 9. close the window '};

helpdlg(helpmsg);

% --- Creates and returns a handle to the GUI figure.
function h1 = metchgui_one_LayoutFcn(policy)
% policy - create a new figure or use a singleton. 'new' or 'reuse'.

persistent hsingleton;
if(strcmpi(policy, 'reuse')==1 && ~isempty(hsingleton) && ishandle(hsingleton))
    h1 = hsingleton;
    return;
end

appdata = [];
appdata.GUIDEOptions = struct(...
    'active_h', [], ...
    'taginfo', struct(...
    'figure', 2, ...
    'axes', 3, ...
    'listbox', 3, ...
    'edit', 4, ...
    'text', 8, ...
    'checkbox', 2, ...
    'togglebutton', 3, ...
    'pushbutton', 13, ...
    'slider', 2), ...
    'override', 0, ...
    'release', 13, ...
    'resize', 'none', ...
    'accessibility', 'callback', ...
    'mfile', 1, ...
    'callbacks', 1, ...
    'singleton', 1, ...
    'syscolorfig', 1, ...
    'blocking', 0, ...
    'lastSavedFile', '/autofs/space/earth_002/users/fangq/pmihome/metch/metchgui_one.m');
appdata.lastValidTag = 'MetchGUI';
appdata.GUIDELayoutEditor = [];

h1 = figure(...
'Units','characters',...
'PaperUnits',get(0,'defaultfigurePaperUnits'),...
'Color',[0.701960784313725 0.701960784313725 0.701960784313725],...
'Colormap',[0 0 0.5625;0 0 0.625;0 0 0.6875;0 0 0.75;0 0 0.8125;0 0 0.875;0 0 0.9375;0 0 1;0 0.0625 1;0 0.125 1;0 0.1875 1;0 0.25 1;0 0.3125 1;0 0.375 1;0 0.4375 1;0 0.5 1;0 0.5625 1;0 0.625 1;0 0.6875 1;0 0.75 1;0 0.8125 1;0 0.875 1;0 0.9375 1;0 1 1;0.0625 1 1;0.125 1 0.9375;0.1875 1 0.875;0.25 1 0.8125;0.3125 1 0.75;0.375 1 0.6875;0.4375 1 0.625;0.5 1 0.5625;0.5625 1 0.5;0.625 1 0.4375;0.6875 1 0.375;0.75 1 0.3125;0.8125 1 0.25;0.875 1 0.1875;0.9375 1 0.125;1 1 0.0625;1 1 0;1 0.9375 0;1 0.875 0;1 0.8125 0;1 0.75 0;1 0.6875 0;1 0.625 0;1 0.5625 0;1 0.5 0;1 0.4375 0;1 0.375 0;1 0.3125 0;1 0.25 0;1 0.1875 0;1 0.125 0;1 0.0625 0;1 0 0;0.9375 0 0;0.875 0 0;0.8125 0 0;0.75 0 0;0.6875 0 0;0.625 0 0;0.5625 0 0],...
'IntegerHandle','off',...
'InvertHardcopy',get(0,'defaultfigureInvertHardcopy'),...
'MenuBar','none',...
'Name','Metch GUI: A mesh/image registration utility',...
'NumberTitle','off',...
'PaperPosition',get(0,'defaultfigurePaperPosition'),...
'PaperSize',[20.98404194812 29.67743169791],...
'PaperType',get(0,'defaultfigurePaperType'),...
'Position',[103.8 16.8901098901099 144.5 44.5714285714286],...
'Resize','off',...
'HandleVisibility','callback',...
'Tag','MetchGUI',...
'UserData',[],...
'Visible','on',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'axMesh';

h2 = axes(...
'Parent',h1,...
'Units','characters',...
'Position',[2.83333333333333 3 80.5 39.3571428571429],...
'CameraPosition',[0.5 0.5 9.16025403784439],...
'CameraPositionMode',get(0,'defaultaxesCameraPositionMode'),...
'Color',get(0,'defaultaxesColor'),...
'ColorOrder',get(0,'defaultaxesColorOrder'),...
'LooseInset',[18.9583333333333 5.28 13.8541666666667 3.6],...
'XColor',get(0,'defaultaxesXColor'),...
'YColor',get(0,'defaultaxesYColor'),...
'ZColor',get(0,'defaultaxesZColor'),...
'ButtonDownFcn','metchgui_one(''axMesh_ButtonDownFcn'',gcbo,[],guidata(gcbo))',...
'Tag','axMesh',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

h3 = get(h2,'title');

set(h3,...
'Parent',h2,...
'Units','data',...
'FontUnits','points',...
'BackgroundColor','none',...
'Color',[0 0 0],...
'EdgeColor','none',...
'FontAngle','normal',...
'FontName','Helvetica',...
'FontSize',10,...
'FontWeight','normal',...
'HorizontalAlignment','center',...
'LineStyle','-',...
'LineWidth',0.5,...
'Margin',2,...
'Position',[0.5 1.00998185117967 1.00005459937205],...
'Rotation',0,...
'String','',...
'Interpreter','tex',...
'VerticalAlignment','bottom',...
'ButtonDownFcn',[],...
'CreateFcn', {@local_CreateFcn, [], ''} ,...
'DeleteFcn',[],...
'BusyAction','queue',...
'HandleVisibility','off',...
'HitTest','on',...
'Interruptible','on',...
'SelectionHighlight','on',...
'Tag','',...
'UserData',[],...
'Visible','on',...
'XLimInclude','on',...
'YLimInclude','on',...
'ZLimInclude','on',...
'Clipping','off');

h4 = get(h2,'xlabel');

set(h4,...
'Parent',h2,...
'Units','data',...
'FontUnits','points',...
'BackgroundColor','none',...
'Color',[0 0 0],...
'EdgeColor','none',...
'FontAngle','normal',...
'FontName','Helvetica',...
'FontSize',10,...
'FontWeight','normal',...
'HorizontalAlignment','center',...
'LineStyle','-',...
'LineWidth',0.5,...
'Margin',2,...
'Position',[0.497929606625259 -0.0408348457350272 1.00005459937205],...
'Rotation',0,...
'String','',...
'Interpreter','tex',...
'VerticalAlignment','cap',...
'ButtonDownFcn',[],...
'CreateFcn', {@local_CreateFcn, [], ''} ,...
'DeleteFcn',[],...
'BusyAction','queue',...
'HandleVisibility','off',...
'HitTest','on',...
'Interruptible','on',...
'SelectionHighlight','on',...
'Tag','',...
'UserData',[],...
'Visible','on',...
'XLimInclude','on',...
'YLimInclude','on',...
'ZLimInclude','on',...
'Clipping','off');

h5 = get(h2,'ylabel');

set(h5,...
'Parent',h2,...
'Units','data',...
'FontUnits','points',...
'BackgroundColor','none',...
'Color',[0 0 0],...
'EdgeColor','none',...
'FontAngle','normal',...
'FontName','Helvetica',...
'FontSize',10,...
'FontWeight','normal',...
'HorizontalAlignment','center',...
'LineStyle','-',...
'LineWidth',0.5,...
'Margin',2,...
'Position',[-0.056935817805383 0.498185117967332 1.00005459937205],...
'Rotation',90,...
'String','',...
'Interpreter','tex',...
'VerticalAlignment','bottom',...
'ButtonDownFcn',[],...
'CreateFcn', {@local_CreateFcn, [], ''} ,...
'DeleteFcn',[],...
'BusyAction','queue',...
'HandleVisibility','off',...
'HitTest','on',...
'Interruptible','on',...
'SelectionHighlight','on',...
'Tag','',...
'UserData',[],...
'Visible','on',...
'XLimInclude','on',...
'YLimInclude','on',...
'ZLimInclude','on',...
'Clipping','off');

h6 = get(h2,'zlabel');

set(h6,...
'Parent',h2,...
'Units','data',...
'FontUnits','points',...
'BackgroundColor','none',...
'Color',[0 0 0],...
'EdgeColor','none',...
'FontAngle','normal',...
'FontName','Helvetica',...
'FontSize',10,...
'FontWeight','normal',...
'HorizontalAlignment','right',...
'LineStyle','-',...
'LineWidth',0.5,...
'Margin',2,...
'Position',[-0.036231884057971 1.0535390199637 1.00005459937205],...
'Rotation',0,...
'String','',...
'Interpreter','tex',...
'VerticalAlignment','middle',...
'ButtonDownFcn',[],...
'CreateFcn', {@local_CreateFcn, [], ''} ,...
'DeleteFcn',[],...
'BusyAction','queue',...
'HandleVisibility','off',...
'HitTest','on',...
'Interruptible','on',...
'SelectionHighlight','on',...
'Tag','',...
'UserData',[],...
'Visible','off',...
'XLimInclude','on',...
'YLimInclude','on',...
'ZLimInclude','on',...
'Clipping','off');

appdata = [];
appdata.lastValidTag = 'axPoints';

h7 = axes(...
'Parent',h1,...
'Units','characters',...
'Position',[86.8333333333333 19.4285714285714 54.8333333333333 22.4285714285714],...
'CameraPosition',[0.5 0.5 9.16025403784439],...
'CameraPositionMode',get(0,'defaultaxesCameraPositionMode'),...
'Color',get(0,'defaultaxesColor'),...
'ColorOrder',get(0,'defaultaxesColorOrder'),...
'LooseInset',[18.9583333333333 5.28 13.8541666666667 3.6],...
'XColor',get(0,'defaultaxesXColor'),...
'YColor',get(0,'defaultaxesYColor'),...
'ZColor',get(0,'defaultaxesZColor'),...
'ButtonDownFcn','metchgui_one(''axPoints_ButtonDownFcn'',gcbo,[],guidata(gcbo))',...
'Tag','axPoints',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

h8 = get(h7,'title');

set(h8,...
'Parent',h7,...
'Units','data',...
'FontUnits','points',...
'BackgroundColor','none',...
'Color',[0 0 0],...
'EdgeColor','none',...
'FontAngle','normal',...
'FontName','Helvetica',...
'FontSize',10,...
'FontWeight','normal',...
'HorizontalAlignment','center',...
'LineStyle','-',...
'LineWidth',0.5,...
'Margin',2,...
'Position',[0.5 1.01751592356688 1.00005459937205],...
'Rotation',0,...
'String','',...
'Interpreter','tex',...
'VerticalAlignment','bottom',...
'ButtonDownFcn',[],...
'CreateFcn', {@local_CreateFcn, [], ''} ,...
'DeleteFcn',[],...
'BusyAction','queue',...
'HandleVisibility','off',...
'HitTest','on',...
'Interruptible','on',...
'SelectionHighlight','on',...
'Tag','',...
'UserData',[],...
'Visible','on',...
'XLimInclude','on',...
'YLimInclude','on',...
'ZLimInclude','on',...
'Clipping','off');

h9 = get(h7,'xlabel');

set(h9,...
'Parent',h7,...
'Units','data',...
'FontUnits','points',...
'BackgroundColor','none',...
'Color',[0 0 0],...
'EdgeColor','none',...
'FontAngle','normal',...
'FontName','Helvetica',...
'FontSize',10,...
'FontWeight','normal',...
'HorizontalAlignment','center',...
'LineStyle','-',...
'LineWidth',0.5,...
'Margin',2,...
'Position',[0.496960486322189 -0.0716560509554141 1.00005459937205],...
'Rotation',0,...
'String','',...
'Interpreter','tex',...
'VerticalAlignment','cap',...
'ButtonDownFcn',[],...
'CreateFcn', {@local_CreateFcn, [], ''} ,...
'DeleteFcn',[],...
'BusyAction','queue',...
'HandleVisibility','off',...
'HitTest','on',...
'Interruptible','on',...
'SelectionHighlight','on',...
'Tag','',...
'UserData',[],...
'Visible','on',...
'XLimInclude','on',...
'YLimInclude','on',...
'ZLimInclude','on',...
'Clipping','off');

h10 = get(h7,'ylabel');

set(h10,...
'Parent',h7,...
'Units','data',...
'FontUnits','points',...
'BackgroundColor','none',...
'Color',[0 0 0],...
'EdgeColor','none',...
'FontAngle','normal',...
'FontName','Helvetica',...
'FontSize',10,...
'FontWeight','normal',...
'HorizontalAlignment','center',...
'LineStyle','-',...
'LineWidth',0.5,...
'Margin',2,...
'Position',[-0.0835866261398175 0.495222929936306 1.00005459937205],...
'Rotation',90,...
'String','',...
'Interpreter','tex',...
'VerticalAlignment','bottom',...
'ButtonDownFcn',[],...
'CreateFcn', {@local_CreateFcn, [], ''} ,...
'DeleteFcn',[],...
'BusyAction','queue',...
'HandleVisibility','off',...
'HitTest','on',...
'Interruptible','on',...
'SelectionHighlight','on',...
'Tag','',...
'UserData',[],...
'Visible','on',...
'XLimInclude','on',...
'YLimInclude','on',...
'ZLimInclude','on',...
'Clipping','off');

h11 = get(h7,'zlabel');

set(h11,...
'Parent',h7,...
'Units','data',...
'FontUnits','points',...
'BackgroundColor','none',...
'Color',[0 0 0],...
'EdgeColor','none',...
'FontAngle','normal',...
'FontName','Helvetica',...
'FontSize',10,...
'FontWeight','normal',...
'HorizontalAlignment','right',...
'LineStyle','-',...
'LineWidth',0.5,...
'Margin',2,...
'Position',[-1.58510638297872 1.11624203821656 1.00005459937205],...
'Rotation',0,...
'String','',...
'Interpreter','tex',...
'VerticalAlignment','middle',...
'ButtonDownFcn',[],...
'CreateFcn', {@local_CreateFcn, [], ''} ,...
'DeleteFcn',[],...
'BusyAction','queue',...
'HandleVisibility','off',...
'HitTest','on',...
'Interruptible','on',...
'SelectionHighlight','on',...
'Tag','',...
'UserData',[],...
'Visible','off',...
'XLimInclude','on',...
'YLimInclude','on',...
'ZLimInclude','on',...
'Clipping','off');

appdata = [];
appdata.lastValidTag = 'lbMesh';

h12 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[85.5 4.35714285714286 27.5 9.35714285714285],...
'String','',...
'Style','listbox',...
'Value',1,...
'Tag','lbMesh',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'lbPoints';

h13 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[114 4.35714285714286 27.6666666666667 9.42857142857143],...
'String','',...
'Style','listbox',...
'Value',1,...
'Tag','lbPoints',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'isSelect';

h14 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','metchgui_one(''isSelect_Callback'',gcbo,[],guidata(gcbo))',...
'Position',[85.5 15.8571428571429 10 1.78571428571429],...
'String','Select',...
'Style','togglebutton',...
'Tag','isSelect',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'btDelete';

h15 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','metchgui_one(''btDelete_Callback'',gcbo,[],guidata(gcbo))',...
'Position',[95.8333333333333 15.8571428571429 10 1.78571428571429],...
'String','Delete',...
'Tag','btDelete',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'bInit';

h16 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','metchgui_one(''bInit_Callback'',gcbo,[],guidata(gcbo))',...
'Position',[109 15.8571428571429 10 1.78571428571429],...
'String','Initialize',...
'Tag','bInit',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'txMesh';

h17 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[0.614 0.052 0],...
'ForegroundColor',[1 1 1],...
'Position',[2.66666666666667 42.5 80.6666666666667 1.64285714285714],...
'String','Surface mesh',...
'Style','text',...
'ButtonDownFcn','metchgui_one(''txMesh_ButtonDownFcn'',gcbo,[],guidata(gcbo))',...
'Tag','txMesh',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'txPoint';

h18 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[0.0487072545035106 0 0.701960784313725],...
'ForegroundColor',[1 1 1],...
'Position',[85.5 42.5 56 1.64285714285714],...
'String','Point cloud',...
'Style','text',...
'ButtonDownFcn','metchgui_one(''txMesh_ButtonDownFcn'',gcbo,[],guidata(gcbo))',...
'Tag','txPoint',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'btAddMeshPt';

h19 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','metchgui_one(''btAddMeshPt_Callback'',gcbo,[],guidata(gcbo))',...
'Position',[91.5 2.35714285714286 14.5 1.71428571428571],...
'String','Add Selected',...
'Tag','btAddMeshPt',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'btAddCloudPt';

h20 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','metchgui_one(''btAddCloudPt_Callback'',gcbo,[],guidata(gcbo))',...
'Position',[120 2.42857142857143 14.5 1.71428571428571],...
'String','Add Selected',...
'Tag','btAddCloudPt',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'btProj';

h21 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','metchgui_one(''btProj_Callback'',gcbo,[],guidata(gcbo))',...
'Position',[129.666666666667 15.8571428571429 12 1.78571428571429],...
'String','Proj2Mesh',...
'Tag','btProj',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'txMapTo';

h22 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[0.542 0.063 0],...
'ForegroundColor',[1 1 1],...
'Position',[85.5 13.9285714285714 28 1.64285714285714],...
'String','Map To',...
'Style','text',...
'ButtonDownFcn','metchgui_one(''txMesh_ButtonDownFcn'',gcbo,[],guidata(gcbo))',...
'Tag','txMapTo',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'txMapFrom';

h23 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[0.0487072545035106 0 0.701960784313725],...
'ForegroundColor',[1 1 1],...
'Position',[113.666666666667 13.9285714285714 28 1.64285714285714],...
'String','Map From',...
'Style','text',...
'ButtonDownFcn','metchgui_one(''txMesh_ButtonDownFcn'',gcbo,[],guidata(gcbo))',...
'Tag','txMapFrom',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'btOptimize';

h24 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','metchgui_one(''btOptimize_Callback'',gcbo,[],guidata(gcbo))',...
'Position',[119.333333333333 15.8571428571429 10 1.78571428571429],...
'String','Optimize',...
'Tag','btOptimize',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'slPos';

h25 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[0.9 0.9 0.9],...
'Callback','metchgui_one(''slPos_Callback'',gcbo,[],guidata(gcbo))',...
'Position',[2.83333333333333 1.42857142857143 80.5 1.57142857142857],...
'String',{  'Slider' },...
'Style','slider',...
'CreateFcn', {@local_CreateFcn, 'metchgui_one(''slPos_CreateFcn'',gcbo,[],guidata(gcbo))', appdata} ,...
'Tag','slPos',...
'Visible','off');

appdata = [];
appdata.lastValidTag = 'lbZPos';

h26 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Position',[41.8333333333333 -0.0714285714285714 6.66666666666667 1.57142857142857],...
'String','',...
'Style','text',...
'Tag','lbZPos',...
'Visible','off',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'btSaveRes';

h27 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','metchgui_one(''btSaveRes_Callback'',gcbo,[],guidata(gcbo))',...
'Position',[84.3333333333333 -0.0714285714285714 16 1.71428571428571],...
'String','Save Session',...
'Tag','btSaveRes',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'btLoadSession';

h28 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','metchgui_one(''btLoadSession_Callback'',gcbo,[],guidata(gcbo))',...
'Position',[100.833333333333 -0.0714285714285714 16 1.71428571428571],...
'String','Load Session',...
'Tag','btLoadSession',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'btPlotResults';

h29 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','metchgui_one(''btPlotResults_Callback'',gcbo,[],guidata(gcbo))',...
'Position',[117.333333333333 -0.0714285714285714 16 1.71428571428571],...
'String','Plot Results',...
'Tag','btPlotResults',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'btClose';

h30 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[0.701960784313725 0.0456922325275102 0.0152120246425083],...
'Callback','metchgui_one(''btClose_Callback'',gcbo,[],guidata(gcbo))',...
'ForegroundColor',[1 1 1],...
'Position',[134 -0.0714285714285714 10 1.71428571428571],...
'String','Close',...
'Tag','btClose',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'btHelp';

h31 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'BackgroundColor',[0.12 0.542 0],...
'Callback','metchgui_one(''btHelp_Callback'',gcbo,[],guidata(gcbo))',...
'ForegroundColor',[1 1 1],...
'Position',[108.166666666667 2.35714285714286 10 1.71428571428571],...
'String','Help',...
'Tag','btHelp',...
'CreateFcn', {@local_CreateFcn, '', appdata} );

hsingleton = h1;

% --- Set application data first then calling the CreateFcn.
function local_CreateFcn(hObject, eventdata, createfcn, appdata)

if ~isempty(appdata)
   names = fieldnames(appdata);
   for i=1:length(names)
       name = char(names(i));
       setappdata(hObject, name, getfield(appdata,name));
   end
end

if ~isempty(createfcn)
   eval(createfcn);
end

% --- Handles default GUIDE GUI creation and callback dispatch
function varargout = gui_mainfcn(gui_State, varargin)

gui_StateFields =  {'gui_Name'
                    'gui_Singleton'
                    'gui_OpeningFcn'
                    'gui_OutputFcn'
                    'gui_LayoutFcn'
                    'gui_Callback'};
gui_Mfile = '';
for i=1:length(gui_StateFields)
    if ~isfield(gui_State, gui_StateFields{i})
        error('Could not find field %s in the gui_State struct in GUI M-file %s', gui_StateFields{i}, gui_Mfile);
    elseif isequal(gui_StateFields{i}, 'gui_Name')
        gui_Mfile = [gui_State.(gui_StateFields{i}), '.m'];
    end
end

numargin = length(varargin);

if numargin == 0
    % METCHGUI_ONE
    % create the GUI
    gui_Create = 1;
elseif isequal(ishandle(varargin{1}), 1) && ispc && iscom(varargin{1}) && isequal(varargin{1},gcbo)
    % METCHGUI_ONE(ACTIVEX,...)
    vin{1} = gui_State.gui_Name;
    vin{2} = [get(varargin{1}.Peer, 'Tag'), '_', varargin{end}];
    vin{3} = varargin{1};
    vin{4} = varargin{end-1};
    vin{5} = guidata(varargin{1}.Peer);
    feval(vin{:});
    return;
elseif ischar(varargin{1}) && numargin>1 && isequal(ishandle(varargin{2}), 1)
    % METCHGUI_ONE('CALLBACK',hObject,eventData,handles,...)
    gui_Create = 0;
else
    % METCHGUI_ONE(...)
    % create the GUI and hand varargin to the openingfcn
    gui_Create = 1;
end

if gui_Create == 0
    varargin{1} = gui_State.gui_Callback;
    if nargout
        [varargout{1:nargout}] = feval(varargin{:});
    else
        feval(varargin{:});
    end
else
    if gui_State.gui_Singleton
        gui_SingletonOpt = 'reuse';
    else
        gui_SingletonOpt = 'new';
    end

    % Open fig file with stored settings.  Note: This executes all component
    % specific CreateFunctions with an empty HANDLES structure.

    % Do feval on layout code in m-file if it exists
    if ~isempty(gui_State.gui_LayoutFcn)
        gui_hFigure = feval(gui_State.gui_LayoutFcn, gui_SingletonOpt);
        % openfig (called by local_openfig below) does this for guis without
        % the LayoutFcn. Be sure to do it here so guis show up on screen.
	if(exist('movegui'))
            movegui(gui_hFigure,'onscreen');
	end
    else
        gui_hFigure = local_openfig(gui_State.gui_Name, gui_SingletonOpt);
        % If the figure has InGUIInitialization it was not completely created
        % on the last pass.  Delete this handle and try again.
        if isappdata(gui_hFigure, 'InGUIInitialization')
            delete(gui_hFigure);
            gui_hFigure = local_openfig(gui_State.gui_Name, gui_SingletonOpt);
        end
    end

    % Set flag to indicate starting GUI initialization
    setappdata(gui_hFigure,'InGUIInitialization',1);

    % Fetch GUIDE Application options
    gui_Options = getappdata(gui_hFigure,'GUIDEOptions');

    if ~isappdata(gui_hFigure,'GUIOnScreen')
        % Adjust background color
        if gui_Options.syscolorfig
            set(gui_hFigure,'Color', get(0,'DefaultUicontrolBackgroundColor'));
        end

        % Generate HANDLES structure and store with GUIDATA. If there is
        % user set GUI data already, keep that also.
        data = guidata(gui_hFigure);
        handles = guihandles(gui_hFigure);
        if ~isempty(handles)
            if isempty(data)
                data = handles;
            else
                names = fieldnames(handles);
                for k=1:length(names)
                    data.(char(names(k)))=handles.(char(names(k)));
                end
            end
        end
        guidata(gui_hFigure, data);
    end

    % If user specified 'Visible','off' in p/v pairs, don't make the figure
    % visible.
    gui_MakeVisible = 1;
    for ind=1:2:length(varargin)
        if length(varargin) == ind
            break;
        end
        len1 = min(length('visible'),length(varargin{ind}));
        len2 = min(length('off'),length(varargin{ind+1}));
        if ischar(varargin{ind}) && ischar(varargin{ind+1}) && ...
                strncmpi(varargin{ind},'visible',len1) && len2 > 1
            if strncmpi(varargin{ind+1},'off',len2)
                gui_MakeVisible = 0;
            elseif strncmpi(varargin{ind+1},'on',len2)
                gui_MakeVisible = 1;
            end
        end
    end

    % Check for figure param value pairs
    for index=1:2:length(varargin)
        if length(varargin) == index || ~ischar(varargin{index})
            break;
        end
        try set(gui_hFigure, varargin{index}, varargin{index+1}), catch break, end
    end

    % If handle visibility is set to 'callback', turn it on until finished
    % with OpeningFcn
    gui_HandleVisibility = get(gui_hFigure,'HandleVisibility');
    if strcmp(gui_HandleVisibility, 'callback')
        set(gui_hFigure,'HandleVisibility', 'on');
    end

    feval(gui_State.gui_OpeningFcn, gui_hFigure, [], guidata(gui_hFigure), varargin{:});

    if ishandle(gui_hFigure)
        % Update handle visibility
        set(gui_hFigure,'HandleVisibility', gui_HandleVisibility);

        % Make figure visible
        if gui_MakeVisible
            set(gui_hFigure, 'Visible', 'on')
            if gui_Options.singleton
                setappdata(gui_hFigure,'GUIOnScreen', 1);
            end
        end

        % Done with GUI initialization
        rmappdata(gui_hFigure,'InGUIInitialization');
    end

    % If handle visibility is set to 'callback', turn it on until finished with
    % OutputFcn
    if ishandle(gui_hFigure)
        gui_HandleVisibility = get(gui_hFigure,'HandleVisibility');
        if strcmp(gui_HandleVisibility, 'callback')
            set(gui_hFigure,'HandleVisibility', 'on');
        end
        gui_Handles = guidata(gui_hFigure);
    else
        gui_Handles = [];
    end

    if nargout
        [varargout{1:nargout}] = feval(gui_State.gui_OutputFcn, gui_hFigure, [], gui_Handles);
    else
        feval(gui_State.gui_OutputFcn, gui_hFigure, [], gui_Handles);
    end

    if ishandle(gui_hFigure)
        set(gui_hFigure,'HandleVisibility', gui_HandleVisibility);
    end
end

function gui_hFigure = local_openfig(name, singleton)

% this application data is used to indicate the running mode of a GUIDE
% GUI to distinguish it from the design mode of the GUI in GUIDE.
setappdata(0,'OpenGuiWhenRunning',1);

% openfig with three arguments was new from R13. Try to call that first, if
% failed, try the old openfig.
try
    gui_hFigure = openfig(name, singleton, 'auto');
catch
    % OPENFIG did not accept 3rd input argument until R13,
    % toggle default figure visible to prevent the figure
    % from showing up too soon.
    gui_OldDefaultVisible = get(0,'defaultFigureVisible');
    set(0,'defaultFigureVisible','off');
    gui_hFigure = openfig(name, singleton);
    set(0,'defaultFigureVisible',gui_OldDefaultVisible);
end
rmappdata(0,'OpenGuiWhenRunning');

author: fangq


text:
%% subfunction: split nii components into multiple nii
function nii = split_components(nii, s)
fld = 'ComplexImageComponent';
if ~strcmp(tryGetField(s, fld, ''), 'MIXED'), return; end

if ~isfield(s, 'Volumes') % PAR file and single-frame file have this
    nSL = nii.hdr.dim(4); nVol = nii.hdr.dim(5);
    iFrames = 1:nSL:nSL*nVol;
    if isfield(s, 'SortFrames'), iFrames = s.SortFrames(iFrames); end
    s1 = struct(fld, {cell(1, nVol)}, 'MRScaleSlope', nan(1,nVol), ...
            'RescaleSlope', nan(1,nVol), 'RescaleIntercept', nan(1,nVol));
    s.Volumes = dicm_hdr(s, s1, iFrames);
end
if ~isfield(s, 'Volumes'), return; end

% suppose scl not applied in set_nii_hdr, since MRScaleSlope is not integer
flds = {'EchoTimes' 'CardiacTriggerDelayTimes'}; % to split
s1 = s.Volumes;
nii0 = nii;
% [c, ia] = unique(s.Volumes.(fld), 'stable'); % since 2013a?
[~, ia] = unique(s1.(fld));
ia = sort(ia);
c = s1.(fld)(ia);
for i = 1:numel(c)
    nii(i) = nii0;
    ind = strcmp(c{i}, s1.(fld));
    nii(i).img = nii0.img(:,:,:,ind);
    slope = s1.RescaleSlope(ia(i)); if isnan(slope), slope = 1; end
    inter = s1.RescaleIntercept(ia(i)); if isnan(inter), inter = 0; end
    if ~isnan(s1.MRScaleSlope(ia(i)))
        inter = inter / (slope * s1.MRScaleSlope(ia(i)));
        slope = 1 / s1.MRScaleSlope(ia(i));
    end
    nii(i).hdr.scl_inter = inter;
    nii(i).hdr.scl_slope = slope;
    nii(i).hdr.file_name = [s.NiftiName '_' lower(c{i})];
    nii(i) = nii_tool('update', nii(i));

    for j = 1:numel(flds)
        if ~isfield(nii(i).json, flds{j}), continue; end
        nii(i).json.(flds{j}) = nii(i).json.(flds{j})(ind);
    end
end

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
ndataset = {};
location = ['rooms',filesep];
for i = 1:length(dataset)
    data = dataset{i};
    obblist = data.obblist;
    nobblist = [];
    for j = 1:size(obblist,2)
        obb = obblist(1:12,j);
        label = obblist(13:end,j);
        label = binary2dec(label);
        cornerpoints = OBBrep2cornerpoints(obb);
        nobb = [label];
        for k = 1:size(cornerpoints,1)
            nobb = [nobb;cornerpoints(k,:)'];
        end
        nobblist = [nobblist,nobb];
    end
    ndataset{i} = nobblist;

    filename = [location, num2str(i),'.txt'];
    fid = fopen(filename,'w');
    for j = 1:size(nobblist,2)
        nobb = nobblist(:,j);
        for k = 1:length(nobb)
            fprintf(fid, '%f ', nobb(k));
        end
        fprintf(fid,'\n');
    end
    fclose(fid);
end

repo: GRAINS


text:
function [DI, k, mad, w, chi2]  = detectChange(obj, t1, t2)
% Refer to http://people.compute.dtu.dk/alan/software.html
[rows, cols, chns1] = size(t1);
chns2 = size(t2, 3);
chns = min(chns1, chns2);
N = rows*cols;
w = ones(N, 1); % Initial weights
t1_ = reshape(double(t1), N, chns1);
t2_ = reshape(double(t2), N, chns2);
rhos = [];

for ii = 1:obj.nIters
    [sigma, xc] = covW(obj, [t1_, t2_], w);
    x1 = xc(:,1:chns1);
    x2 = xc(:,chns1+1:end);
    sigma11 = sigma(1:chns1, 1:chns1);
    sigma12 = sigma(1:chns1, chns1+1:end);
    sigma21 = sigma(chns1+1:end, 1:chns1);
    sigma22 = sigma(chns1+1:end, chns1+1:end);

    [a, e1] = eig(sigma12 / sigma22 * sigma21, sigma11);
    e1 = sqrt(diag(e1));
    [b, e2] = eig(sigma21 / sigma11 * sigma12, sigma22);
    e2 = sqrt(diag(e2));
    [e1, idx1] = sort(e1, 'descend');
    a = a(:,idx1);
    a = a(:,chns:-1:1);
    e1 = e1(chns:-1:1);
    [e2, idx2] = sort(e2, 'descend');
    b = b(:,idx2);
    b = b(:,chns:-1:1);
    e2 = e2(chns:-1:1);

    % Normalize a for unit dispersion
    % Ensure that a'*s11*a=I to meet the constraints
    vars1 = (a'*sigma11*a);
    a = a ./ sqrt(diag(vars1))';
    % Similiar operations on b
    vars2 = (b'*sigma22*b);
    b = b ./ sqrt(diag(vars2))';

    % Ensure sum of positive correlations between x1 and x1*a is positive
    invStd1 = diag(1./std(x1));
    sgn = diag(sign(sum(invStd1*sigma11*a)));
    a = a*sgn;

    % Assure positive correlation between pair of canonical variates
    b = b .* diag(sign(a'*sigma12*b))';

    mad = x1*a - x2*b;

    % Normalize mad
    % This is no regular operation, yet appears to improve the result
    mad = (mad - mean(mad)) ./ (std(mad)+eps);
    chi2 = sum(mad.^2, 2);

    %         chi2 = sum(mad.^2 ./ (2*(1-e1')), 2);   % Should be no-change std only

    w = 1 - chi2cdf(chi2, chns);

    if ii > 1
        err = max(abs(e1'-rhos(end,:)));
        if err < obj.epsilon, break; end
    end
    rhos = [rhos; e1'];
end

if ii == obj.nIters
    warning('Exceeded max number of iterations.')
end

%     % Use L2 pooling
%     DI = reshape(sqrt(sum(mad.*mad, 2)), rows, cols);

mad = reshape(mad, rows, cols, chns);
w = reshape(w, rows, cols);
chi2 = reshape(chi2, rows, cols);
k = min(chns, obj.nMADUsed);
DI = abs(mad(:,:,1:k));
end

author: Bobholamovic

repo: ChangeDetectionToolbox


text:
function G = bst_meg_sph(L, Channel, Param)
% BST_MEG_SPH: Calculate the (overlapping) sphere models for MEG
%
% USAGE:  G = bst_meg_sph(L, Channel, Param);
%
% INPUT:
%    - L        : a 3 x nL array, each column a source location (x y z coordinates); nL sources
%    - Channel  : a Brainstorm channel structure
%    - Param[]  : array of structures (one per channel)
%        |- Center  : a vector of the x, y, z locations for the sphere model
%        |            (assume the same center for every sphere for the classical spherical head model)
%
% OUTPUT:
%    - G  : the gain matrix: each column is the forward field of each source

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@

%% ===== PARSE INPUTS =====
% Sources locations should be 3 x m
if(size(L,1)~=3)
    error('Matrix not given as 3 x n. Correct calling code');
end
% Check that the number of coils is the same for all the channels
chanCoils = cellfun(@(c)size(c,2), {Channel.Loc});
grpCoils = unique(chanCoils);
% If there are multiple sensor sensor types (different numbres of coils)
if (length(grpCoils) > 1)
    % This function can only accept calls to groups of sensors with the same number of coils
    % => Group the sensors by number of coils and call os_meg as many times as needed
    G = NaN * zeros(length(Channel), 3 * size(L,2));
    for iGrp = 1:length(grpCoils)
        % Get all the sensors with this amount of coils
        iMegGrp = find(chanCoils == grpCoils(iGrp));
        % Compute (os_meg)
        G(iMegGrp,:) = bst_meg_sph(L, Channel(iMegGrp), Param(iMegGrp));
    end
    return;
end
% Number of coils for this call
NumCoils = chanCoils(1);

%% ===== COMPUTATION =====
% Get locations
AllLocs = [Channel.Loc];
AllLocs = reshape(AllLocs, NumCoils*3, size(AllLocs,2)/NumCoils);
% Get orientations
AllOrient = [Channel.Orient];
AllOrient = AllOrient * bst_inorcol(AllOrient);
AllOrient = reshape(AllOrient, NumCoils*3, size(AllOrient,2)/NumCoils);
% Get weights
AllWeight = [Channel.Weight];
AllWeight = reshape(AllWeight(:), NumCoils, length(AllWeight(:))/NumCoils);

% Process each group of coils
G = 0;
for j = 1:NumCoils
    % P.sensor is 3 x nR,each column a sensor location
    % P.orient is 3 x nR, the sensor orientation
    % P.center is 3 x nR, the sphere center for each sensor
    P.sensor = AllLocs((-2:0) + j*3, :);
    P.orient = AllOrient((-2:0) + j*3, :);
    P.weight = AllWeight(j,:);
    P.center = [Param.Center];
    % Local call below
    G = G + sarvas(L, P);
end

%% %%%%%%%%%%%%%%%%%%%%%%%%%%%  Local Sarvas functions %%%%%%%%%%%%%%%%%%%%%%%%
function G = sarvas(L, P)
% Bronzan Sarvas forward model, spherical head
% P.sensor is 3 x nR,each column a sensor location
% P.orient is 3 x nR, the sensor orientation
% P.center is 3 x nR, the sphere center for each sensor

if(~isfield(P,'center')), % user did not provide
   P.center = []; % initialize to null
end
if(isempty(P.center)), % user gave as null
   P.center = zeros(size(P.sensor));  % set to coordinate origin
end

P.sensor = P.sensor - P.center; % shift sensor coordinates

iMag = find(sum(P.sensor.^2,1) == 0); % Indices of channels located at P.center.
if ~isempty(iMag)
    P.sensor(:,iMag) = repmat([1 1 1]',1,length(iMag)); % Move them away (arbitrary location).
end

nR = size(P.sensor,2); % number of sensors
nL = size(L,2);  % number of source points

Rn2 = sum(P.sensor.^2,1); % distance to sensor squared
Rn = sqrt(Rn2); % distance

if (nR >= nL), % more sensors than dipoles
   G = zeros(nR,3*nL);  % gain matrix
   for Li = 1:nL,
      Lmat = L(:,Li+zeros(1,nR)); % matrix of location repeated
      Lmat = Lmat - P.center; % each center shifted relative to its center
      D = P.sensor - Lmat;  % distance from souce to sensors
      Dn2 = sum(D.^2,1); % distance squared
      Dn = sqrt(Dn2);  % distance
      R_dot_D = sum(P.sensor .* D);  % dot product of sensor and distance
      R_dot_Dhat = R_dot_D ./ Dn;  % dot product of sensor and distance

      F = Dn2 .* Rn + Dn .* R_dot_D;  % Sarvas' function F

      GF_dot_o = Dn2 .* sum(P.sensor.*P.orient) ./ Rn + ...
         (2 * Rn + R_dot_Dhat) .* sum(D.*P.orient) + ...
         Dn .* sum((D+P.sensor).*P.orient);

      tempF = GF_dot_o ./ F.^2;

      temp = bst_cross(Lmat,P.orient) ./ F([1 1 1],:) - ...
             bst_cross(Lmat,P.sensor) .* tempF([1 1 1],:);
      G(:,Li*3+[-2 -1 0]) = temp';

   end

else  % more dipoles than sensors nL > nR
   G = zeros(3*nL,nR);  % gain matrix transposed

   for Ri = 1:nR,
      Rmat = P.sensor(:,Ri+zeros(1,nL)); % matrix of sensor repeated
      Omat = P.orient(:,Ri+zeros(1,nL)); % orientations
      Lmat = L - P.center(:,Ri+zeros(1,nL)); % shift centers to this coordinate

      D = Rmat - Lmat;
      Dn2 = sum(D.^2,1); % distance squared
      Dn = sqrt(Dn2);  % distance
      R_dot_D = sum(Rmat .* D);  % dot product of sensor and distance
      R_dot_Dhat = R_dot_D ./ Dn;  % dot product of sensor and distance

      F = Dn2 * Rn(Ri) + Dn .* R_dot_D;  % Sarvas' function F

      GF_dot_o = Dn2 * sum(P.sensor(:,Ri).*P.orient(:,Ri)) / Rn(Ri) + ...
         (2 * Rn(Ri) + R_dot_D ./ Dn) .* sum(D.*Omat) + ...
         Dn .* sum((D+Rmat).*Omat);

      tempF = GF_dot_o ./ F.^2;

      temp = bst_cross(Lmat,Omat) ./ F([1 1 1],:) - ...
             bst_cross(Lmat,Rmat) .* tempF([1 1 1],:);

      G(:,Ri) = temp(:);
   end

   G = G';
end

if(isfield(P,'weight')),
   Weights = P.weight(:); %make sure column
   % scale each row by its appropriate weight
   G = Weights(:,ones(1,size(G,2))) .* G;
end

G = G * 1e-7; % mu_o over 4 pi

author: brainstorm-tools


text:
function y = t_lpdf(x,v,mu,sigma)
% T_LPDF  Log probability density function (lpdf) for Student's T distribution
%
%   Y = T_LPDF(X,V,MU,SIGMA) returns the lpdf of Student's T distribution with
%   degrees of freedom, V, mean, MU and standard deviation, SIGMA, at the
%   values in X.
%
%   The size of Y is the common size of the input arguments. A scalar input
%   functions as a constant matrix of the same size as the other inputs.
%
%   Default values for MU and SIGMA are 0 and 1 respectively.

% Copyright (c) 1998-2004 Aki Vehtari

% This software is distributed under the GNU General Public
% License (version 3 or later); please refer to the file
% License.txt, included with the software, for details.

if nargin < 4,
  sigma = 1;
end

if nargin < 3;
  mu = 0;
end

if nargin < 2,
  error('Requires at least two input arguments.');
end

term = gammaln((v + 1) / 2) - gammaln(v/2) -log(v.*pi)/2;
y = term - log(sigma) + log(1 + ((((x-mu)./sigma).^2)./v)) .* (-(v+1)/2);

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function [grad]= B_sigmoid(future_layers, curr_layer)
output = curr_layer.a;
future_grad = GetFutureGrad(future_layers, curr_layer);
if isfield(curr_layer, 'rho')
    L1 = curr_layer.L1;
    L1weight = curr_layer.L1weight;
    rho = curr_layer.rho;

    tmp = -L1./max(1e-3,rho) + (1-L1)./max(1e-3,(1-rho));
    future_grad = future_grad + repmat(L1weight * tmp, 1, size(future_grad,2));
end

grad = future_grad .* output .* (1-output);

end

author: singaxiong

repo: SignalGraph


text:
function obj = setFuncIndices(obj, index)
    % Sets indinces of the Nlp Function
    %
    % Parameters:
    %  index: the indices of the function @type integer

    % If an offset is not specified, set it to zero.

    assert(length(index) == obj.Dimension, ...
        'The length of the variable indices must be equal to the dimension of the NlpVariable object.');

    if ~isempty(obj.SummandFunctions)
        arrayfun(@(x) setFuncIndices(x, index), ...
            obj.SummandFunctions, 'UniformOutput', false);
    end

    obj.FuncIndices = index;
end

author: ayonga

repo: frost-dev

save_path: github-repos/MATLAB/ayonga-frost-dev


text:
function newpt=rotatevec3d(pt,v1,u1,p0)
%
% newpt=rotatevec3d(pt,v1,u1,p0)
%
% rotate 3D points from one Cartesian coordinate system to another
%
% author: Qianqian Fang, <fangq at nmr.mgh.harvard.edu>
%
% input:
%   pt: 3D points defined in a standard Cartesian system where a unitary
%       z-vector is (0,0,1), 3 columns for x, y and z
%   v1: the unitary z-vector for the target coordinate system
%   u1: the unitary z-vector for the source coordinate system, if ignored,
%       u1=(0,0,1)
%   p0: offset of the new coordinate system, if ignored, p0=(0,0,0)
%
% output:
%   newpt: the transformed 3D points
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

if(nargin<2)
    error('you must give at least pt and v1');
end
if(nargin==2)
    u1=[0,0,1];
end
if(nargin<=3)
    p0=[0,0,0];
end

u1=u1/norm(u1);
v1=v1/norm(v1);

[R,s]=rotmat2vec(u1,v1);
newpt=(R*pt'*s)';

if(nargin>3)
  p0=p0(:)';
  newpt=newpt+repmat(p0,size(newpt,1),1);
end

repo: REST


text:
%DEFINE_MAPPING Define untrained or fixed mapping
%
%   W = DEFINE_MAPPING(ARGIN,TYPE,NAME,PAR)
%
% INPUT
%   ARGIN   - Cell array with arguments of calling routine
%   TYPE    - Mapping type, 'fixed', 'untrained (default)' or 'combiner'
%   NAME    - Name of the mapping, default name of calling routine
%   PAR     - Additional parameters for the name of the mapping
%
% OUTPUT
%   W       - Mapping
%
% DESCRIPTION
% This routine fascilitates the definition of untrained, fixed and
% combiners in order to make the definition of mappings more readable.
%
% SEE ALSO (PRTools Guide)
% MAPPINGS, PRMAPPING, TRAINED_CLASSIFIER, TRAINED_MAPPING, MAPPING_TASK

% Copyright: Robert P.W. Duin, prtools@rduin.nl

function w = define_mapping(varargin)

[pars,type,mapname] = setdefaults(varargin,[],'untrained',[]);
fname = callername;
if isempty(mapname)
  mapname = fname;
end
if (length(varargin)>3)
   mapname = sprintf(mapname,varargin{4:end});
end
if numel(pars) < 2
  w = prmapping(fname,type);
else
  w = prmapping(fname,type,pars(2:end));
end
w = setname(w,mapname);
return

%CALLERNAME
%
%	NAME = CALLERNAME
%
% Returns the name the calling function

function name = callername

[ss ,i] = dbstack;
if length(ss) < 3
	name = [];
else
	name = ss(3).name;
end

author: marianux

repo: ecg-kit

save_path: github-repos/MATLAB/marianux-ecg-kit


text:
function [column_1, column_2, labels, lenght] = load_data(file)
    is_last_line = 0;
    start=1;
    labels = [];
    k = 0;
    file_instance=fopen(file,'rt');
    line = fopen(file_instance);
    while ischar(line)
        line = fgetl(file_instance);
        if ~isempty(strfind(line,'object'))
            k = k+1;
            index = k;
        end
        if ~isempty(strfind(line,'class'))
                split_values = split(line,' ');
                class = split_values(3);
                labels(index) = class;
        end
        if ~isempty(strfind(line,'----------------'))
           is_last_line=0;
        end
        if is_last_line == 1
            if line ~= -1
                start = start+1;
                split_values = strsplit(string(line));
                column_1(index,start) = double(split_values(1, 2));
                column_2(index,start) = double(split_values(1, 3));
            end
        end
        if ~isempty(strfind(line,'dominant hand trajectory:'))
           is_last_line = 1;
           start = 1;
        end
    end
    fclose(file_instance);
    lenght = index;
end

repo: Machine-Learning-Models


text:
function [f] = spm_fx_Lagrangian(P,M,U)
% FORMAT [f] = spm_fx_Lagrangian(P,M,U)
%
% flow subfunction for Langrangian demo

% Lagrangian and Q
%==========================================================================
[n m] = size(U);

for i = 1:m
    x = U(:,i);
    L = P.P{1};
    for j = 2:length(P.P)
        L = L + P.P{j}(:)'*x;
        x = kron(x,U(:,i));
    end

end

% estimate parameters of Lagrangian and Q
%==========================================================================
f    = P.Q*dLdx;

author: spm


text:
% SUMMARY:  Update p_start, A
%           This is common for multinominal-HMM, Gauss-HMM, GMM-HMM, etc.
% AUTHOR:   QIUQIANG KONG
% Created:  14-11-2015
% Modified: 17-11-2015 Add annotation
% -----------------------------------------------------------
% input:
%   Gamma   p(zn|X^{r})
%   Ksi     p(zn-1,zn|X^{r})
% output:
%   p_start p(z1)
%   A       p(zn|zn-1)
% ===========================================================
function [p_start, A] = M_step_common(Gamma, Ksi)
    obj_num = length(Gamma);
    Q = size(Gamma{1},2);

    % calculate p_start
    p_start_numer = zeros(1,Q);
    for r = 1:obj_num
        p_start_numer = p_start_numer + Gamma{r}(1,:);
    end
    p_start = p_start_numer / sum(p_start_numer);

    % calculate A
    A_numer = zeros(Q,Q);
    for r = 1:obj_num
        A_numer = A_numer + reshape(sum(Ksi{r},1), Q, Q);
    end
    A = bsxfun(@rdivide, A_numer, sum(A_numer,2));
end

author: qiuqiangkong

repo: matlab-hmm


text:
function hole_num = p08_hole_num ( )

%*****************************************************************************80
%
%% P08_HOLE_NUM counts the holes in problem 08.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer HOLE_NUM, the number of holes.
%
  hole_num = 1;

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function images = experiment_get_dataset(varargin)
% images = experiment_get_dataset(varargin) - Collect all the images
%   from one of more datasets
% Eg: images = experiment_get_dataset('stock') - to get the stock images
% Use any subset of
%  'copydays', 'stock', 'imnet', 'imnet-lite', 'imnet-nogreen', 'imnet-large', 'hoggle'

if nargin == 0
  subsets = {'stock', 'imnet', 'hoggle'} ;
else
  subsets = varargin ;
end

images = {} ;
for i=1:numel(subsets)

  switch subsets{i}

    case 'copydays'
      % copydays dataset
      tmp = dir('/users/aravindh/work/datasets/copydays/*.jpg') ;
      copydays = cellfun(@(x) fullfile('/users/aravindh/work/datasets/copydays/', x), {tmp(:).name}, 'uniform', false);
      images = horzcat(images, copydays) ;

    case 'stock'
      % stock images
      tmp = vertcat(...
        dir('data/stock_images/*.jpg'), ...
        dir('data/stock_images/*.png')) ;
      stock = cellfun(@(x) fullfile('data/stock_images', x), {tmp(~[tmp.isdir]).name}, 'uniform', false);
      images = horzcat(images, stock) ;

    case 'imnet'
      % image net images. This is a large scale experiment.
      tmp = dir('data/imagenet12-val/*.JPEG') ;
      imnet = cellfun(@(x) fullfile('data/imagenet12-val/', x), {tmp(1:100).name}, 'uniform', false);
      imnet_large = cellfun(@(x) fullfile('data/imagenet12-val/', x), {tmp(101:500).name}, 'uniform', false);
      images = horzcat(images, imnet) ;

    case 'imnet-lite'
      % image net images tiny subset
      tmp = dir('data/imagenet12-val/*.JPEG') ;
      imnet = cellfun(@(x) fullfile('data/imagenet12-val/', x), {tmp(1:100).name}, 'uniform', false);
      imnet_large = cellfun(@(x) fullfile('data/imagenet12-val/', x), {tmp(101:500).name}, 'uniform', false);
      images = horzcat(images, imnet([13 24 43 70])) ;% [1 2 5 8 17 18 30 34 48 56]

    case 'imnet-nogreen'
      % image net images which are not green. To see if the greenish output
      % is a property of the prior or the network.
      tmp = dir('data/imagenet12-val/ILSVRC2012_val_000000*.JPEG') ;
      imnet = cellfun(@(x) fullfile('data/imagenet12-val/', x), {tmp(1:99).name}, 'uniform', false);
      images = horzcat(images, imnet( [1 2 5 17 18 30 34 48 56 70] ));

    case 'imnet-large'
      % image net images
      tmp = dir('data/imagenet12-val/*.JPEG') ;
      imnet_large = cellfun(@(x) fullfile('data/imagenet12-val/', x), {tmp(101:500).name}, 'uniform', false);
      images = horzcat(images, imnet_large);

    case 'hoggle'
      % hoggle images
      hoggle{1} = 'data/hoggle/hoggle-orig-1.jpg' ;
      hoggle{2} = 'data/hoggle/hoggle-orig-2.jpg' ;
      images = horzcat(images, hoggle) ;

  end
end

author: aravindhm

repo: deep-goggle


text:
function finish
% finish
% Matlab OnExit Routine
% Save current path in order to return
% to the same workdir automatically (startup).
% 4/7/99 Ishai Hoch
% mailto:ishaihoch@yahoo.com
% see also startup
sepath=pwd;
save ([matlabroot,'\bin\sepath'],'sepath');

author: Sable

repo: mcbench-benchmarks


text:
function rgb = yellow

% This returns a predefined color as [red green blue] values
%   red               = [255   0   0]/255;
%   green             = [  0 192   0]/255;
%   blue              = [  0   0 255]/255;
%   magenta           = [255 255   0]/255;
%   cyan              = [  0 255 255]/255;
%   yellow            = [255 255   0]/255;
%   white             = [255 255 255]/255;
%   black             = [  0   0   0]/255;
%
%   skull             = [140  85  85]/255
%   cortex            = [255 213 119]/255;
%   cortex_light      = [199 194 169]/255;
%   cortex_dark       = [100  97  85]/255;
%   skin              = [249 223 192]/255;
%   skin_light        = [249 223 192]/255;
%   skin_medium_light = [225 194 158]/255;
%   skin_medium       = [188 142 106]/255;
%   skin_medium_dark  = [155 102	65]/255;
%   skin_dark         = [ 91  71  61]/255;

rgb = [255 255 0]/255;


text:
function problem_num = p00_problem_num ( )

%*****************************************************************************80
%
%% P00_PROBLEM_NUM returns the number of test integration problems.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 September 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer PROBLEM_NUM, the number of problems.
%
  problem_num = 8;

  return
end


text:
%BUCKYTUMBLE shows tumbling Bucky Ball
%   BUCKYTUMBLE -- display the Bucky Ball, slowly tumbling in space
%   Needs perms.m

%   Bill McKeeman

function buckytumble
  gr = (1+sqrt(5))/2;                  % golden ration
  d = @(a,b) a + b*gr;                 % vertex function

  bb = perms(...                       % Bucky Ball vertices
    [d(0,0), d(0,3), d(1,0)            % truncated icosahedron
     d(1,0), d(0,2), d(2,1)
     d(2,0), d(0,1), d(1,2)]/2, 'cycles', 'signs', 'unique');
  [s,f] = edges(bb);                   % start,finish

  mx = max(abs(bb(:)))*1.2;            % frame the picture
  mz = max(abs(bb(3,:)));              % z scale
  clip = @(vec) min(max(vec,0),1);     % black and white
  axis([-mx mx -mx mx]);               % fix the axes
  axis equal
  axis off
  bg = .8*[1 1 1];                     % background grey
  set(gcf, 'color', bg);

  hold on
  tumble;                              % plot it
  hold off

  return;

  % compute the edges of a polyhedron
  function [s,f] = edges(p)
    m = size(p,1);
    d = inf(m);                        % distance matrix
    for i=1:m
      for j=i+1:m
        seg = p(i,:)-p(j,:);           % vertex pairs
        d(i,j) = sqrt(seg*seg');       % distance between
      end
    end
    es = min(d(:));                    % nearest neighbors
    TOL = es/10000;
    [s,f] = find(abs(d-es)<TOL);       % compensate for roundoff
  end

  % tumble until stopped with ^C
  function tumble
    nd = size(bb,2);
    a = rand(nd)/25;                   % about 1 degree
    p = bb;                            % rotatable vertex set
    for reps = 1:intmax
      dr = ndrotate(a);
      for i=1:100                      % 100, then change direction
        cla;                           % clear previous
        fromInfinity(p);               % new edges
        drawnow;
        p = p*dr;                      % new position
        pause(0.03);                   % leave some cycles
      end
      a = a + (rand-0.5)/100;          % change direction
    end
  end

  % plot 2-D shadow of edges
  function fromInfinity(p)
    for k = 1:numel(s)                 % all edges
      e1 = [p(s(k),1)  p(f(k),1)];     % x end
      e2 = [p(s(k),2)  p(f(k),2)];     % y end
      z = p(s(k),3) + p(f(k),3);       % 2*mx : -2*mx
      h = ((z+2*mz)/mz)/4;             %    1 : 0
      h = 1-h;                         %    0 : 1
      c = clip([h h h]);               % black is nearest
      w = 2-h;
      plot(e1, e2, 'color', c, 'linewidth', w);
    end
  end

  % turn angles into orthogonal matrix
  function res = ndrotate(angles)
    [m,n] = size(angles);
    res = eye(n);
    for i=1:m
      for j=1:n
        if i ~= j && angles(i,j) ~= 0
          tmp = eye(n);
          tmp(i,i) = cos(angles(i,j));
          tmp(j,j) = tmp(i,i);
          tmp(i,j) = -sin(angles(i,j));
          tmp(j,i) = -tmp(i,j);
          res = res*tmp;
        end
      end
    end
  end
end


text:
function [x_cplx,opt_val,lb_seq,ub_seq] = CE_similarity_ComRad( H,y,power,ee,x0,cle )
% Branch and Bound Method for ComRad CEP
%   Detailed explanation goes here
N = length(x0);
amp = sqrt(power/N); % Amplitude of the Transmit Signal
y_wave = sqrt(power*cle)*[real(y);imag(y)]; % Equivalent Real Desired Symbol
H_wave = amp*[real(H),imag(H);-imag(H),real(H)]; % Equivalent Real Channel
x0_wave = [real(x0);imag(x0)];
delta = acos(1-ee^2/2);
for ii = 1:N
    l(ii,1) = angle(x0(ii))-delta;
    u(ii,1) = angle(x0(ii))+delta;     %Initialized Upper and Lower Bound
end

A = zeros(N,2*N);
for ii = 1:N
    A(ii,ii) = cos((l(ii)+u(ii))/2)/cos(delta);
    A(ii,ii+N) = sin((l(ii)+u(ii))/2)/cos(delta);
end

max_iternum = 200; %Maximum Iteration Number
epsl = 1e-3; %Tolerence
epsl1 = 1e-6;

[x,LB] = QCQP_LB1( H_wave,y_wave,N,l,u);          %Initialized LB and x
[x_nml1,UB1] = normalize_UB( H_wave,y_wave,x,N,l,u); %Initialized Normalization UB
[x_nml2,UB2] = QCQP_UB( H_wave,y_wave,N,l,u,x_nml1); % fmincon UB
[x_nml,UB] = QCQP_UB( H_wave,y_wave,N,l,u,x_nml2); % fmincon UB
LB_start = LB;
UB_start = UB;

prob_list = zeros(max_iternum+100,4*N+1);          %Problem list initialization
prob_list(1,:)=[x',l',u',LB];
used = 1;
lbest = LB;
ubest = UB;
x_opt = x_nml;

lb_seq = lbest;
ub_seq = ubest;

% if (ubest-lbest)/abs(ubest)<epsl
%     final_lb=lbest;
%     final_ub=ubest;
% end

iter = 2;
con = 1;

while iter<=max_iternum
    xc = prob_list(con,1:2*N)';                                   % Pick a problem having the smallest LB
    lc = prob_list(con,(2*N+1):3*N )';
    uc = prob_list(con,(3*N+1):4*N)';
    x_cplx = x(1:N)+j*x(N+1:2*N);
    %     x_abs = abs(x_cplx);
%     [x_abs_min,cd] = min(x_abs);

    [x_nml3,~] = normalize_UB( H_wave,y_wave,x,N,lc,uc);          % Calculate the UB of the problem
    x_nml3_cplx = x_nml3(1:N)+j*x_nml3(N+1:2*N);
    x_abs = abs(x_cplx - x_nml3_cplx);                            % Branching from the x(n) having the largest gap between x_u and x_l
    [~,cd] = max(x_abs);

    xchild_left_lb=lc;                                            % Generate two sub-problems (left child and right child) at the chosen x(n)
    xchild_left_ub=uc;
    xchild_right_lb=lc;
    xchild_right_ub=uc;
    tr=(lc(cd)+uc(cd))/2;
    xchild_left_ub(cd)=tr;
    xchild_right_lb(cd)=tr;

    if con < used
        prob_list(con,:) = prob_list(used,:);
        used=used-1;
    else
        used=used-1;
    end
    [x,lb] = QCQP_LB1( H_wave,y_wave,N,xchild_left_lb,xchild_left_ub);        % Compute the LB and the associated solution of the left sub-problem

%     [xn_temp,ub_temp] = normalize_UB( H_wave,y_wave,x,N,xchild_left_lb,xchild_left_ub);
%     [xn,ub] = QCQP_UB( H_wave,y_wave,N,xchild_left_lb,xchild_left_ub,xn_temp);
    [xn,ub] = normalize_UB( H_wave,y_wave,x,N,xchild_left_lb,xchild_left_ub); % Compute the UB and the associated solution of the left sub-problem

    if ub < ubest                                                   % If the UB is lower than the current ubest, replace ubest with UB
       ubest=ub;
       x_opt=xn;
    end
    prob_list(used+1,:)=[x',xchild_left_lb',xchild_left_ub',lb];              % Insert the associated LB and solutions into the problem list
    used=used+1;

    [x,lb] = QCQP_LB1( H_wave,y_wave,N,xchild_right_lb,xchild_right_ub);                         % Compute the LB and the associated solution of the right sub-problem
%     [xn_temp,ub_temp] = normalize_UB( H_wave,y_wave,x,N,xchild_right_lb,xchild_right_ub);
%     [xn,ub] = QCQP_UB( H_wave,y_wave,N,xchild_right_lb,xchild_right_ub,xn_temp);
    [xn,ub] = normalize_UB( H_wave,y_wave,x,N,xchild_right_lb,xchild_right_ub); % Compute the UB and the associated solution of the right sub-problem
    if ub < ubest                    % If the UB is lower than the current ubest, replace ubest with UB
       ubest=ub;
       x_opt=xn;
    end
    prob_list(used+1,:)=[x',xchild_right_lb',xchild_right_ub',lb]; % Insert the associated LB and solutions into the problem list
    used=used+1;

    [lbest,con]=min(prob_list(1:used,4*N+1)); % Replace lbest with the smallest LB in the list, mark its index in the problem list as con

    lb_seq(iter)=lbest;           %Generate LB and UB sequences
    ub_seq(iter)=ubest;
    iter=iter+1;

    if ((ubest-lbest)/abs(ubest)<epsl || (ubest-lbest)<epsl1)               %Convergence condition
        final_lb=lbest;
        final_ub=ubest;
        break;
    end
%     clc
%     disp(['Progress - ',num2str(iter),'/',num2str(max_iternum)]);
end
x_cplx = x_opt(1:N)+j*x_opt(N+1:2*N);          %Optimal x

opt_val = objval_func(x_opt,H_wave,y_wave);  %Optimal objective function

end

author: yuanhao-cui

repo: Must-Reading-on-ISAC


text:
function [T, DISTR, df, M, S] = dtiDirTest(Sbar1, N1, Sbar2, N2)

% Computes voxel-wise directional test statistics of two groups.
%
%   [T, DISTR, df, M, S] = dtiDirTest(Sbar1, N1, Sbar2, [N2])
%
% Input:
%   Sbar1, Sbar2    XxYxZx6 (or nx6) arrays of scatter matrices for each group in dt6 format.
%                   X, Y, Z are the volume dimensions (n is the number of voxels).
%   N1, N2          Number of subjects in each group (N2 defaults to 1).
%
% Output:
%   T               XxYxZx1 (or nx1) array of test statistics.
%   DISTR           The string 'f'
%   df              The degrees of freedom of the f distribution
%   M               XxYxZx3 (or nx3) array of pooled mean directions
%   S               XxYxZx1 (or nx1) array of pooled dispersions
%
% Utilities:    ndfun.m, dtiEig.m, dti33to6.m
%
% WARNING: If using Pentium 4, eliminate NaN's from array before running
% (processor bug).
%
% E.g.:
%   [vec,val] = dtiEig(dt6);
%   [M, S, N, Sbar1] = dtiDirMean(squeeze(vec(:,:,1,1:6)));
%   [M1, S1, N1, Sbar2] = dtiDirMean(squeeze(vec(:,:,1,7)));
%   [T, DISTR, df] = dtiDirTest(Sbar, N, Sbar1);
%
% Reference:
%   A. Schwartzman, R. F. Dougherty, J. E. Taylor (2005),
%       "Cross-subject comparison of principal diffusion direction maps",
%       Magnetic Resonance in Medicine 53(6):1423-1431.
%
% Copyright by Armin Schwartzman, 2004

% HISTORY:
%   2004.06.23 ASH (armins@stanford.edu) wrote it.
%   2006.07.18 ASH added indexed format capability.
%   2006.07.25 ASH changed input parameters.

% Check inputs
if ~exist('N2'),
    N2 = 1;
end
if ((ndims(Sbar1)==2) & (ndims(Sbar2)==2)),
    Ind = 1;    % Data in indexed nx6 format
    Sbar1 = shiftdim(Sbar1, -2);
    Sbar2 = shiftdim(Sbar2, -2);
elseif ((ndims(Sbar1)==4) & (ndims(Sbar2)==4)),
    Ind = 0;    % Data in XxYxZx6 format
else
    error('Wrong input format');
end

% Constants
N  = N1 + N2;
p = 3;
DISTR = 'f';
df = [p-1, (p-1)*(N-2)];

Sbar = (N1 * Sbar1 + N2 * Sbar2)/(N1 + N2);
[vec1, val1] = dtiEig(Sbar1); % ndfun('eig', Sbar1);
[vec2, val2] = dtiEig(Sbar2); % ndfun('eig', Sbar2);
[vec, val] = dtiEig(Sbar); % ndfun('eig', Sbar);
M = vec(:,:,:,:,1);
S = (N - N1*val1(:,:,:,1) - N2*val2(:,:,:,1)) / (N-2);
T = (N1*val1(:,:,:,1) + N2*val2(:,:,:,1) - N*val(:,:,:,1)) ./ S;

% Adjust output
if Ind,
    T = shiftdim(T, 2);
    M = shiftdim(M, 2);
    S = shiftdim(S, 2);
end

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function create(obj,wrt)
% Create a NIFTI-1 file
% FORMAT create(obj)
% This writes out the header information for the nifti object
%
% create(obj,wrt)
% This also writes out an empty image volume if wrt==1
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

%
% $Id$

for i=1:numel(obj)
    create_each(obj(i));
end;

function create_each(obj)
if ~isa(obj.dat,'file_array'),
    error('Data must be a file-array');
end;
fname = obj.dat.fname;
if isempty(fname),
    error('No filename to write to.');
end;
dt = obj.dat.dtype;
ok = write_hdr_raw(fname,obj.hdr,dt(end-1)=='B');
if ~ok,
    error(['Unable to write header for "' fname '".']);
end;

write_extras(fname,obj.extras);

if nargin>2 && any(wrt==1),
    % Create an empty image file if necessary
    d   = findindict(obj.hdr.datatype, 'dtype');
    dim = double(obj.hdr.dim(2:end));
    dim((double(obj.hdr.dim(1))+1):end) = 1;
    nbytes = ceil(d.size*d.nelem*prod(dim(1:2)))*prod(dim(3:end))+double(obj.hdr.vox_offset);
    [pth,nam,ext] = fileparts(obj.dat.fname);

    if any(strcmp(deblank(obj.hdr.magic),{'n+1','nx1'})),
        ext = '.nii';
    else
        ext = '.img';
    end;
    iname = fullfile(pth,[nam ext]);
    fp    = fopen(iname,'a+');
    if fp==-1,
        error(['Unable to create image for "' fname '".']);
    end;

    fseek(fp,0,'eof');
    pos = ftell(fp);
    if pos<nbytes,
        bs      = 2048; % Buffer-size
        nbytes  = nbytes - pos;
        buf     = uint8(0);
        buf(bs) = 0;
        while(nbytes>0)
            if nbytes<bs, buf = buf(1:nbytes); end;
            nw = fwrite(fp,buf,'uint8');
            if nw<min(bs,nbytes),
                fclose(fp);
                error(['Problem while creating image for "' fname '".']);
            end;
            nbytes = nbytes - nw;
        end;
    end;
    fclose(fp);
end;

return;


text:
function err=geterror(dataname,traindataname)

load(dataname);
load (traindataname);

[numcases numdims numbatches]=size(batchdata);
N=numcases;
err=0;
for batch = 1:numbatches
  data = [batchdata(:,:,batch)];
  data = [data ones(N,1)];
  w1probs = 1./(1 + exp(-data*w1)); w1probs = [w1probs  ones(N,1)];
  w2probs = 1./(1 + exp(-w1probs*w2)); w2probs = [w2probs ones(N,1)];
  w3probs = 1./(1 + exp(-w2probs*w3)); w3probs = [w3probs  ones(N,1)];
  w4probs = w3probs*w4; w4probs = [w4probs  ones(N,1)];
  w5probs = 1./(1 + exp(-w4probs*w5)); w5probs = [w5probs  ones(N,1)];
  w6probs = 1./(1 + exp(-w5probs*w6)); w6probs = [w6probs  ones(N,1)];
  w7probs = 1./(1 + exp(-w6probs*w7)); w7probs = [w7probs  ones(N,1)];
  dataout = 1./(1 + exp(-w7probs*w8));
%   err=err+sum(sum(dataori.*dataout))/(sqrt(sum(sum(dataori.^2)))*sqrt(sum(sum(dataout.^2))));
  err = err +  1/N*sum(sum( (data(:,1:end-1)-dataout).^2 ));
end
 err=err/numbatches;
 fprintf(1,'squared error: %6.3f ,%s of %s \t \t \n',err, dataname, traindataname);

repo: DeepFi


text:
function [B, obj] = optimize_B(fft_r, fft_X, para)

%d = length(fft_r);

lambda = para.lambda;
fft_B = fft_X*diag(fft_r); % a N by d matrix
% fft(X) is column-wise fft fft(X,2) is row-wise fft
B_time = ifft(fft_B,[], 2);
B_time = real(B_time);
B = zeros(size(B_time));
B(B_time>=0) = 1;
B(B_time<0) = -1;
%B = B / sqrt(d); % Jan 22

if (para.bit < length(fft_r))
    B(:, para.bit+1:end) = B(:, para.bit+1:end).*0;
    B_time(:, para.bit+1:end) = B(:, para.bit+1:end);
end

obj = sum(sum((B-B_time).^2));
obj = obj + lambda*sum((real(fft_r).^2 + imag(fft_r).^2 - 1).^2);
end

author: willard-yuan

repo: hashing-baseline-for-image-retrieval


text:
function err_total = error_depth_list(param_dist,xcn_list,xpn_list,R,T,X_shape_list,ind_list);

N_view = length(ind_list);

err_total = [];

N_pts = zeros(1,N_view);

for kk = 1:N_view,

   xcn = xcn_list{kk};
   xpn = xpn_list{kk};
   ind = ind_list{kk};

   xpn = xpn([1 3],:);

   X_shape = X_shape_list{kk};

X_new = depth_compute(xcn,xpn,[param_dist],R,T);

N_pt_calib = size(xcn,2);

% UnNormalized shape extraction:

X_shape2 = X_new;
X_shape2 = X_shape2 - (X_shape2(:,1)*ones(1,N_pt_calib));

% map the second vector at [1;0;0]:

omu = -cross([1;0;0],X_shape2(:,2));
omu = acos((dot([1;0;0],X_shape2(:,2)))/norm(X_shape2(:,2)))*(omu / norm(omu));
Ru = rodrigues(omu);

X_shape2 = Ru* X_shape2;

omu2 = -cross([0;1;0],[0;X_shape2(2:3,ind)]);
omu2 = acos((dot([0;1;0],[0;X_shape2(2:3,ind)]))/norm([0;X_shape2(2:3,ind)]))*(omu2 / norm(omu2));
Ru2 = rodrigues(omu2);

X_shape2 = Ru2* X_shape2;

% Error:

err_shape = X_shape2(:,2:end) - X_shape(:,2:end);

err_shape = err_shape(:);

N_pts(kk) = N_pt_calib;

err_total = [ err_total ; err_shape ];

end;

%err_depth = Z_new - Z_ref;

repo: ekfmonoslam


text:
%% AMPL Install for OPTI Toolbox
% Supplied binaries are built from Netlib's AMPL Solver Library Interface

%   Copyright (C) 2011 Jonathan Currie (I2C2)

% This file will help you compile AMPL Solver Library (ASL) for use with
% MATLAB.

% My build platform:
% - Windows 8 x64
% - Visual Studio 2012

% 1) Get AMPL Solver Library
% The generic NL reader for AMPL is available free from Netlib
% (http://www.netlib.org/ampl/solvers/). You will need to download all .c
% and .h as well as .hd files. Note this is not the AMPL engine
% (www.ampl.com) which is a commerical product, but code to allow people to
% connect their solvers to AMPL. Alternatively send a blank email to
% "netlib@netlib.org" with "send all from ampl/solvers" as the subject to
% retrieve all files.

% 2) Compile ASL
% The easiest way to compile ASL is to use the Visual Studio Project
% Builder included with OPTI. Use the following commands, substituting the
% required path on your computer:

% %% Visual Studio Builder Commands
% path = 'full path to ASL here'; %e.g. 'C:\Solvers\ASL'
% sdir = path;
% name = 'libasl';
% opts = [];
% opts.exPP = {'Arith_Kind_ASL=1','Sscanf=sscanf','Printf=printf','Sprintf=sprintf',...
%              'Fprintf=fprintf','snprintf=_snprintf','NO_STDIO1','_CRT_SECURE_NO_WARNINGS','_CRT_NONSTDC_NO_DEPRECATE'};
% opts.exclude = {'arithchk.c','atof.c','b_search.c','dtoa.c','fpinit.c','funcadd.c',...
%                 'funcadd0.c','funcaddk.c','funcaddr.c','obj_adj0.c','sjac0dim.c',...
%                 'sprintf.c','sscanf.c','printf.c','mpec_adj0.c'};
% opts.charset = 'MultiByte';
% VS_WriteProj(sdir,name,[],opts)
% %%

% Once complete, you will have a directory called ASL\libasl. Open the
% Visual Studio 2012 project file, then complete the following steps:
%   a) Rename arith.h0 to arith.h, and uncomment the define "IEEE_8087"
%   b) Rename stdio1.h0 to stdio1.h
%   c) Under project properties change the character set to "Use
%   Multi-Byte Character Set" (both Win32 and x64 as required).
%   d) Comment out the line "exit(n)" in mainexit.c (this stops MATLAB
%   crashing on an ASL error) [line 62]
%   e) To prevent Matlab crashing on a bad NL file comment all code under
%   the if(n_con < 0 || ...) statement on line 260 in jac0dim.c. Add return
%   NULL; so instead of exiting, our MEX file can determine this as a bad file.
%   f) Comment line 900 in asl.h (extern int Sprintf(char*, ....)
%   g) Comment line 36 in jac0dim.c (extern int Sscanf(char*, ...)
%   h) Comment line 56 in stderr.c (AllocConsole();)
%   i) Build a Win32 or x64 Release to compile the code.
%   j) Copy the generated .lib file to the following folder:
%
%   OPTI/Utilities/File IO/Source/lib/win32 or win64
%
%   Also copy all header files to the include directory as per the above
%   path.

% 3) MEX Interface
% The Read MEX Interface is a simple MEX interface I wrote to use the AMPL
% File IO and Eval routines.

% 4) Compile the MEX File
% The code below will automatically include all required libraries and
% directories to build the MEX file. Once you have completed all
% the above steps, simply run this file to compile! You MUST BE in
% the base directory of OPTI!

clear asl

% Get Arch Dependent Library Path
libdir = opti_GetLibPath();

fprintf('\n------------------------------------------------\n');
fprintf('AMPL MEX FILE INSTALL\n\n');

post = [' -IInclude -L' libdir ' -llibasl -DNO_STDIO1 -output asl'];

%CD to Source Directory
cdir = cd;
cd 'Utilities/File IO/Source';

%Compile & Move
pre = 'mex -v -largeArrayDims amplmex.c';
try
    eval([pre post])
     movefile(['asl.' mexext],'../','f')
    fprintf('Done!\n');
catch ME
    cd(cdir);
    error('opti:ampl','Error Compiling AMPL!\n%s',ME.message);
end
cd(cdir);
fprintf('------------------------------------------------\n');

author: vigente

repo: gerardus

save_path: github-repos/MATLAB/vigente-gerardus


text:
clear;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% indicate the super-resolution factor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
down_factor = 3;    % 2, 3 or 4
image_path = 'data/deepeaf/BSDS500/';
data_chs = 1;   % 1 or 3
training_mat_path = 'data/Shepard_CNN/Shepard_super_res/x3/train_1ch/';
val_mat_path = 'data/Shepard_CNN/Shepard_super_res/x3/val_1ch/';

patch_dim = 48;
num_patches = 20000;
listing = dir(strcat(image_path, '*.jpg'));
mat_num = 51;
for m = 1 : mat_num
    fprintf('Extracting patch batch: %d / %d\n', m, mat_num);
    % extract random patches
    images = zeros(patch_dim, patch_dim, data_chs, num_patches);
    labels = zeros(size(images));
    for i = 1 : num_patches
        if (mod(i,100) == 0)
            fprintf('Extracting patch: %d / %d\n', i, num_patches);
        end

        r_idx = random('unid', size(listing, 1));
        I = im2double(imread(strcat(image_path, listing(r_idx).name)));
        orig_img_size = size(I);
        r = random('unid', orig_img_size(1) - patch_dim + 1);
        c = random('unid', orig_img_size(2) - patch_dim + 1);

        patch = I(r:r+patch_dim-1, c:c+patch_dim-1, :);

        if(data_chs == 1)
            patch = rgb2ycbcr(patch);
            patch = patch(:,:,1);
        end

        patch_down = imresize(patch, [patch_dim/down_factor, patch_dim/down_factor], 'bicubic');
        patch_up = imresize(patch_down, [patch_dim, patch_dim], 'nearest');
        images(:,:,:,i) = patch_up;
        labels(:,:,:,i) = patch;
        %imshow([patch_up patch]); pause;
    end
    % save it
    images = single(images);
    labels = single(labels);

    if(m >= mat_num)
        % save validation data
        filename = strcat(val_mat_path, 'val_1');
        images_t = images;
        labels_t = labels;
        save(filename, '-v7.3', 'images_t', 'labels_t');
    else
        % save training data
        filename = strcat(training_mat_path, 'patches_', num2str(m));
        save(filename, '-v7.3', 'images', 'labels');
    end
end

author: jimmy-ren


text:
function result = TLDA_test_LR(traindata, testdata, trainlabel, testlabel)
    %% use the model test the target domain data
    tempTrainXY = scale_cols(traindata, trainlabel);

    % train the classifier
    c00 = zeros(size(tempTrainXY,1),1);
    lambdaLG = exp(linspace(-0.5,6,20));
    wbest=c00;
    f1max = -inf;
    for j = 1 : length(lambdaLG)
        c_0 = train_cg(tempTrainXY,c00,lambdaLG(j));
        f1 = logProb(tempTrainXY,c_0);
        if f1 > f1max
            f1max = f1;
            wbest = c_0;
        end
    end
    C = wbest;

    result = zeros(1,2);
    % test the train data
    probability = 1./(1+1./(exp(C'*traindata)));
    probability(probability >= 0.5) = 1;
    probability(probability < 0.5) = -1;
    result(1,1) = mean(probability(:) == trainlabel(:));

    % test the test data
    probability = 1./(1+1./(exp(C'*testdata)));
    probability(probability >= 0.5) = 1;
    probability(probability < 0.5) = -1;
    result(1,2) = mean(probability(:) == testlabel(:));

author: FuzhenZhuang

repo: Transfer-Learning-Toolkit


text:
% std_selectdataset() - select datasets and trials for a given independent
%                       variable with a given set of values.
%
% Usage:
%   >> [STUDY] = std_selectdataset(STUDY, ALLEEG, indvar, indvarvals);
%
% Inputs:
%   STUDY       - EELAB STUDY structure
%   ALLEEG      - EELAB dataset structure
%   indvar      - [string] independent variable name
%   indvarvals  - [cell] cell array of string for selected values for the
%   verboseflag - ['verbose'|'silent'] print info flag
%
%                choosen independent variable
% Output:
%   datind       - [integer array] indices of selected dataset
%   dattrialsind - [cell] trial indices for each dataset (not only the
%                  datasets selected above).
%
% Author: Arnaud Delorme, CERCO, 2010-

% Copyright (C) Arnaud Delorme, arno@salk.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program 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 General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function [datind, dattrialselect] = std_selectdataset(STUDY, ALLEEG, indvar, indvarvals, verboseFlag);

if nargin < 3
    help std_selectdataset;
    return;
end;
if nargin < 5
    verboseFlag = 'verbose';
end;

% check for multiple condition selection
if ~iscell(indvarvals),
    pos = strfind(' - ', indvarvals);
    if ~isempty(pos)
        tmpindvar = indvarvals;
        indvarvals = { indvarvals(1:pos(1)-1) };
        pos(end+1) = length(tmpindvar)+1;
        for ind = 1:length(pos)-1
            indvarvals{end+1} = tmpindvar(pos(ind)+3:pos(ind+1)-1);
        end;
    else
        indvarvals = { indvarvals };
    end;
end;

% default dattrialselect = all trials
% -----------------------------------
if isfield(STUDY.datasetinfo, 'trialinfo')
     dattrialselect = cellfun(@(x)([1:length(x)]), { STUDY.datasetinfo.trialinfo }, 'uniformoutput', false);
else for i=1:length(ALLEEG), dattrialselect{i} = [1:ALLEEG(i).trials]; end;
end;

if isempty(indvar)
    datind = [1:length(STUDY.datasetinfo)];
elseif isfield(STUDY.datasetinfo, indvar) && ~isempty(getfield(STUDY.datasetinfo(1), indvar))
    % regular selection of dataset in datasetinfo
    % -------------------------------------------
    if strcmpi(verboseFlag, 'verbose'), fprintf('   Selecting datasets with field ''%s'' equal to %s\n', indvar, vararg2str(indvarvals)); end;
    eval( [ 'myfieldvals = { STUDY.datasetinfo.' indvar '};' ] );
    datind = [];
    for dat = 1:length(indvarvals)
        datind = union_bc(datind, std_indvarmatch(indvarvals{dat}, myfieldvals));
    end;
else
    % selection of trials within datasets
    % -----------------------------------
    if strcmpi(verboseFlag, 'verbose'), fprintf('   Selecting trials with field ''%s'' equal to %s\n', indvar, vararg2str(indvarvals)); end;
    dattrials      = cellfun(@(x)(eval(['{ x.' indvar '}'])),  { STUDY.datasetinfo.trialinfo }, 'uniformoutput', false);
    dattrials      = cellfun(@(x)(eval(['{ x.' indvar '}'])),  { STUDY.datasetinfo.trialinfo }, 'uniformoutput', false); % do not remove duplicate line (or Matlab crashes)
    dattrialselect = cell(1,length(STUDY.datasetinfo));
    for dat = 1:length(indvarvals)
        for tmpi = 1:length(dattrials)
            dattrialselect{tmpi} = union_bc(dattrialselect{tmpi}, std_indvarmatch(indvarvals{dat}, dattrials{tmpi}));
        end;
    end;
    datind = find(~cellfun(@isempty, dattrialselect));
end;

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
function [im,header] = ufmf_read_mean(header,varargin)

[meani,framei,dopermute] = myparse(varargin,'meani',[],'framei',[],'dopermute',true);
fp = header.fid;

meani = [meani,header.frame2mean(framei)];

if isempty(meani),
  [im,header] = ufmf_read_mean_helper(fp,header);
else
  if length(meani) > 1,
    im = zeros([header.ncolors,header.nr,header.nc,length(meani)],header.meandataclass);
  end
  if isfield(header,'cachedmeans_idx'),
    [idx,cachei] = ismember(meani,header.cachedmeans_idx);
  else
    idx = false(size(meani));
  end
  for i = find(idx),
    im(:,:,:,i) = header.cachedmeans(:,:,:,cachei(i));
    header.cachedmeans_accesstime(i) = now;
  end
  for i = find(~idx),
    fseek(fp,header.mean2file(meani(i)),'bof');
    [im(:,:,:,i),header] = ufmf_read_mean_helper(fp,header);
  end
end
if dopermute,
  im = permute(im,[2,3,1,4]);
end

function [im,header,timestamp] = ufmf_read_mean_helper(fp,header)

% Keyframe file format:
%
% 0 (chunk type)                       uchar
% 4 (length of keyframe type)          uchar
% 'mean' (keyframe type)               char x 4
% timestamp                            double
% number of boxes/points               ushort
% dtype ('f' for float, 'B' for uint8) char
% width                                ushort
% height                               ushort
% timestamp                            double
% background mean                      dtype x width x height x ncolors
% (iterate over colors,
%  followed by columns in sideways im,
%  followed by rows)

KEYFRAME_CHUNK = 0;
MEAN_KEYFRAME_TYPE = 'mean';

loc = ftell(fp);
meani = find(header.mean2file == loc,1);
if isempty(meani),
  error('Could not find current file location in mean2file index');
end

% chunktype: 1
chunktype = fread(fp,1,'uchar');
if chunktype ~= KEYFRAME_CHUNK,
  error('Expected chunktype = %d at start of keyframe.');
end

% keyframe type
l = fread(fp,1,'uchar');
keyframe_type = fread(fp,[1,l],'*char');
if ~strcmp(keyframe_type,MEAN_KEYFRAME_TYPE),
  error('Expected keyframe type = ''%s'' at start of mean keyframe',MEAN_KEYFRAME_TYPE);
end

% data type
dtypechar = fread(fp,1,'*char');
matlabclass = dtypechar2matlabclass(dtypechar);

% images are sideways: swap width and height
% width, height
sz = double(fread(fp,2,'ushort'));
height = sz(1); width = sz(2);

% timestamp
timestamp = fread(fp,1,'double');

% actual frame data
im = fread(fp,width*height*header.bytes_per_pixel,['*',matlabclass]);
% TODO: handle colorspaces other than RGB8 and MONO8
if ~ismember(lower(header.coding),{'mono8','rgb8'}),
  error('Colorspace %s not yet supported. Only MONO8 and RGB8 allowed.',header.coding);
end
im = reshape(im,[header.ncolors,height,width]);

% store in cache
if isfield(header,'cachedmeans'),
  [~,idxreplace] = min(header.cachedmeans_accesstime);
  header.cachedmeans(:,:,:,idxreplace) = im;
  header.cachedmeans_idx(idxreplace) = meani;
  header.cachedmeans_accesstime(idxreplace) = now;
end

author: kristinbranson

repo: JAABA


text:
function msk=get_lines_executable(obj)
% get a mask indicating which lines are executable
%
% msk=get_lines_executable(obj)
%
% Input:
%   obj                 MOcovMFile instance
%
% Output:
%   msk                 Nx1 logical mask, with msk(k)==true indicating
%                       that the k-th line can be exectued

    msk=obj.executable;

author: qMRLab

repo: qMRLab

save_path: github-repos/MATLAB/qMRLab-qMRLab


text:
function plot_att(matlab_time,matlab_att, mcu_time,mcu_att, sins_time,sins_att, bl_time,bl_att)
%姿态与航向估计曲线
    for i=2:2:nargin
        if i==2
%             matlab_time = matlab_time/60;
            figure('name', '姿态与航向估计曲线');
            subplot(3,1,1);
            plot(matlab_time, matlab_att(:,1), 'b', 'linewidth', 1.5); hold on; grid on;
            xlim([matlab_time(1) matlab_time(end)]);
            ylim([-20 20]);
            ylabel('Pitch(°)'); legend('MATLAB', 'Orientation','horizontal');
            subplot(3,1,2);
            plot(matlab_time, matlab_att(:,2), 'b', 'linewidth', 1.5); hold on; grid on;
            xlim([matlab_time(1) matlab_time(end)]);
            ylim([-20 20]);
            ylabel('Roll(°)'); legend('MATLAB', 'Orientation','horizontal');
            subplot(3,1,3);
            plot(matlab_time, matlab_att(:,3), 'b', 'linewidth', 1.5); hold on; grid on;
            legend('MATLAB', 'Orientation','horizontal');
            xlim([matlab_time(1) matlab_time(end)]);
            ylim([-30 420]);
            yticks(0:45:360);
            xlabel('时间(s)'); ylabel('Yaw(°)');
        elseif i==4
%             mcu_time = mcu_time/60;
            subplot(3,1,1);
            plot(mcu_time, mcu_att(:,1), 'm', 'linewidth', 1.5);
            legend('MATLAB', 'MCU', 'Orientation','horizontal');
            subplot(3,1,2);
            plot(mcu_time, mcu_att(:,2), 'm', 'linewidth', 1.5);
            legend('MATLAB', 'MCU', 'Orientation','horizontal');
            subplot(3,1,3);
            plot(mcu_time, mcu_att(:,3), 'm', 'linewidth', 1.5);
            legend('MATLAB', 'MCU', 'Orientation','horizontal');
        elseif i==6
%             sins_time = sins_time/60;
            subplot(3,1,1);
            plot(sins_time, sins_att(:,1), 'r', 'linewidth', 1.5);
            legend('MATLAB', 'MCU', '纯惯性', 'Orientation','horizontal');
            subplot(3,1,2);
            plot(sins_time, sins_att(:,2), 'r', 'linewidth', 1.5);
            legend('MATLAB', 'MCU', '纯惯性', 'Orientation','horizontal');
            subplot(3,1,3);
            plot(sins_time, sins_att(:,3), 'r', 'linewidth', 1.5);
            legend('MATLAB', 'MCU', '纯惯性', 'Orientation','horizontal');
        elseif i==8
%             bl_time = bl_time/60;
            subplot(3,1,1);
            plot(bl_time, bl_att(:,1), 'g', 'linewidth', 1.5);
            legend('MATLAB', 'MCU', '纯惯性', '双天线','Orientation','horizontal');
            subplot(3,1,3);
            plot(bl_time, bl_att(:,2), 'g', 'linewidth', 1.5);
            legend('MATLAB', 'MCU', '纯惯性', '双天线','Orientation','horizontal');
        end
    end

    sgtitle('姿态与航向估计曲线');
    set(gcf, 'Units', 'normalized', 'Position', [0.025, 0.05, 0.95, 0.85]);
end

author: yandld