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

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

% Last Modified by GUIDE v2.5 19-Feb-2013 00:02:42

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

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

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

% Choose default command line output for gui_causalBrainMovie3D_online
handles.output = hObject;
handles.gcf    = hObject;
set(hObject,'Name','BrainMovie3D Control Panel');
% set default termination behavior
handles.ExitButtonClicked = 'Cancel';

% extract some data from command-line input
if isempty(varargin)
    error('You must pass ALLEEG and Conn to gui_CausalBrainMovie3D');
end

% Extract input parameters/data and store
handles.ud.ALLEEG  = varargin{1};
handles.ud.Conn    = varargin{2};
varargin([1 2]) = [];

% set default EEGLAB background and text colors
%-----------------------------------------------
try, icadefs;
catch,
	GUIBACKCOLOR        =  [.8 .8 .8];
	GUIPOPBUTTONCOLOR   = [.8 .8 .8];
	GUITEXTCOLOR        = [0 0 0];
end;

allhandlers = hObject;

hh = findobj(allhandlers,'style', 'text');
%set(hh, 'BackgroundColor', get(hObject, 'color'), 'horizontalalignment', 'left');
set(hh, 'Backgroundcolor', GUIBACKCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
set(hObject, 'color',GUIBACKCOLOR );
% set(hh, 'horizontalalignment', g.horizontalalignment);

hh = findobj(allhandlers, 'style', 'edit');
set(hh, 'BackgroundColor', [1 1 1]); %, 'horizontalalignment', 'right');

hh =findobj(allhandlers, 'parent', hObject, 'style', 'pushbutton');
if ~strcmpi(computer, 'MAC') && ~strcmpi(computer, 'MACI') % this puts the wrong background on macs
    set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
    set(hh, 'foregroundcolor', GUITEXTCOLOR);
end;
hh =findobj(allhandlers, 'parent', hObject, 'style', 'popupmenu');
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh =findobj(allhandlers, 'parent', hObject, 'style', 'checkbox');
set(hh, 'backgroundcolor', GUIBACKCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh =findobj(allhandlers, 'parent', hObject, 'style', 'listbox');
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh =findobj(allhandlers, 'parent', hObject, 'style', 'radio');
set(hh, 'foregroundcolor', GUITEXTCOLOR);
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(hObject, 'visible', 'on');

set(handles.pnlPropertyGrid,'backgroundcolor', GUIBACKCOLOR);
set(handles.pnlPropertyGrid,'foregroundcolor', GUITEXTCOLOR);

%-----------------------------------------------

drawnow

% render the PropertyGrid in the correct panel
handles.PropertyGridHandle = arg_guipanel( ...
                 handles.pnlPropertyGrid, ...
                'Function',@vis_causalBrainMovie3D, ...
                'params',{'ALLEEG',handles.ud.ALLEEG, 'Conn',handles.ud.Conn, varargin{:}});

handles.BrainMovieFigure = [];
handles.figureHandle = hObject;

% Update handles structure
guidata(hObject, handles);

% Wait for user to click OK, Cancel or close figure
% uiwait(handles.gui_BrainMovie3D);

% UIWAIT makes gui_causalBrainMovie3D_online wait for user response (see UIRESUME)
% uiwait(handles.gui_BrainMovie3D);

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

varargout = {hObject};

% --- Executes on button press in cmdCancel.
function cmdCancel_Callback(hObject, eventdata, handles)

if isempty(handles)
    % user closed the figure
    varargout = {[] hObject};
% elseif strcmpi(handles.ExitButtonClicked,'OK')
%     % user clicked OK
%     % get PropertySpecification
%     varargout = {handles.PropertyGridHandle handles.output};
else
    % user clicked cancel
    varargout = {[] handles.output};
end

evalin('base','opts.miscOptCfg.doSIFT.dispBrainMovie.arg_selection=false;');
% evalin('base','if ishandle(figHandles.BMDisplay), close(figHandles.BMDisplay); end');

try
    close(handles.figureHandle);
catch
end

% --- Executes on button press in cmdOK.
function cmdOK_Callback(hObject, eventdata, handles)

% handles.ExitButtonClicked ='OK';
% get the property specification
pg = handles.PropertyGridHandle;
ps = pg.GetPropertySpecification;
cfg = arg_tovals(ps,false);
assignin('base','BMCFG',cfg);
assignin('base','BM_CFG_CHANGED',true);
set(handles.gcf,'UserData','newBrainmovie');
% guidata(hObject,handles);
% uiresume(handles.gui_BrainMovie3D);

% % --- Executes on slider movement.
% function slideCurTime_Callback(hObject, eventdata, handles)
%
% % get the PropertyGrid object
% % ud = get(handles.gui_BrainMovie3D,'UserData');
% % if isempty(ud)
% %     error('Could not obtain handle to PropertyGrid! Did you pass it to the UserData of the figure?');
% % end
%
% % get the property specification
% pg = handles.PropertyGridHandle;
% ps = pg.GetPropertySpecification;
% cfg = arg_tovals(ps,false);
%
% if isempty(cfg)
%     error('could not retrieve property specification from propertygrid');
% end
%
% % get the index of the frame the user wants to render
% range = get(hObject,'max')-get(hObject,'min');
% curframe = round(get(hObject,'Value'));
%
% % update the curTime textbox
% set(handles.txtCurTime,'string',handles.ud.Conn(1).erWinCenterTimes(curframe));
%
% minTime = str2num(get(handles.txtMinTime,'String'));
% maxTime = str2num(get(handles.txtMaxTime,'String'));
%
% figh = handles.BrainMovieFigure; %findobj('tag','BrainMovieFigure');
% try figure(figh)
% catch
%     figh = [];
% end
% curpos = get(findobj(figh,'tag','brain'),'CameraPosition');
% % execute the brainmovie function to render this frame
% vis_causalBrainMovie3D('ALLEEG',handles.ud.ALLEEG,'Conn',handles.ud.Conn,cfg,'MovieTimeRange',[minTime maxTime],'BrainMovieOptions',{cfg.BMopts,'visible','off','FigureHandle',figh,'LatenciesToRender',[],'FramesToRender',curframe,'outputFormat',{'framefolder','','moviename',''}});
% figh = gcf;
% set(findobj(figh,'tag','brain'),'CameraPosition',curpos);
% set(gcf,'visible','on')
% handles.BrainMovieFigure = gcf;
% guidata(hObject,handles);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ADDITIONAL CALLBACKS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% % --- Executes during object creation, after setting all properties.
% function slideCurTime_CreateFcn(hObject, eventdata, handles)
%
%
% % Hint: slider controls usually have a light gray background.
% if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
%     set(hObject,'BackgroundColor',[.9 .9 .9]);
% end

% --- Executes during object deletion, before destroying properties.
function cmdOK_DeleteFcn(hObject, eventdata, handles)
% hObject    handle to cmdOK (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%
% % --- Executes on button press in cmdHelp.
% function cmdHelp_Callback(hObject, eventdata, handles)
% % hObject    handle to cmdHelp (see GCBO)
% % eventdata  reserved - to be defined in a future version of MATLAB
% % handles    structure with handles and user data (see GUIDATA)
%
% warndlg2('Coming soon!');

% --- Executes on key press with focus on gui_BrainMovie3D or any of its controls.
function gui_BrainMovie3D_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to gui_BrainMovie3D (see GCBO)
% eventdata  structure with the following fields (see FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)

% hObject    handle to gui_BrainMovie3D (see GCBO)
% eventdata  structure with the following fields (see FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)

% if strcmpi(eventdata.Key,'s') ...
%         && (strcmpi(eventdata.Modifier,'control') ...
%         || strcmpi(eventdata.Modifier,'command'))
%
%
%     % get current contents of property grid
%     pg    = handles.PropertyGridHandle;
%     ps    = pg.GetPropertySpecification;
%     BMCFG = arg_tovals(ps,false);
%
%     % select the path/file for saving configs
%     [fname fpath] = uiputfile('*.mat','Save BrainMovie Config File');
%     if ~fname
%         return;
%     end
%     % save the opts structure
%     save(fullfile(fpath,fname),'BMCFG');
%
%
% %     varname = inputdlg2({'Enter name of variable in workspace to store configuration'}, ...
% %                         'Save GUI configuration to workspace',1,{''});
% %
% %     if isempty(varname)
% %         return;
% %     end
% %
% %     % get the property specification
% %     pg = handles.PropertyGridHandle;
% %     ps = pg.GetPropertySpecification;
% %     cfg = arg_tovals(ps,false);
% %
% %     % save configuration structure to workspace
% %     assignin('base',varname{1},cfg);
% end
%
% % load configuration
% if strcmpi(eventdata.Key,'l') ...
%         && (strcmpi(eventdata.Modifier,'control') ...
%         || strcmpi(eventdata.Modifier,'command'))
%
%     % load the configs
%     [fname fpath] = uigetfile('*.mat','Load BrainMovie Config File');
%     if ~fname
%         return;
%     end
%     tmp   = load(fullfile(fpath,fname));
%     fn    = fieldnames(tmp);
%     BMCFG = tmp.(fn{1});
%
%     % pause the brainmovie rendering
%     evalin('base','opts.miscOptCfg.doSIFT.dispBrainMovie.arg_selection=false;');
%
%     % close existing brainmovie figure
%     evalin('base','close(figHandles.BMDisplay);  figHandles.BMDisplay = [];');
%     % update configs in base workspace
%     assignin('base','BMCFG',BMCFG);
%     assignin('base','BM_CFG_CHANGED',true);
%     assignin('base','newBrainmovie',true);
%     % close the BrainMovie control panel (a new one will be opened)
%     close(hObject);
%     % resume the brainmovie rendering
%     evalin('base','opts.miscOptCfg.doSIFT.dispBrainMovie.arg_selection=true;');
%
% %     % pause the brainmovie rendering
% %     evalin('base','opts.miscOptCfg.doSIFT.dispBrainMovie.arg_selection=false;');
% %     % redraw the property grids
% %     handles = redrawPropertyGrid(hObject,handles,BMCFG);
% %     % close existing brainmovie figure
% %     evalin('base','close(figHandles.BMDisplay);  figHandles.BMDisplay = [];');
% %     % update configs in base workspace
% %     assignin('base','BMCFG',BMCFG);
% %     assignin('base','BM_CFG_CHANGED',true);
% %     % resume the brainmovie rendering
% %     evalin('base','opts.miscOptCfg.doSIFT.dispBrainMovie.arg_selection=true;');
%
%     guidata(hObject,handles);
% end

% --- User-defined function to (re)draw Property Grids
function handles = redrawPropertyGrid(hObject,handles,BMCFG)

try
    % delete existing property grids
    delete(handles.PropertyGridHandle.Control);
catch err
end

% render the PropertyGrid in the correct panel
handles.PropertyGridHandle = arg_guipanel( ...
                 handles.pnlPropertyGrid, ...
                'Function',@vis_causalBrainMovie3D, ...
                'params',{'ALLEEG',handles.ud.ALLEEG, 'Conn',handles.ud.Conn, BMCFG});

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

% pause the brainmovie
% pause the brainmovie
if strcmpi(get(hObject,'String'),'pause');
    doBrainMovie = false;
    set(hObject,'String','Unpause');
else
    doBrainMovie = true;
    set(hObject,'String','Pause');
end

evalin('base',sprintf('opts.miscOptCfg.doSIFT.dispBrainMovie.arg_selection=%s;',fastif(doBrainMovie,'true','false')));
guidata(hObject,handles);

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

% load the configs
[fname fpath] = uigetfile('*.mat','Load BrainMovie Config File');
if ~fname
    return;
end
tmp   = load(fullfile(fpath,fname));
fn    = fieldnames(tmp);
BMCFG = tmp.(fn{1});

if ~isstruct(BMCFG) || ~isfield(BMCFG,'BMopts')
    fprintf('Invalid BrainMovie Config\n');
    return;
end

% pause the brainmovie rendering
evalin('base','opts.miscOptCfg.doSIFT.dispBrainMovie.arg_selection=false;');

% close existing brainmovie figure
evalin('base','close(figHandles.BMDisplay);  figHandles.BMDisplay = [];');
% update configs in base workspace
assignin('base','BMCFG',BMCFG);
assignin('base','BM_CFG_CHANGED',true);
assignin('base','newBrainmovie',true);
% close the BrainMovie control panel (a new one will be opened)
close(handles.figureHandle);
% resume the brainmovie rendering
evalin('base','opts.miscOptCfg.doSIFT.dispBrainMovie.arg_selection=true;');

%     % pause the brainmovie rendering
%     evalin('base','opts.miscOptCfg.doSIFT.dispBrainMovie.arg_selection=false;');
%     % redraw the property grids
%     handles = redrawPropertyGrid(hObject,handles,BMCFG);
%     % close existing brainmovie figure
%     evalin('base','close(figHandles.BMDisplay);  figHandles.BMDisplay = [];');
%     % update configs in base workspace
%     assignin('base','BMCFG',BMCFG);
%     assignin('base','BM_CFG_CHANGED',true);
%     % resume the brainmovie rendering
%     evalin('base','opts.miscOptCfg.doSIFT.dispBrainMovie.arg_selection=true;');

guidata(handles.figureHandle,handles);

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

% get current contents of property grid
pg    = handles.PropertyGridHandle;
ps    = pg.GetPropertySpecification;
BMCFG = arg_tovals(ps,false);

% select the path/file for saving configs
[fname fpath] = uiputfile('*.mat','Save BrainMovie Config File');
if ~fname
    return;
end
% save the opts structure
save(fullfile(fpath,fname),'BMCFG');

%     varname = inputdlg2({'Enter name of variable in workspace to store configuration'}, ...
%                         'Save GUI configuration to workspace',1,{''});
%
%     if isempty(varname)
%         return;
%     end
%
%     % get the property specification
%     pg = handles.PropertyGridHandle;
%     ps = pg.GetPropertySpecification;
%     cfg = arg_tovals(ps,false);
%
%     % save configuration structure to workspace
%     assignin('base',varname{1},cfg);

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

repo: REST


text:
function Cmatrix = correlation_3d_to_2d(C)
% Turn an k x k x n matrix of correlations into a 2-d flat matrix
%
% Cmatrix = correlation_3d_to_2d(C)
%
% C = [k x k x n],  each [k x k] matrix is inter-variable correlation
% matrix, one correlation matrix for each of n replicates.

% get data for prediction
%-----------------------------------

[j, k, n] = size(C);

if j ~= k, error('Not a series of correlation matrices'); end

E = eye(j);

nout = j * (j - 1) ./ 2;
Cmatrix = zeros(n, nout);

for i = 1:n

    Cmatrix(i, :) = squareform(C(:, :, i) - E);

end

end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
% VL_IHASHFIND
%  SEL = VL_IHASHFIND(ID, NEXT, K, X)

author: jianxiongxiao

repo: ProfXkit


text:
function varargout = process_ft_channelrepair( varargin )
% PROCESS_FT_CHANNELREPAIR: Call FieldTrip function ft_channelrepair.
% Replace bad channels with interpolations of neighboring values.

% @=============================================================================
% 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.
% =============================================================================@
%
% Authors: Roey Schurr, Francois Tadel, 2015

eval(macro_method);
end

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
    % Description the process
    sProcess.Comment     = 'FieldTrip: ft_channelrepair';
    sProcess.Category    = 'File';
    sProcess.SubGroup    = 'Standardize';
    sProcess.Index       = 309;
    sProcess.Description = 'http://www.fieldtriptoolbox.org/reference/ft_channelrepair';
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'data'};
    sProcess.OutputTypes = {'data'};
    sProcess.nInputs     = 1;
    sProcess.nMinFiles   = 1;

    % Definition of the options
    % === INTEPROLATION METHOD
    sProcess.options.warning.Comment = ['Note that you cannot indicate the bad channels here,
' ...
                                        'you need to mark them from the interface before.

' ...
                                        'Interpolation method:'];
    sProcess.options.warning.Type    = 'label';
    sProcess.options.method.Comment = {'Nearest: Neighbours weighted by distance', 'Average: Mean of all neighbours', 'Spline: Spherical spline', 'Slap: Surface Laplacian'};
    sProcess.options.method.Type    = 'radio';
    sProcess.options.method.Value   = 1;
    % === MAXIMAL DISTANCE BETWEEN NEIGHBOURS
    sProcess.options.maxdist.Comment = 'Maximal distance between neighbours: ';
    sProcess.options.maxdist.Type    = 'value';
    sProcess.options.maxdist.Value   = {4, 'cm', 1};
    % === SENSOR TYPES
    sProcess.options.sensortypes.Comment = 'Sensor types (empty=all): ';
    sProcess.options.sensortypes.Type    = 'text';
    sProcess.options.sensortypes.Value   = 'EEG';
end

%% ===== FORMAT COMMENT =====
function Comment = FormatComment(sProcess) %#ok<DEFNU>
     Comment = sProcess.Comment;
end

%% ===== RUN =====
function OutputFiles = Run(sProcess, sInput) %#ok<DEFNU>
    % Initialize returned list of files
    OutputFiles = {};
    % Initialize FieldTrip
    [isInstalled, errMsg] = bst_plugin('Install', 'fieldtrip');
    if ~isInstalled
        bst_report('Error', sProcess, [], errMsg);
        return;
    end
    bst_plugin('SetProgressLogo', 'fieldtrip');
    % Get option values
    MaxDist = sProcess.options.maxdist.Value{1} / 100;   % Convert from centimeters to meters
    SensorTypes = sProcess.options.sensortypes.Value;
    switch (sProcess.options.method.Value)
        case 1,    Method  = 'nearest';   % replacs the electrode with the average of its neighbours weighted by distance
        case 2,    Method  = 'average';
        case 3,    Method  = 'spline';
        case 4,    Method  = 'slap';
        otherwise, error('Invalid method');
    end

    % ===== LOAD DATA =====
    % Convert to FieldTrip structures
    [ftData, DataMat, ChannelMat] = out_fieldtrip_data(sInput.FileName, sInput.ChannelFile, SensorTypes, 0);

    % ===== FIND NEIGHBORS =====
    % Prepare structure of neighbouring electrodes
    neicfg = struct();
    neicfg.method        = 'distance';
    neicfg.neighbourdist = MaxDist;
    if isfield(ftData, 'elec')
        neicfg.elec = ftData.elec;
    end
    if isfield(ftData, 'grad')
        neicfg.grad = ftData.grad;
    end
    neighbours = ft_prepare_neighbours(neicfg);

    % ===== INTERPOLATE CHANNELS =====
    % Find bad channels
    iBadChan = find(DataMat.ChannelFlag == -1);
    badchannel = {ChannelMat.Channel(iBadChan).Name};
    % Preprare structure
    intcfg = struct();
    intcfg.neighbours = neighbours;
    intcfg.method     = Method;
    intcfg.badchannel = badchannel';
    intcfg.trials     = 1;
    interpolatedData = ft_channelrepair(intcfg, ftData);

    % ===== GET RESULTS =====
    % Get indices of the channels that were updated
    [tmp,I,J] = intersect({ChannelMat.Channel(iBadChan).Name}, ftData.label);
    % Replace interpolated channels
    DataMat.F(iBadChan(I),:) = interpolatedData.trial{1}(J,:);
    % Set those channels as good
    DataMat.ChannelFlag(iBadChan(I),:) = 1;
    % Add history comment
    DataMat = bst_history('add', DataMat, 'interpbad', ['Replaced bad channels with method "' Method '" (' num2str(MaxDist*100) 'cm): ' sprintf('%s ', intcfg.badchannel{:})]);
    if isfield(interpolatedData, 'cfg') && isfield(interpolatedData.cfg, 'version')
        DataMat = bst_history('add', DataMat, 'fieldtrip', interpolatedData.cfg.version.name);
        DataMat = bst_history('add', DataMat, 'fieldtrip', interpolatedData.cfg.version.id);
    end
    % Add comment tag
    DataMat.Comment = [DataMat.Comment ' | interpbad'];

    % ===== SAVE THE RESULTS =====
    % Create output filename
    [fPath, fBase, fExt] = bst_fileparts(file_fullpath(sInput.FileName));
    OutputFiles{1} = file_unique(bst_fullfile(fPath, [fBase '_interpbad', fExt]));
    % Save on disk
    bst_save(OutputFiles{1}, DataMat, 'v6');
    % Register in database
    db_add_data(sInput.iStudy, OutputFiles{1}, DataMat);
    % Remove logo
    bst_plugin('SetProgressLogo', []);
end

author: brainstorm-tools


text:
function [prot,rstraj] = read_twix_hdr(fid)

% function to read raw data header information from siemens MRI scanners
% (currently VB and VD software versions are supported and tested).
%
% Author: Philipp Ehses (philipp.ehses@tuebingen.mpg.de), Mar/11/2014

    nbuffers = fread(fid, 1,'uint32');

    prot = [];
    for b=1:nbuffers
        % Read string up to nul termination
        % ARC 20201020: previous version failed to find nul termination on buffer names > 10 characters
        bl=64;
        bufname = fread(fid, bl, 'uint8=>char').';

        nul_ix=min(find(bufname==0)); % ARC: index of nul termination

        if isempty(nul_ix)
          % This is not a simple buffer name as would be expected.
          % Since we don't have a good strategy for dealing with this, just
          % carry on reading until a nul temrinator is found, then discard this
          % buffer.

          warning('read_twix_hdr: skipping extraordinarily long buffer.');

          % keep reading until we find a nul
          while isempty(nul_ix)
            junk = fread(fid, bl, 'uint8=>char').';
            if numel(junk)==0
              error('read_twix_hdr: reached EOF before nul. This is perplexing.');
            end
            nul_ix=min(find(junk==0));
          end

          fseek(fid, nul_ix-bl, 'cof');

          continue; % skip to the next buffer
        end

        bufname=bufname(1:nul_ix-1);
        fseek(fid, numel(bufname)-(bl-1), 'cof');

        buflen         = fread(fid, 1,'uint32');
        buffer         = fread(fid, buflen, 'uint8=>char').';
        buffer         = regexprep(buffer,'\n\s*\n',''); % delete empty lines
        prot.(bufname) = parse_buffer(buffer);
    end

    if nargout>1
        rstraj = [];
        if isfield(prot,'Meas') && isfield(prot.Meas,'alRegridMode') && prot.Meas.alRegridMode(1)>1
            ncol           = prot.Meas.alRegridDestSamples(1);
            dwelltime      = prot.Meas.aflRegridADCDuration(1)/ncol;
            gr_adc         = zeros(1,ncol,'single');
            start          = prot.Meas.alRegridRampupTime(1) - (prot.Meas.aflRegridADCDuration(1)-prot.Meas.alRegridFlattopTime(1))/2;
            time_adc       = start + dwelltime * (0.5:ncol);
            ixUp           = time_adc <= prot.Meas.alRegridRampupTime(1);
            ixFlat         = (time_adc <= prot.Meas.alRegridRampupTime(1)+prot.Meas.alRegridFlattopTime(1)) & ~ixUp;
            ixDn           = ~ixUp & ~ixFlat;
            gr_adc(ixFlat) = 1;
            if prot.Meas.alRegridMode(1) == 2
                % trapezoidal gradient
                gr_adc(ixUp)   = time_adc(ixUp)/prot.Meas.alRegridRampupTime(1);
                gr_adc(ixDn)   = 1 - (time_adc(ixDn)-prot.Meas.alRegridRampupTime(1)-prot.Meas.alRegridFlattopTime(1))/prot.Meas.alRegridRampdownTime(1);
            elseif prot.Meas.alRegridMode(1) == 4
                % sinusoidal gradient
                gr_adc(ixUp)   = sin(pi/2*time_adc(ixUp)/prot.Meas.alRegridRampupTime(1));
                gr_adc(ixDn)   = sin(pi/2*(1+(time_adc(ixDn)-prot.Meas.alRegridRampupTime(1)-prot.Meas.alRegridFlattopTime(1))/prot.Meas.alRegridRampdownTime(1)));
            else
                warning('regridding mode unknown');
                return;
            end
            % make sure that gr_adc is always positive (rstraj needs to be
            % strictly monotonic):
            gr_adc = max(gr_adc,1e-4);
            rstraj = (cumsum(gr_adc(:)) - ncol/2)/sum(gr_adc(:));
            rstraj = rstraj - rstraj(ncol/2+1);
            % scale rstraj by kmax (only works if all slices have same FoV!!!)
            kmax = prot.MeasYaps.sKSpace.lBaseResolution/...
                prot.MeasYaps.sSliceArray.asSlice{1}.dReadoutFOV;
            rstraj = kmax * rstraj;
        end
    end

end

function prot = parse_buffer(buffer)
    [ascconv, xprot] = regexp(buffer,'### ASCCONV BEGIN[^\n]*\n(.*)\s### ASCCONV END ###','tokens','split');

    if ~isempty(ascconv)
        ascconv = ascconv{:}{:};
        prot = parse_ascconv(ascconv);
    else
        prot = struct();
    end

    if ~isempty(xprot)
        xprot = strcat(xprot{:}); % bug fix by Qiuting Wen (added strcat)
        xprot = parse_xprot(xprot);
        if isstruct(xprot)
            name   = cat(1,fieldnames(prot),fieldnames(xprot));
            val    = cat(1,struct2cell(prot),struct2cell(xprot));
            [~,ix] = unique(name);
            prot   = cell2struct(val(ix),name(ix));
        end
    end
end

function xprot = parse_xprot(buffer)
    xprot = [];
    tokens = regexp(buffer, '<Param(?:Bool|Long|String)\."(\w+)">\s*{([^}]*)','tokens');
    tokens = [tokens, regexp(buffer, '<ParamDouble\."(\w+)">\s*{\s*(<Precision>\s*[0-9]*)?\s*([^}]*)','tokens')];
    for m=1:numel(tokens)
        name         = char(tokens{m}(1));
        % field name has to start with letter
        if (~isletter(name(1)))
            name = strcat('x', name);
        end

        value = char(strtrim(regexprep(tokens{m}(end), '("*)|( *<\w*> *[^\n]*)', '')));
        value = regexprep(value, '\s*', ' ');

        try %#ok<TRYNC>
            value = eval(['[' value ']']);  % inlined str2num()
        end

        xprot.(name) = value;
    end
end

function mrprot = parse_ascconv(buffer)
    mrprot = [];
    % [mv] was: vararray = regexp(buffer,'(?<name>\S*)\s*=\s(?<value>\S*)','names');
    vararray = regexp(buffer,'(?<name>\S*)\s*=\s*(?<value>\S*)','names');

    isOctave = exist('OCTAVE_VERSION', 'builtin') ~= 0;

    for var=vararray

        try
            value = eval(['[' var.value ']']);  % inlined str2num()
        catch
            value = var.value;
        end

        % now split array name and index (if present)
        v = regexp(var.name,'(?<name>\w*)\[(?<ix>[0-9]*)\]|(?<name>\w*)','names');

        cnt = 0;
        tmp = cell(2, numel(v));

        breaked = false;
        for k=1:numel(v)
            if isOctave
                vk = v{k};
                if iscell(vk.name)
                    % lazy fix that throws some info away
                    vk.name = vk.name{1};
                    vk.ix   = vk.ix{1};
                end
            else
                vk = v(k);
            end
            if ~isletter(vk.name(1))
                breaked = true;
                break;
            end
            cnt = cnt+1;
            tmp{1,cnt} = '.';
            tmp{2,cnt} = vk.name;

            if ~isempty(vk.ix)
                cnt = cnt+1;
                tmp{1,cnt} = '{}';
                tmp{2,cnt}{1} = 1 + str2double(vk.ix);
            end
        end
        if ~breaked && ~isempty(tmp)
            S = substruct(tmp{:});
            mrprot = subsasgn(mrprot,S,value);
        end
    end
end

author: CIC-methods

repo: FID-A

save_path: github-repos/MATLAB/CIC-methods-FID-A


text:
% STD_REJECTOUTLIERS  - Commandline function, to reject outlier component(s) from clusters.
%                            Reassign the outlier component(s) to an outlier cluster specific to each cluster.
% Usage:
%                   >> [STUDY] = std_rejectoutliers(STUDY, ALLEEG, clusters, th);
% Inputs:
%   STUDY         - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
%   ALLEEG        - global EEGLAB vector of EEG structures for the dataset(s) included in the STUDY.
%                       ALLEEG for a STUDY set is typically created using LOAD_ALLEEG.
% Optional inputs:
%   clusters        - [numeric vector| 'all' ] specific cluster numbers (or 'all' clusters), which outliers
%                        will be rejected from. {default:'all'}.
%   th                 - [number] a threshold factor to select outliers. How far a component can be from the
%                       cluster centroid (in the cluster std multiples) before it will be considered as an outlier.
%                       Components that their distance from the cluster centroid are more than this factor
%                       times the cluster std (th *std) will be rejected. {default: 3}.
%
% Outputs:
%   STUDY    - the input STUDY set structure modified with the components reassignment,
%                    from the cluster to its outlier cluster.
%
%   Example:
%                         >> clusters = [10 15]; th = 2;
%                         >> [STUDY] = std_rejectoutliers(STUDY, ALLEEG, clusters, th);
%                    Reject outlier components (that are more than 2 std from the cluster centroid) from cluster 10 and 15.
%
%  See also  pop_clustedit
%
% Authors:  Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, July, 2005

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

function STUDY = std_rejectoutliers(STUDY, ALLEEG, varargin)

cls = 2:length(STUDY.cluster); % all clusters in STUDY
th = 3; % The threshold factor - default: 3

if length(varargin) > 1
    if isnumeric(varargin{1})
        cls = varargin{1};
        if isempty(cls)
            cls = 2:length(STUDY.cluster);
        end
    else
        if ischar(varargin{1}) && strcmpi(varargin{1}, 'all')
            cls = 2:length(STUDY.cluster);
        else
            error('std_prejectoutliers: clusters input takes either specific clusters (numeric vector) or keyword ''all''.');
        end
    end
end
tmp =[];
for k = 1: length(cls)
    % don't include 'Notclust' clusters
    if ~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8) && ~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)
        tmp = [tmp cls(k)];
    end
end
cls = tmp;
clear tmp

if length(varargin) == 2
    if isnumeric(varargin{2})
        th = varargin{2};
    else
        error('std_prejectoutliers: std input must be a numeric value.');
    end
end

% Perform validity checks
for k = 1:length(cls)
	% Cannot reject outlier components if cluster is a 'Notclust' or 'Outlier' cluster
	if strncmpi('Notclust',STUDY.cluster(cls(k)).name,8) || strncmpi('Outliers',STUDY.cluster(cls(k)).name,8) || ...
        strncmpi('ParentCluster', STUDY.cluster(cls(k)).name,13)
        warndlg2('Cannot reject outlier components from a Notclust or Outliers cluster');
        return;
	end
	% Cannot reject outlier components if cluster has children clusters
	if ~isempty(STUDY.cluster(cls(k)).child)
        warndlg2('Cannot reject outlier components if cluster has children clusters.');
        return;
	end

    % If the PCA data matrix of the cluster components is empty (case of merged cluster)
    if isempty(STUDY.cluster(cls(k)).preclust.preclustdata) % No preclustering information
        warndlg2('Cannot reject outlier components if cluster was not a part of pre-clustering.');
        return;
	end
end

% For each of the clusters reject outlier components
for k = 1:length(cls)
    % The PCA data matrix of the cluster components
    clsPCA = STUDY.cluster(cls(k)).preclust.preclustdata;
    % The cluster centroid
    clsCentr = mean(clsPCA,1);
    % The std of the cluster (based on the distances between all cluster components to the cluster centroid).
    std_std = std(sum((clsPCA-ones(size(clsPCA,1),1)*clsCentr).^2,2),1);
    outliers = [];
    for l = 1:length(STUDY.cluster(cls(k)).comps)
        compdist = sum((clsPCA(l,:) - clsCentr).^2); % Component distance from cluster centroid
        if compdist > std_std * th % check if an outlier
            outliers = [ outliers l];
        end
    end
    % Move outlier to the outlier cluster
    if ~isempty(outliers) % reject outliers if exist
        STUDY = std_moveoutlier(STUDY, ALLEEG,cls(k) , outliers);
    end
end

author: sccn

repo: eeglab

save_path: github-repos/MATLAB/sccn-eeglab


text:
%THIS FUMCTION ILLUSTRATES HOW TO USE THE USER-DEFINED ALGORITHM
%
% This is the second-order NMF algorithm based on the Newton method.
% The algorithm is presented by R. Zdunek and A. Cichocki in Signal
% Processing (2007)
function [A,X] = user_alg1(Y,R,Xexact)
%
% The example of implementing the user-defined algorithm
% (this is the second-order algorithm applied to the Euclidean function)
%
% INPUTS:
% Y - mixed signals (matrix of size [M by T])
% R - number of estimated signals
% Xexact - true source signals
%
% OUTPUTS
% A - estimated mixing matrix (matrix of size [M by R])
% X - estimated source signals (matrix of size [R by T])
%
% #########################################################################
% Initialization
MaxIter = 1000; % Number of alternating steps
Alpha0 = 100; Tau = 50; % Parameters in regularization for estimation of X
%
Y(Y <=0) = eps; % this enforces the positive value in the data
% Scaling to unit-variance
mx = 1./sqrt(var(Y,0,2) + eps);  Y = repmat(mx,[1,size(Y,2),1]).*Y;

% Settings
[M,T]=size(Y); I = eye(R); A = []; X = [];
lambda = 1E-12; % Levenberg-Marquardt regularization of Hessian
HA = spalloc(M*R,M*R,M*R^2); % Spase allocation for Hessian
while 1 A = rand(M,R); if cond(A) < 50 break; end; end % Initialization

% Alternatings
k = 0;
while k <=MaxIter
    k = k + 1;

  % Estimation of X
    alpha_reg = Alpha0*exp(-k/Tau); % exponential rule for regular.param.
    if isnan(A)  disp('Matrix A is too much ill-conditioned. Try again.');
        break; end
    if cond(A) > 1E6 alphaX = 1E-6; else alphaX = 0; end
    X = max(1E6*eps,pinv(A'*A + alpha_reg + alphaX*I)*A'*Y); %Updating of X

  % Estimation of A
    hA = X*X';
    hA = hA + (lambda + 1E8*exp(-k))*eye(R);  % Levenberg-Marquardt regularization
    GA = X*Y' - hA*A';  % Gradient
    HA = kron(speye(M),-hA); % Hessian

cond_HA = condest(HA);
if cond_HA > 1E17
fprintf(1,'Hessian is singular in %d iteration(s). Restart is needed.\n',k)
break; end
A = A'; A(:) = A(:) - .9*inv(HA)*GA(:); % Newton iterations
A(A <= 0) = 1E2*eps;  A = A';
A = A*diag(1./sum(A,1)); % Normalization to unit L1-column norm
end
A = repmat(1./mx,[1,size(A,2),1]).*A; % De-scaling

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function [curCosts] = updateCosts(curCosts, costs)
  fieldNames = fields(curCosts);
  for ii=1:length(fieldNames)
    field = fieldNames{ii};
    curCosts.(field) = curCosts.(field) + costs.(field);
  end
end

author: lmthang


text:
classdef LiftCoeffModel < matlab.mixin.SetGet & matlab.mixin.Copyable
    %LiftCoeffModel Summary of this class goes here
    %   Detailed explanation goes here

    properties
        cylinderModel(1,:) CylindricalLiftModel

        liftCoeffObj(1,:) AbstractLiftCoefficientModel = AbstractLiftCoefficientModel.empty(1,0);
    end

    methods
        function obj = LiftCoeffModel()
            obj.cylinderModel = CylindricalLiftModel(1, 1);

            obj.liftCoeffObj = obj.cylinderModel;
        end

        function [ClS, liftUnitVectInertial] = getLiftCoeffAndDir(obj, ut, rVect, vVect, bodyInfo, mass, altitude, pressure, density, vVectECEF, attState)
            arguments
                obj(1,1) LiftCoeffModel
                ut(1,1) double
                rVect(3,1) double
                vVect(3,1) double
                bodyInfo(1,1) KSPTOT_BodyInfo
                mass(1,1) double
                altitude(1,1) double
                pressure(1,1) double
                density(1,1) double
                vVectECEF(3,1) double
                attState(1,1) LaunchVehicleAttitudeState
            end

            [ClS, liftUnitVectInertial] = obj.liftCoeffObj.getLiftCoeffAndDir(ut, rVect, vVect, bodyInfo, mass, altitude, pressure, density, vVectECEF, attState);
        end

        function useTf = openEditDialog(obj, lvdData)
            out = AppDesignerGUIOutput();
            lvd_EditLiftCoefficientModels_App(obj, lvdData, out);
            useTf = out.output{1};
        end
    end

    methods(Static)
        function obj = loadobj(obj)
            if(isempty(obj.cylinderModel))
                obj.cylinderModel = CylindricalLiftModel(1, 1);
            end

            if(isempty(obj.liftCoeffObj))
                obj.liftCoeffObj = obj.cylinderModel;
            end
        end
    end
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
x=@(s,t) 3*tan(s).*cos(t);
y=@(s,t) 2*tan(s).*sin(t);
z=@(s,t) tan(s);
ezsurf(x,y,z)

author: Eurus-Holmes


text:
%% Feature homography based planar tracking
%
% Example of using features2d framework for interactive video homography
% matching. ORB features and FLANN matcher are used. The actual tracking is
% implemented by |PlaneTracker| class.
%
% Inspired by <http://www.youtube.com/watch?v=-ZNYoL8rzPY>
%
% Video: <http://www.youtube.com/watch?v=FirtmYcC0Vc>
%
% Select a textured planar object to track by drawing a box with a mouse.
%
% Sources:
%
% * <https://github.com/opencv/opencv/blob/3.3.1/samples/python/feature_homography.py>
%

function feature_homography_track_demo(vid)
    % video file, and a default target to track [x,y,w,h]
    win = [];
    if nargin < 1
        vid = fullfile(mexopencv.root(), 'test', 'blais.mp4');
        assert(exist(vid, 'file') == 2, 'Missing video file');
        if true
            win = [135 165 285 175];  % face
        else
            win = [136 0 366 433];    % book
        end
    elseif isempty(vid)
        vid = 0;
    end

    % open video feed, and get first frame
    cap = cv.VideoCapture(vid);
    pause(1);
    assert(cap.isOpened(), 'Failed to open video');
    frame = cap.read();
    assert(~isempty(frame), 'Failed to read frames');

    % prepare plot
    paused = false;
    tframe = zeros(size(frame), class(frame));  % target frame + drawings
    hImg = imshow([frame, tframe]);

    % create and initialize tracker
    tracker = PlaneTracker();
    if ~isempty(win)
        onRect(win);
    end

    % create ROI region selector
    if ~mexopencv.isOctave()
        onHelp();
        roi = RectSelector(hImg);
        roi.clip = true;
        roi.callback = @onRect;
    else
        %HACK: RectSelector not Octave compatible
        %HACK: function handle to nested function not supported in Octave
        roi = struct('isDragging',@()false);
    end

    % listen to keyboard input
    if ~mexopencv.isOctave()
        %HACK: function handle to nested function not supported in Octave
        set(ancestor(hImg,'figure'), 'WindowKeyPressFcn',@onType);
    end

    % main loop
    while ishghandle(hImg)
        playing = ~paused && ~roi.isDragging();
        if playing
            % read new frame
            frame = cap.read();
            if isempty(frame), break; end
        end
        out = [frame, tframe];

        % track and draw keypoints and boundary of target in new frame
        if playing
            tracked = tracker.track(frame);
            if ~isempty(tracked)
                tr = tracked(1);
                out = cv.circle(out, tr.pt1, 2, 'Color',[255 0 0]);
                out = cv.polylines(out, tr.quad, 'Closed',true, ...
                    'Color',[0 255 0], 'Thickness',2);
                % draw matches
                out = cv.line(out, ...
                    bsxfun(@plus, tr.pt0, [size(frame,2) 0]), tr.pt1, ...
                    'Color',[0 0 255]);
            end
        end

        % display result
        set(hImg, 'CData',out);
        if playing
            drawnow;
        else
            pause(0.1);  % slow down a bit if paused
        end
    end
    cap.release();
    if isobject(roi), delete(roi); end

    % --- Callback functions ---

    function onRect(rect)
        %ONRECT  Callback for ROI selector
        %
        %     onRect(rect)
        %
        % ## Input
        % * __rect__ selected rectangle [x,y,w,h], or empty
        %

        if isempty(rect), return; end

        % selection must be made in left image (current frame)
        rect = cv.Rect.intersect(rect, [0 0 size(frame,2) size(frame,1)]);
        if cv.Rect.area(rect) < 1, return; end

        % track new target
        disp('New target...')
        tracker.clear();
        tracker.addTarget(frame, rect);

        % draw keypoints and boundary in target frame
        if ~isempty(tracker.targets)
            t = tracker.targets(1);
            tframe = cv.drawKeypoints(t.image, t.kpts, 'Color',[255 0 0]);
            tframe = cv.rectangle(tframe, t.rect(1:2), t.rect(3:4), ...
                'Color',[0 255 0], 'Thickness',2);
        else
            tframe(:) = 0;
        end

        % un-pause
        paused = false;
    end

    function onType(hfig, e)
        %ONTYPE  Event handler for key press on figure

        switch e.Key
            case {'q', 'escape'}
                close(hfig);

            case 'h'
                onHelp();

            case {'space', 'p'}
                disp('Toggle pause...');
                paused = ~paused;

            case {'c', 'r'}
                disp('Clearing tracker...');
                tracker.clear();
                tframe(:) = 0;
        end
    end

    function onHelp()
        %ONHELP  Display usage help dialog

        h = helpdlg({
            'Select object(s) to track using the mouse.'
            'Hot keys:'
            '  q - quit'
            '  h - help'
            '  p - pause'
            '  c - clear targets'
        });

        % wait for user to accept dialog
        set(h, 'WindowStyle','modal');
        waitfor(h);
    end
end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
function Igo = GetRemoveResult(f, e)

Igo = f.df1/f.df*double(e.eroded_co12)+f.df2/f.df*double(e.eroded_co22)+...
    f.df3/f.df*double(e.eroded_co32)+f.df4/f.df*double(e.eroded_co42);
Igo = mat2gray(Igo);

author: decouples


text:
function [im_h] = backprojection(im_h, im_l, maxIter)

[row_l, col_l] = size(im_l);
[row_h, col_h] = size(im_h);

p = fspecial('gaussian', 5, 1);
p = p.^2;
p = p./sum(p(:));

im_l = double(im_l);
im_h = double(im_h);

for ii = 1:maxIter,
    im_l_s = imresize(im_h, [row_l, col_l], 'bicubic');
    im_diff = im_l - im_l_s;

    im_diff = imresize(im_diff, [row_h, col_h], 'bicubic');
    im_h = im_h + conv2(im_diff, p, 'same');
end

author: thomas-koehler

repo: SupER


text:
here=pwd;
cd /home/bernard/Data/ABC/apascal
attrs=dlmread('all-perimage.attributes');
classes=dlmread('all.classid');
cd (here);
classes=classes+1;

nClasses=length(unique(classes));
[nInstances, nAttrs]=size(attrs);

classesAttrs=zeros(nClasses*3,nAttrs);
classesCells=cell(1,nClasses);

for i=1:nInstances
    class=classes(i);
    signature=attrs(i,:);
    classesCells{class}=[classesCells{class}; signature];
end
counter=1;
for class=1:nClasses
    classesAttrs(counter,:)=mean(classesCells{class});
    classesAttrs(counter+1,:)=mean(classesCells{class})+0.5*std(classesCells{class});
    classesAttrs(counter+2,:)=mean(classesCells{class})-0.5*std(classesCells{class});
    counter=counter+3;
end

repo: Embarrassingly-simple-ZSL


text:
function loadRaceline(filename_raceline, DDname)
%
% Author:
%   Leonhard Hermansdorfer      Date: 03.12.2020
%
% Description:
%   function used to load a raceline for trajectory planning emulation.
%
% Input:
%   filename_raceline:  name of file containing the raceline to be loaded
%                       data format:
%                       - delimiter: ';'
%                       - header char: '#'
%                       - max. number of s-coordinates: Variable "int_max_datapoints"
%                       - contained data:
%                       [s_m;x_m;y_m;psi_rad;kappa_radpm;vx_mps;ax_mps2(;banking_rad)]
%   DDname (optional):  name of data dictionary where to save raceline;
%                       default is "raceline.sldd"

%% user input

% fixed length of raceline data arrays
int_max_datapoints = 5000;

% number of vehicles (necessary for starting and parking position calculation)
int_count_vehicles = 10;

%% read csv-file which contains the raceline

    % name of data dictionary where to write raceline
    if ~exist("DDname", "var")
        DDname = "raceline.sldd";
    end

    % add .sldd to data dictionary name if not already included
    if ~contains(DDname, ".sldd")
        DDname = strcat(DDname,'.sldd');
    end

    % add .csv to filename if not already included
    if ~contains(filename_raceline, ".csv")
        filename_raceline = strcat(filename_raceline,'.csv');
    end

    % raise error when no raceline file with specified name is found
    if isempty(which(filename_raceline))
        error(strcat('No raceline file found with name: "', filename_raceline, '"!'))
    end

    % find first line without comment char '#' to determine where to start
    % reading the raceline file
    fid = fopen(filename_raceline);
    tline = fgetl(fid);

    int_row_start = 0;

    while contains(tline, '#')
        tline = fgetl(fid);
        int_row_start = int_row_start + 1;
    end

    % start reading raceline file at first row which contains relevant data
    raceline_data = dlmread(filename_raceline,';',int_row_start,0);

    % load corresponding racetrack file if available
    loadRacetrack(strcat('traj_ltpl_cl_', filename_raceline));

%% preprocess and reshape raceline data

    % get length of original raceline
    size_raceline_init = size(raceline_data);

    % get factor for reducing number of data points in output raceline array if it is above specified limit
    dist = ceil(size_raceline_init(1) / int_max_datapoints);

    % discard last row, if x,y-coordinates are the same (trajectory is closed)
    if abs(raceline_data(1, 2) - raceline_data(end, 2)) <= 0.1 && ...
        abs(raceline_data(1, 3) - raceline_data(end, 3)) <= 0.1

        int_count_validpoints = size_raceline_init(1) - 1;

    else
        int_count_validpoints = size_raceline_init(1);

    end

    % crop raceline data to fit maximum number of data points (rows)
    raceline_data_cropped = raceline_data(1:dist:int_count_validpoints, :);
    size_raceline_cropped = size(raceline_data_cropped,1);

    % get mean distance of cropped raceline for interpolation of
    % s-coordinate
    mean_sdistance = mean(diff(raceline_data_cropped(:, 1)));

    % fill raceline array with zeros to match max number of data points (rows)
    raceline_data_out = [raceline_data_cropped;
                zeros((int_max_datapoints - size_raceline_cropped), size_raceline_init(2))];

    % create Raceline struct which is then stored in raceline data dictionary
    Raceline.s_m = raceline_data_out(:,1);
    % extrapolate s-coordinate to end of raceline array
    Raceline.s_m(size_raceline_cropped+1:int_max_datapoints, 1) = ...
        (Raceline.s_m(size_raceline_cropped) + [1:(int_max_datapoints-size_raceline_cropped)] * mean_sdistance)';

    Raceline.x_m = raceline_data_out(:,2);
    Raceline.y_m = raceline_data_out(:,3);
    Raceline.psi_rad = raceline_data_out(:,4);
    Raceline.kappa_radpm = raceline_data_out(:,5);
    Raceline.vx_mps = raceline_data_out(:,6);
    Raceline.ax_mps2 = raceline_data_out(:,7);

    Raceline.ValidPointCnt = length(raceline_data(1:dist:int_count_validpoints,1));
    Raceline.s_m_end = Raceline.s_m(Raceline.ValidPointCnt);

    % if no banking information is available, write zeros
    try
        Raceline.banking_rad = raceline_data_out(:,8);
    catch
        Raceline.banking_rad = zeros(length(raceline_data_out(:,1)), 1);
    end

%% calculate default starting (activated vehicles) and parking position (deactivated vehicles)

    % TODO: add options as function arguments (e.g. "chain", "grid")

    % starting position
    s_distance_m = 15;

    x0_vehiclepose_start = [Raceline.x_m(1), Raceline.y_m(1), Raceline.psi_rad(1); ...
                            zeros((int_count_vehicles - 1), 3)];

    for i=2:int_count_vehicles

        s_target = Raceline.s_m(int_count_validpoints + 1) - s_distance_m * (i - 1);
        abs(Raceline.s_m - s_target);
        idx = find(abs(Raceline.s_m - s_target)==min(abs(Raceline.s_m - s_target)));

        x0_vehiclepose_start(i, :) = [Raceline.x_m(idx), Raceline.y_m(idx), Raceline.psi_rad(idx)];

    end

    % parking position
    s_distance_toraceline_m = 15;
    s_distance_betweenvehicles_m = 7;

    direction_raceline = [Raceline.x_m(2) - Raceline.x_m(1), ...
                          Raceline.y_m(2) - Raceline.y_m(1)];
    direction_raceline = direction_raceline ./ sqrt(sum(direction_raceline.^2));
    normalvec_direction_raceline = cross([direction_raceline, 0], [0,0,1]);
    normalvec_direction_raceline = normalvec_direction_raceline(1:2);
    x0_vehiclepose_park = zeros(int_count_vehicles, 3);

    for i=1:int_count_vehicles

        x0_vehiclepose_park(i, :) = ...
            [[Raceline.x_m(1), Raceline.y_m(1)] ...
             + normalvec_direction_raceline * s_distance_toraceline_m ...
             + -1 * s_distance_betweenvehicles_m * direction_raceline* (i - 1), ...
             Raceline.psi_rad(1) + pi/4];

    end

%% assign struct to data dictionary

    path2module = split(which(mfilename), "mod_control");
    path2racelines = strcat(path2module{1}, "mod_control/racelines/");
    filepath2racelineDD = strcat(path2racelines, DDname);

    try

        % open default data dictionary
        if DDname == "raceline.sldd"
            datadict = Simulink.data.dictionary.open(DDname);

        % create new data dictionary with custom name
        else

            % check if data dictionary with custom name already exists
            if exist(filepath2racelineDD, "file")
                i = 1;

                while exist(filepath2racelineDD, "file")
                    DDname_temp = split(DDname,'.sldd');
                    DDname_temp = DDname_temp(1);

                    filepath2racelineDD = strcat(path2racelines, DDname_temp, num2str(i),'.sldd');

                    i = i + 1;

                end

                warning(strcat('data dictionary already exists. New name is ', filepath2racelineDD));

            end

            datadict = Simulink.data.dictionary.create(filepath2racelineDD);

        end

        % delete old data dictionary content
        dDataSectObj = getSection(datadict,'Design Data');
        list_struct_entries = find(dDataSectObj, 'DataSource', DDname);

        % delete all data dict entries of type struct
        for i=1:length(list_struct_entries)
            deleteEntry(dDataSectObj, list_struct_entries(i).Name)
        end

        % write raceline, start position and raceline file info to data dictionary
        disp(strcat('Write raceline "', filename_raceline, '" to raceline data dictionary...'));

        addEntry(dDataSectObj, "Raceline", Raceline)

        % add starting and parking position to data dictionary

        % TODO: Replace
        addEntry(dDataSectObj,'x0_vehiclepose_stm',...
        [Raceline.x_m(1),Raceline.y_m(1),Raceline.psi_rad(1)]);

        addEntry(dDataSectObj,'x0_vehiclepose_dtm',...
        [Raceline.x_m(1), -1 * Raceline.y_m(1), 0, 0, 0, normalizeAngle((-pi/2) - Raceline.psi_rad(1))]);

        for i=1:int_count_vehicles
            addEntry(dDataSectObj, strcat("x0_vehiclepos_start_veh", num2str(i)), x0_vehiclepose_start(i, :))
         	addEntry(dDataSectObj, strcat("x0_vehiclepos_park_veh", num2str(i)), x0_vehiclepose_park(i, :))
        end

        % add name of current raceline
        addEntry(dDataSectObj, 'current_raceline', filename_raceline)

        % save and close data dictionary
        datadict.saveChanges()
        datadict.close();

        % activate raceline (if other mode was used before)DDObj = ...
        DDObj = Simulink.data.dictionary.open('TrajectoryPlanningEmulation.sldd');
        dataSectObj = getSection(DDObj, 'Design Data');
        switchObj = getEntry(dataSectObj, 'P_VDC_TrajEmulation_mode');
        setValue(switchObj, 0);
        % save & close
        saveChanges(DDObj);
        close(DDObj);

    catch e
        warning(['Something went wrong during configuration of ' ...
                'raceline data dictionary']);
        disp('******************************************');
        disp('Exception: ');
        disp(getReport(e))
        disp('******************************************');

    end

end

author: TUMFTM


text:
function mean = uniform_01_mean ( )

%*****************************************************************************80
%
%% UNIFORM_01_MEAN returns the mean of the Uniform 01 PDF.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real MEAN, the mean of the discrete uniform PDF.
%
  mean = 0.5;

  return
end

author: johannesgerer

repo: jburkardt-m


text:
% Same syntax as subplot(nrow,ncol,indx)
% except that everytying is plotted much tighter together.
%
function sptight(nrow,ncol,indx)
    if (indx > nrow*ncol)
       error('invalid index');
    end

    intcol = 1/ncol;
    introw = 1/nrow;

    % compute the row,col we are in
    myrow = ceil(indx/ncol);
    mycol = mod(indx,ncol);
    if mycol==0, mycol = ncol; end

    left = intcol*(mycol-1);
    bottom = introw*(nrow-myrow);

    % make sub-plot
    subplot('Position',[left,bottom,intcol,introw]);
    set(gca,'XTick',[],'YTick',[]);
end

author: brendenlake

repo: BPL

save_path: github-repos/MATLAB/brendenlake-BPL


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

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

% Last Modified by GUIDE v2.5 01-Mar-2012 11:00:16

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

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

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

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

% Update handles structure
guidata(hObject, handles);

initialize_gui(hObject, handles, false);

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

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

% Get default command line output from handles structure
varargout{1} = handles.output;

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

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

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

% Hints: get(hObject,'String') returns contents of density as text
%        str2double(get(hObject,'String')) returns contents of density as a double
density = str2double(get(hObject, 'String'));
if isnan(density)
    set(hObject, 'String', 0);
    errordlg('Input must be a number','Error');
end

% Save the new density value
handles.metricdata.density = density;
guidata(hObject,handles)

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

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

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

% Hints: get(hObject,'String') returns contents of volume as text
%        str2double(get(hObject,'String')) returns contents of volume as a double
volume = str2double(get(hObject, 'String'));
if isnan(volume)
    set(hObject, 'String', 0);
    errordlg('Input must be a number','Error');
end

% Save the new volume value
handles.metricdata.volume = volume;
guidata(hObject,handles)

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

mass = handles.metricdata.density * handles.metricdata.volume;
set(handles.mass, 'String', mass);

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

initialize_gui(gcbf, handles, true);

% --- Executes when selected object changed in unitgroup.
function unitgroup_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in unitgroup
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

if (hObject == handles.english)
    set(handles.text4, 'String', 'lb/cu.in');
    set(handles.text5, 'String', 'cu.in');
    set(handles.text6, 'String', 'lb');
else
    set(handles.text4, 'String', 'kg/cu.m');
    set(handles.text5, 'String', 'cu.m');
    set(handles.text6, 'String', 'kg');
end

% --------------------------------------------------------------------
function initialize_gui(fig_handle, handles, isreset)
% If the metricdata field is present and the reset flag is false, it means
% we are we are just re-initializing a GUI by calling it from the cmd line
% while it is up. So, bail out as we dont want to reset the data.
if isfield(handles, 'metricdata') && ~isreset
    return;
end

handles.metricdata.density = 0;
handles.metricdata.volume  = 0;

set(handles.density, 'String', handles.metricdata.density);
set(handles.volume,  'String', handles.metricdata.volume);
set(handles.mass, 'String', 0);

set(handles.unitgroup, 'SelectedObject', handles.english);

set(handles.text4, 'String', 'lb/cu.in');
set(handles.text5, 'String', 'cu.in');
set(handles.text6, 'String', 'lb');

% Update handles structure
guidata(handles.figure1, handles);

author: Sable

repo: mcbench-benchmarks


text:
%% Diplay mesh points based on Gaussian-Hermite quadrature
% This script complements the article
%	"Fully Flexible Extreme Views"
%	by A. Meucci, D. Ardia, S. Keel
%	available at www.ssrn.com
% The most recent version of this code is available at
% MATLAB Central - File Exchange

clc;
clear all;
close all;

N = 50;
X = NaN(N, N);

for i = 1:N
    x = gaussHermiteMesh(i);
    X(1:length(x), i) = x;
end

% mesh points
figure;
plot(1:N, X', 'o', 'MarkerFace', 'k', 'Color', 'k', 'MarkerSize', 3);
grid on;


text:
filename='Cantilever_tetrahedra_coarse';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance';'perimeter'};
weights = [1, 0.1];
constraint = {'volumeConstraint'};
optimizer = 'IPOPT';
incrementFactor = 1;
designVariable = 'Density';
filterType = 'P1';

nsteps = 5;
Vfrac_final = 0.05;
Perimeter_target = 1;
optimality_final = 1e-3;
constr_final =1e-3;

Vfrac_initial = 1;
optimality_initial = 1e-2;
constr_initial = 1e-3;
TOL.rho_plus = 1;
TOL.rho_minus = 0;
TOL.E_plus = 1;
TOL.E_minus = 1e-3;
TOL.nu_plus = 1/3;
TOL.nu_minus = 1/3;

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function out_list = set_default_option(option_list,preserve,option,varargin)
% set option in option list if not yet present
%
% Syntax
%   value = set_default_option(option_list,preserve,option,value) -
%   value = set_default_option(option_list,preserve,{option1,option2,option3}) -
%
% Input
%  option_list   - Cell Array
%  preserve      - options to be preserved
%  option        - String
%  value         - some type
%
% Output
%  out_list      - Cell Array
%
% See also
% check_option get_option delete_option

if nargin == 2
  out_list = [preserve,option_list];
  return
end

if ~check_option(option_list,union_cell(ensure_cell(option),ensure_cell(preserve)))
  out_list = set_option(option_list,option,varargin{:});
else
  out_list = option_list;
end

function c = ensure_cell(s)

if isempty(s)
  c = {};
elseif isa(s,'cell')
  c = s;
else
  c = {s};
end

function c = union_cell(varargin)

c = {};
for i = 1:length(varargin)
  c = [c,varargin{i}];
end

author: mtex-toolbox

repo: mtex

save_path: github-repos/MATLAB/mtex-toolbox-mtex


text:
%                                                    y = psdmul(x,y, K)
% PSDMUL  for full x,y. Computes (XY+YX)/2
%
% **********  INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi

function y = psdmul(x,y, K) %#ok
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
%   Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
%   CRL, McMaster University, Canada.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% 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.,  51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%

disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ')


text:
function [net_config, exp_info]=cnn_load_model(input_path)

  % input_path can be a cached model file, or a folder which contains the
  % model file and the file name follow the pattern: net-config*.mat

  net_config=[];
  exp_info=[];

  fprintf('check model: %s \n', input_path);
  if ~my_check_file(input_path)
    return;
  end

  if exist(input_path, 'dir')

      model_dir=input_path;
      net_config_file=fullfile(model_dir, 'net-config*.mat');
      net_config_file=my_findfile_by_pattern(net_config_file);

      info_file=fullfile(model_dir, 'exp-info*.mat');
      info_file=my_findfile_by_pattern(info_file);

  else

      net_config_file=input_path;
      info_file=[];

  end

  if isempty(net_config_file)
      return;
  end
  net_config=load(net_config_file);
  net_config=net_config.net_config;
  process_dagnn_load(net_config);
  fprintf('model loaded from: %s\n', net_config_file);

  if ~isempty(info_file)
    exp_info=load(info_file) ;
    exp_info=exp_info.exp_info;
    fprintf('exp_info loaded from: %s\n', info_file);
  end

end

function dag_net=fix_dagnn_name(dag_net)

check_file_names={'inputs'; 'outputs'; 'params'};

for l_idx=1:length(dag_net.layers)
    for f_idx=1:length(check_file_names)
        one_field_name=check_file_names{f_idx};
        one_v=dag_net.layers(l_idx).(one_field_name);
        if size(one_v, 1)>1
            dag_net.layers(l_idx).(one_field_name)=one_v';
        end
    end
end

end

function group_info=fix_layer_name(group_info)

  % for legacy model

    if ~isempty(group_info.net_info)
      net_info=group_info.net_info;
        for l_idx=1:length(net_info.ref.layers)
            tmp_layer=net_info.ref.layers{l_idx};
            if isfield(tmp_layer, 'custom_type')
              if strcmp(tmp_layer.custom_type, 'unary_softmaxloss')
                  tmp_layer.custom_type='dense_softmaxloss';
                  net_info.ref.layers{l_idx}=tmp_layer;
              end
            end
        end
    end
end

function process_dagnn_load(net_config)

assert(isa(net_config, 'ref_obj'));

for group_idx=1:length(net_config.ref.group_infos)
    group_info=net_config.ref.group_infos{group_idx};

    group_info=fix_layer_name(group_info);

    if check_group_dag_net(group_info)
        fprintf('processing dag_net for loading, group_idx:%d, group_name: %s\n', group_info.group_idx, group_info.name);
        group_info.dag_net=fix_dagnn_name(group_info.dag_net);
        group_info.dag_net = dagnn.DagNN.loadobj(group_info.dag_net) ;
        net_config.ref.group_infos{group_idx}=group_info;
    end
end

end

function use_dagnn=check_group_dag_net(group_info)

    use_dagnn=isfield(group_info, 'dag_net') && ~isempty(group_info.dag_net);
    if isfield(group_info, 'use_dagnn') && group_info.use_dagnn
        assert(use_dagnn==group_info.use_dagnn);
    end

end

function result=my_findfile_by_pattern(net_config_file)

  result=[];

  file_info=dir(net_config_file);
  if isempty(file_info)
      return
  end
  file_info=file_info(1);
  onedir=fileparts(net_config_file);
  result=fullfile(onedir, file_info.name);

end

author: guosheng

repo: refinenet

save_path: github-repos/MATLAB/guosheng-refinenet


text:
function [lab,q] = psdeig(x,K)
% [lab,q] = psdeig(x,K)
%
% PSDEIG  Computes spectral coefficients of x w.r.t. K
%   Arguments "q" is optional - without it's considerably faster.
%   FLOPS indication: 1.3 nk^3 versus 9.0 nk^3 for nk=500,
%                     1.5 nk^3        9.8 nk^3 for nk=50.
%
% **********  INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi

% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
%   Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
%   CRL, McMaster University, Canada.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% 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.,  51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA

Ks = K.s;
if isempty(Ks),
    lab = [];
    return
end
Kq  = Ks .* Ks;
nr  = K.rsdpN;
nc  = length(Ks);
N   = sum(Kq) + sum(Kq(nr+1:end));
xi  = length(x) - N;
ei  = 0;
lab = zeros(sum(Ks),1);
needv = nargout > 1;
if needv,
    q = zeros(N,1);
    vi = 0;
end
for i = 1 : nc,
    ki = Ks(i);
    qi = Kq(i);
    XX = x(xi+1:xi+qi);
    xi = xi+qi;
    if i > nr,
        XX = XX + 1i*x(xi+1:xi+qi);
        xi = xi+qi;
    end
    XX = reshape(XX,ki,ki);
    XX = XX + XX';
    try
        if needv,
            [QQ,DD] = eig(XX);
            DD = diag(DD);
        else
            DD = eig(XX);
        end
    catch
        % If eig() fails to converge, fall back onto svd(). This costs
        % more, so we don't want to use it every time.
        [QQ,DD,VV] = svd(XX);
        DD = diag(DD).*sign(real(sum(conj(QQ).*VV)'));
    end
    lab(ei+1:ei+ki) = 0.5*DD;
    ei = ei + ki;
    if needv,
        q(vi+1:vi+qi) = real(QQ);
        vi = vi + qi;
        if i > nr,
            q(vi+1:vi+qi) = imag(QQ);
            vi = vi + qi;
        end
    end
end

author: yu-jiang

repo: radpbook

save_path: github-repos/MATLAB/yu-jiang-radpbook


text:
function nn = nnapplygrads(nn)
%NNAPPLYGRADS updates weights and biases with calculated gradients
% nn = nnapplygrads(nn) returns an neural network structure with updated
% weights and biases

    for i = 1 : (nn.n - 1)
        if(nn.weightPenaltyL2>0)
            dW = nn.dW{i} + nn.weightPenaltyL2 * [zeros(size(nn.W{i},1),1) nn.W{i}(:,2:end)];
        else
            dW = nn.dW{i};
        end

        dW = nn.learningRate * dW;

        if(nn.momentum>0)
            nn.vW{i} = nn.momentum*nn.vW{i} + dW;
            dW = nn.vW{i};
        end

        nn.W{i} = nn.W{i} - dW;
    end
end

author: rasmusbergpalm

repo: DeepLearnToolbox


text:
function warningNoTrace(varargin)
warnst = warning('off','backtrace');
warning(varargin{:});
warning(warnst);

author: kristinbranson

repo: JAABA


text:
% clear all;
% clc;
% a=[1,2,3,4;4,5,6,9;2,5,6,5;5 2 8 6];
% [filename,pathname]=uigetfile('*.jpg')
% a=imread(strcat(pathname,filename));
% % a=imread('imag.jpg');

function [v,w]=haaar(a)
a=rgb2gray(a);
a=imresize(a,[512 512]);
% z=a;
% disp('enter the level of pyramid');
% l=input('');
prompt={'enter the level of pyramid'};
dlg='enter 1 to 8';
l=cell2mat(inputdlg(prompt,dlg));
l= sscanf(l,'%f');
f=1;
for p=1:l
[r,c]=size(a);
z=a;
    for i=1:1:r
        k=1;
        t=(r/2+1);
        for j=1:2:c
            avg=(a(i,j)+a(i,j+1))/2;
            dif=(a(i,j)-a(i,j+1))/2;
            z(i,k)=avg;
            z(i,t)=dif;
            k=k+1;
            t=t+1;
        end
    end
    a=z;
    for j=1:1:c
        t=(r/2+1);
        k=1;
        for i=1:2:r
            avg=(a(i,j)+a(i+1,j))/2;
            dif=(a(i,j)-a(i+1,j))/2;
            z(k,j)=avg;
            z(t,j)=dif;
            k=k+1;
            t=t+1;
        end
    end
    if p==1;
        v=z;
    else
    v(1:512/(2^f),1:512/(2^f))=z;
    f=f+1;
    end
    a=z(1:512/(2^p),1:512/(2^p));
end
a=imresize(a,[512 512]);
% figure();
w=a;
% imshow(v);figure();
% imshow(a);
%


text:
% Closed-Form Matting
% This function implements the image matting approach described in
% Anat Levin, Dani Lischinski, Yair Weiss, "A Closed Form Solution to
% Natural Image Matting", IEEE TPAMI, 2008.
% Optional input parameter 'params' can be customized by editing the
% default values in the struct returned by 'getMattingParams('CF').
% - loc_*** define the parameters for the matting Laplacian.

function alpha = closedFormMatting(image, trimap, params, suppressMessages)
    abmtSetup
    tic;
    if ~exist('params', 'var') || isempty(params)
        params = getMattingParams('CF');
    end
    if ~exist('suppressMessages', 'var') || isempty(suppressMessages)
        suppressMessages = false;
    end
    if(~suppressMessages) display('Closed-Form Matting started...'); end

    image = im2double(image);
    trimap = im2double(trimap(:,:,1));

    % Compute matting Laplacian
    unk = trimap < 0.8 & trimap > 0.2;
    dilUnk = imdilate(unk, ones(2 * params.loc_win + 1));
    if(~suppressMessages) display('     Computing matting Laplacian...'); end
    Lap = affinityMatrixToLaplacian(mattingAffinity(image, dilUnk, params.loc_win, params.loc_eps));

    if(~suppressMessages) display('     Solving for alphas...'); end
    alpha = solveForAlphas(Lap, trimap, params.lambda, params.usePCGtoSolve);

    alpha = reshape(alpha, [size(image, 1), size(image, 2)]);

    dur = toc;
    if(~suppressMessages) display(['Done. It took ' num2str(dur) ' seconds.']); end
end

author: yaksoy

repo: AffinityBasedMattingToolbox