function C = construct_winning_matrix(M, num_method)
% -------------------------------------------------------------------------
%   Description:
%       function to construct a winning matrix C ftom vote matrix M
%
%   Input:
%       - M: N x 4 vote matrix, N is the number of images
%            M(i, 1) is image id
%            M(i, 2) is method1 id
%            M(i, 3) is method2 id
%            M(i, 4) is compared result, 1 if user chooses method1, 2 if user chooses method2
%
%       - num_method: the number of evaluated methods
%
%   Output:
%       - C: winning matrix, C(i, j) is the number of times that user choose i over j
%
%   Citation:
%       A Comparative Study for Single Image Blind Deblurring
%       Wei-Sheng Lai, Jia-Bin Huang, Zhe Hu, Narendra Ahuja, and Ming-Hsuan Yang
%       IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2016
%
%   Contact:
%       Wei-Sheng Lai
%       wlai24@ucmerced.edu
%       University of California, Merced
% -------------------------------------------------------------------------

    C = zeros(num_method, num_method);

    for i = 1:size(M, 1)

        img_id  = M(i, 1);
        method1 = M(i, 2);
        method2 = M(i, 3);
        result  = M(i, 4);

        if( result == 1 )
            C(method1, method2) = C(method1, method2) + 1;
        elseif( result == 2 )
            C(method2, method1) = C(method2, method1) + 1;
        end

    end

end


text:
%FREFINE refine estimate of fundamental matrix
%
% fr = frefine(F, uv1, uv2)
%
%  Return a refined estimate of fundamental matrix using non-linear
% optimization and enforcing the rank-2 constraint.

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

function fr = frefine(F, uv1, uv2)

	A = [];
	for i=1:numrows(uv1),
		a = [	uv1(i,1)*uv2(i,1)
			uv1(i,2)*uv2(i,1)
			uv2(i,1)
			uv1(i,1)*uv2(i,2)
			uv1(i,2)*uv2(i,2)
			uv2(i,2)
			uv1(i,1)
			uv1(i,2)
			1
		];
		A = [A; a'];
	end
	f = F';
	f = f(:);
	fprintf('Initial residual is %g\n', norm(A * f));
	fprintf('Initial determinant is %g\n', det(F));

	options = optimset('MaxFunEvals', 10000, ...
		'LevenbergMarquardt', 'on', ...
		'TolFun', 1e-16, ...
		'TolCon', 1e-16, ...
		'LargeScale', 'off' ...
		);
	fr = fmincon(@fun, f, [], [], [], [], [], [], ...
		@nlfun, options, A);
	fprintf('Final residual is %g\n', norm(A * fr));
	fr = reshape(fr, 3, 3)';
	det(fr)
	fprintf('Final determinant is %g\n', det(fr));

function e = fun(x, A)
	e = norm(A * x);

function [c,ceq] = nlfun(x, A)

	ceq = abs( det(reshape(x, 3, 3)) );
	c = [];

author: petercorke

repo: machinevision-toolbox-matlab


text:
function varargout = get_obj_fields(obj,varargin)

vnames = fieldnames(obj);
for k=1:numel(varargin)
  if isfield(struct(obj),varargin{k})
    vnames = [vnames; fieldnames(struct(obj).(varargin{k}))];
  end
end

if nargout > 0,
  varargout{1} = vnames;
else
  disp(vnames);
end

author: mtex-toolbox

repo: mtex

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


text:
function popmail_demo(site,user,pass)
% popmail_demo - Demo that read mail from pop mail server (not delete).
%                The first lines of each mail will be printed out.
%
% Syntax:
%    popmail_demo(site,user,password)
%  or
%    popmail_demo site user password
%  or
%    popmail_demo
%
%  In the last case you will be asked for intput parameters.
%
%  Version: 2002-02-01 Uppgraded to use the API in tcpiptoolbox 2.x, from tcpiptoolbox 1.x API
%

  if nargin<3,
    site=input('Input adress to pop server:','s');
    user=input('user:','s');
    pass=input('password: (sorry, will be displayed on the screen)','s');
  end
  % CONNECT
  fid=pnet('tcpconnect',site,110);
  if fid==-1,
    disp 'Cant connect to server!';
    return;
  end
  %LOGIN
  read_mresp(fid);
  pnet(fid,'printf','USER %s\n',user);
  read_mresp(fid);
  pnet(fid,'printf','PASS %s\n',pass);
  read_mresp(fid);
  pnet(fid,'printf','STAT\n');
  pnet(fid,'readline');
  all=0;
  % READ HEADERS OF FIRST 50 mail.
  for a=1:50 ,
    if all, break; end
    pnet(fid,'printf','TOP %d 0\n',a);
    s='';
    b=0;
    while strncmp(s,'.',1)==0,
      s=pnet(fid,'readline');
      b=b+1;
      if strncmp(s,'-ERR',4),
        all=1;
        nummes=a-1;
        break;
      elseif strncmp('Subject:',s,8);
        subject{a}=s(9:end);
      elseif strncmp('From:',s,5);
        from{a}=s(6:end);
      end
    end
    mlines(a)=b-1;
  end
  disp(sprintf('Number of mails in mailbox on server: %d\n',nummes));
  % DISPLAY HEADER AND READ MESSAGE LINES
  for a=1:nummes,
    disp '###############################################################'
    disp(sprintf('Subject: %s\n   From: %s',subject{a},from{a}));
    disp '---------------------------------------------------------------'
    %Request next line in current mail message.
    pnet(fid,'printf','RETR %d\n',a);
    for b=1:mlines(a),
      s=pnet(fid,'readline');
    end
    b=0;
    atflag=0;   % Set "not displaying" flag to false.
    while strcmp(s,'.')==0,
      b=b+1;
      s=pnet(fid,'readline');

      % Don't display attachment lines and similar stuff.
      if atflag==0 & b<100,
        disp(s);
      end
      if strncmp(s,'Content-',8),
        atflag=1;  % If start of attachment set "not displaying" flag.
      end
    end
  end
  pnet(fid,'close');
  return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % Read and check that response is OK
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ok=read_mresp(fid)
  s=pnet(fid,'readline');
  if strncmp(s,'+OK',3)==0,
    pnet(fid,'close');
    error('Response error!');
  end
  return;

author: PatternRecognition

repo: OpenBMI


text:
function result=moxunit_fieldtrip_util_send_json(url, content)
% Send JSON content to URL, or see which methods are available
%
% methods=moxunit_fieldtrip_util_send_json();
% result==moxunit_fieldtrip_util_send_json(url,content);
%
% Inputs:
%   url                 URL to which content is to be sent.
%   content             Struct with JSON content to be sent.
%
% Output:
%   methods             If no inputs are used, then the output is a cell
%                       string with available methods; possible values
%                       are 'webwrite' and 'curl'.
%

    [keys,send_funcs]=get_methods();

    switch nargin

        case 0
            result=keys;

        case 2
            if isempty(send_funcs)
                error('No method available to send output');
            end
            first_send_func=send_funcs{1};
            first_send_func(url, content);

        otherwise
            error('0 or 2 input arguments are required');
    end

function [keys,send_func]=get_methods()
    prop=get_all_potential_methods();

    % see which ones are availabel
    all_keys=fieldnames(prop);
    keep=cellfun(@(x)prop.(x).available(),all_keys);

    keys=all_keys(keep);
    send_func=cellfun(@(x)prop.(x).func,keys,...
                    'UniformOutput',false);

function prop=get_all_potential_methods()
    prop=struct();

    % recent Matlab's webwrite
    prop.webwrite.available=@()~isempty(which('webwrite')) && ...
                                ~isempty(which('weboptions'));
    prop.webwrite.func=@matlabge2015a_webwrite_send;

    % Unix curl (Octave and older Matlab)
    prop.curl.available=@()isunix() && unix('which curl>/dev/null')==0;
    prop.curl.func=@matlablt2015a_webwrite_send;

function matlabge2015a_webwrite_send(url, content)
    options = weboptions('MediaType','application/json');
    webwrite(url, content, options);

function matlablt2015a_webwrite_send(varargin)
    % use webwrite compatibility function (based on curl command line)
    [unused,ft_root_dir]=ft_version();
    compat_dir=fullfile(ft_root_dir,'compat','matlablt2015a');

    % go to compat directory, ensuring that webwrite is used there
    orig_pwd=pwd();
    cleaner=onCleanup(@()cd(orig_pwd));
    cd(compat_dir);

    % run webwrite
    webwrite(varargin{:});

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function [upsilonap, upsilon] = lfmapComputeUpsilonMatrix(gamma, sigma2, t1, t2, mode)

% LFMAPCOMPUTEUPSILONMATRIX Upsilon matrix acce. pos. with t1, t2 limits
% FORMAT
% DESC computes a portion of the LFM kernel.
% ARG gamma : Gamma value for system.
% ARG sigma2 : length scale of latent process.
% ARG t1 : first time input (number of time points x 1).
% ARG t2 : second time input (number of time points x 1).
% ARG mode : operation mode, according to the derivative (mode 0,
% derivative wrt t1, mode 1 derivative wrt t2)
% RETURN upsilon : result of this subcomponent of the kernel for the given values.
%
% COPYRIGHT : Mauricio Alvarez, 2010
%
% SEEALSO : lfmComputeUpsilonMatrix.F, lfmComputeH3.m

% KERN

sigma = sqrt(sigma2);
gridt1 = repmat(t1, 1, length(t2));
gridt2 = repmat(t2', length(t1), 1);
timeGrid = gridt1 - gridt2;

if mode==0
    if nargout > 1
        upsilon = lfmComputeUpsilonMatrix(gamma, sigma2, t1, t2);
        upsilonap = gamma^2*upsilon - (2/(sqrt(pi)*sigma))*exp(-(timeGrid.^2)./sigma2).*(gamma + 2*timeGrid/sigma2);
    else
        upsilonap = gamma^2*lfmComputeUpsilonMatrix(gamma, sigma2, t1, t2) ...
            - (2/(sqrt(pi)*sigma))*exp(-(timeGrid.^2)./sigma2).*(gamma + 2*timeGrid/sigma2);
    end
else
    if nargout > 1
        upsilon = lfmComputeUpsilonMatrix(gamma, sigma2, t1, t2);
        upsilonap = gamma^2*upsilon - (2/(sqrt(pi)*sigma))*exp(-(timeGrid.^2)./sigma2).*(gamma + 2*timeGrid/sigma2) ...
            + (2/(sqrt(pi)*sigma))*exp(-gamma*t1)*((gamma - 2*t2/sigma2).*exp(-(t2.^2)/sigma2)).';
    else
        upsilonap = gamma^2*lfmComputeUpsilonMatrix(gamma, sigma2, t1, t2) ...
            - (2/(sqrt(pi)*sigma))*exp(-(timeGrid.^2)./sigma2).*(gamma + 2*timeGrid/sigma2) ...
            + (2/(sqrt(pi)*sigma))*exp(-gamma*t1)*((gamma - 2*t2/sigma2).*exp(-(t2.^2)/sigma2)).';
    end
end

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


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

% Last Modified by GUIDE v2.5 09-May-2016 17:18:03

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

%MERGESTUPDATED

handles.data = varargin{1};
clsParams = handles.data.classifier_params;
tf = cellfun(@(x)isequal(x,clsParams{1}),clsParams(2:end));
if ~all(tf)
  warning('ClassifierOptions:multiclass',...
    'Multiple classifiers do not share common parameters. This interface will set all classifiers to have the same parameters.');
end
params = clsParams{1};

handles.classifier_params = params;
set(handles.edit_iter,'String',num2str(params.iter));
set(handles.iter_updates,'String',num2str(params.iter_updates));
set(handles.edit_sample,'String',num2str(params.numSample));
set(handles.edit_bins,'String',num2str(params.numBins));
set(handles.folds,'String',num2str(params.CVfolds));
set(handles.edit_nftrs,'String',num2str(params.nselfeatures));
set(handles.popup_baseclassifier,'String',params.baseClassifierTypes);

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = ClassifierOptions_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;
delete(handles.figure1);

function edit_iter_Callback(hObject, eventdata, handles)
% hObject    handle to edit_iter (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 edit_iter as text
%        str2double(get(hObject,'String')) returns contents of edit_iter as a double
val = str2double(get(hObject,'String'));
if isempty(val) || double(uint64(val))~=val
  warndlg('Enter positive value for number of iterations');
  set(hObject,'String',sprintf('%d',handles.classifier_params.iter));
  return;
end;
handles.classifier_params.iter = val;
guidata(hObject,handles);

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

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

function edit_sample_Callback(hObject, eventdata, handles)
% hObject    handle to edit_sample (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 edit_sample as text
%        str2double(get(hObject,'String')) returns contents of edit_sample as a double
val = str2double(get(hObject,'String'));
if isempty(val) || double(uint64(val))~=val
  warndlg('Enter positive value for number of sample points');
  set(hObject,'String',sprintf('%d',handles.classifier_params.numSample));
  return;
end;
handles.classifier_params.numSample = val;
guidata(hObject,handles);

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

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

function edit_bins_Callback(hObject, eventdata, handles)
% hObject    handle to edit_bins (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 edit_bins as text
%        str2double(get(hObject,'String')) returns contents of edit_bins as a double
val = str2double(get(hObject,'String'));
if isempty(val) || double(uint64(val))~=val
  warndlg('Enter positive integer value for number of iterations');
  set(hObject,'String',sprintf('%d',handles.classifier_params.numBins));
  return;
end;

if val>255 || val<10
  warndlg('Maximum number of bins is 255 and minimum number is 10');
  set(hObject,'String',sprintf('%d',handles.classifier_params.numBins));
  return;
end;
handles.classifier_params.numBins = val;
guidata(hObject,handles);

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

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

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

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

paramCell = repmat({handles.classifier_params},1,handles.data.nclassifiers);
handles.data.setClassifierParams(paramCell);
uiresume(handles.figure1);

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

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

% --- Executes during object creation, after setting all properties.
function popup_baseclassifier_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popup_baseclassifier (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 folds_Callback(hObject, eventdata, handles)
% hObject    handle to folds (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 folds as text
%        str2double(get(hObject,'String')) returns contents of folds as a double
val = str2double(get(hObject,'String'));
if isempty(val) || double(uint64(val))~=val
  warndlg('Enter positive value for number of iterations');
  set(hObject,'String',sprintf('%d',handles.classifier_params.iter));
  return;
end;
handles.classifier_params.CVfolds = val;
guidata(hObject,handles);

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

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

function iter_updates_Callback(hObject, eventdata, handles)
% hObject    handle to iter_updates (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 iter_updates as text
%        str2double(get(hObject,'String')) returns contents of iter_updates as a double
val = str2double(get(hObject,'String'));
if isempty(val) || double(uint64(val))~=val
  warndlg('Enter positive value for number of iterations');
  set(hObject,'String',sprintf('%d',handles.classifier_params.iter_updates));
  return;
end;
handles.classifier_params.iter_updates = val;
guidata(hObject,handles);

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

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

% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure
uiresume(hObject);
% delete(hObject);

function edit_nftrs_Callback(hObject, eventdata, handles)
% hObject    handle to edit_nftrs (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 edit_nftrs as text
%        str2double(get(hObject,'String')) returns contents of edit_nftrs as a double
val = str2double(get(hObject,'String'));
if isempty(val) || double(uint64(val))~=val
  warndlg('Enter positive integer value for number of sample points');
  set(hObject,'String',sprintf('%d',handles.classifier_params.numSample));
  return;
end;
handles.classifier_params.nselfeatures = val;
guidata(hObject,handles);

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

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

author: kristinbranson

repo: JAABA


text:
function [] = DemoCmdsCreate(robot, DemoNum);
%[] = DemoCmdsCreate(serPort, DemoNum)
% Starts built in Demos for Create (not Roomba)
% -1: Aborts the current demo
% 0: Attempts to cover entire room with a combination of different behaviors
% 1: Attempts to cover entire room unless Create sees a signal from home
% base, it uses that signal to dock with the home base and recharge.
% 2: Covers an area around its starting position by spiraling outward than
% inward
% 3: Searches for a wall, once a wall is found, create drives along the
% wall, around the circumference of the room
% 4: Drives in a figure 8 pattern
% 5: Drives foreward when pushed from behind. If Create his an obstacle
% while driving, it drives away from the obstacle
% 6: Drives towards an iRobot Virtual Wall
% 7: Drives into multiple virtual walls by bumping into one, turning around
% and bumping into the next virtual wall.
% 8: Plays the notes of Pachelbel's Cannon in sequence when cliff sensors
% are activated.
% 9: Plays a note of a chord for each of its cliff sensors, chord for each
% bumper.

% By; Joel Esposito, US Naval Academy, 2011

    robot.flush();

    robot.write([136 DemoNum]);

repo: robotics-toolbox-matlab


text:
%CODEGENERATOR Class for code generation
%
% Objects of the CodeGenerator class automatcally generate robot specific
% code, as either M-functions, C-functions, C-MEX functions, or real-time
% capable Simulink blocks.
%
% The various methods return symbolic expressions for robot kinematic and
% dynamic functions, and optionally support side effects such as:
% - M-functions with symbolic robot specific model code
% - real-time capable robot specific Simulink blocks
% - mat-files with symbolic robot specific model expressions
% - C-functions and -headers with symbolic robot specific model code
% - robot specific MEX functions based on the generated C-code (C-compiler
%   must be installed).
%
% Example::
%
%        % load robot model
%        mdl_twolink
%
%        cg = CodeGenerator(twolink);
%        cg.geneverything();
%
%        % a new class has been automatically generated in the robot directory.
%        addpath robot
%
%        tl = @robot();
%        % this class is a subclass of SerialLink, and thus polymorphic with
%        % SerialLink but its methods have been overloaded with robot-specific code,
%        % for example
%        T = tl.fkine([0.2 0.3]);
%        % uses concise symbolic expressions rather than the generalized A-matrix
%        % approach
%
%        % The Simulink block library containing robot-specific blocks can be
%        % opened by
%        open robot/robotslib.slx
%        % and the blocks dragged into your own models.
%
% Methods::
%
%  gencoriolis     generate Coriolis/centripetal code
%  genfdyn         generate forward dynamics code
%  genfkine        generate forward kinematics code
%  genfriction     generate joint friction code
%  gengravload     generate gravity load code
%  geninertia      generate inertia matrix code
%  geninvdyn       generate inverse dynamics code
%  genjacobian     generate Jacobian code
%  geneverything   generate code for all of the above
%
% Properties (read/write)::
%
%  basepath       basic working directory of the code generator
%  robjpath       subdirectory for specialized MATLAB functions
%  sympath        subdirectory for symbolic expressions
%  slib           filename of the Simulink library
%  slibpath       subdirectory for the Simulink library
%  verbose        print code generation progress on console (logical)
%  saveresult     save symbolic expressions to .mat-files (logical)
%  logfile        print modeling progress to specified text file (string)
%  genmfun        generate executable M-functions (logical)
%  genslblock     generate Embedded MATLAB Function blocks (logical)
%  genccode       generate C-functions and -headers (logical)
%  genmex         generate MEX-functions as replacement for M-functions (logical)
%  compilemex     automatically compile MEX-functions after generation (logical)
%
% Properties (read only)::
%  rob            SerialLink object to generate code for (1x1).
%
% Notes::
%  - Requires the MATLAB Symbolic Toolbox.
%  - For robots with > 3 joints the symbolic expressions are massively
%    complex, they are slow and you may run out of memory.
%  - As much as possible the symbolic calculations are down row-wise to
%    reduce the computation/memory burden.
%  - Requires a C-compiler if robot specific MEX-functions shall be
%    generated as m-functions replacement (see MATLAB documentation of MEX
%    files).
%
% Author::
%  Joern Malzahn, (joern.malzahn@tu-dortmund.de)
%
% See also SerialLink, Link.

% Copyright (C) 1993-2012, by Peter I. Corke
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module originally emerged during the work on a project
% funded by the German Research Foundation (DFG, BE1569/7-1). The authors
% gratefully acknowledge the financial support.

classdef CodeGenerator
    properties (SetAccess = private)
        rob
        ccodepath;
        cppcodepath;
        robjpath;
        sympath;
        slibpath;
    end
    properties
        basepath;
        slib;
        verbose;
        saveresult;
        logfile;
        genmfun;
        genslblock;
        genccode;
        genmex;
        compilemex;
    end
    properties (GetAccess = private)
        debug;        % just appears because of tb_optparse, so hide it from the user
    end
    methods

        function CGen = CodeGenerator(rob,varargin)
        %CodeGenerator.CodeGenerator Construct a code generator object
        %
        % cGen = CodeGenerator(ROB, OPTIONS) is a code generator object for the SerialLink
        % object ROB.
        %
        %
        % Options::
        %
        % CodeGenerator has many options, and useful sets of options are called
        % optionSets, and the following are recognized:
        %
        %  'default'     set the options: verbose, saveResult, genMFun, genSLBlock
        %  'debug'       set the options: verbose, saveResult, genMFun, genSLBlock
        %                and create a logfile named 'robModel.log' in the working directory
        %  'silent'      set the options: saveResult, genMFun, genSLBlock
        %  'disk'        set the options: verbose, saveResult
        %  'workspace'   set the option: verbose; just outputs symbolic expressions to workspace
        %  'mfun'        set the options: verbose, saveResult, genMFun
        %  'slblock'     set the options: verbose, saveResult, genSLBlock
        %  'ccode'       set the options: verbose, saveResult, genCcode
        %  'mex'         set the options: verbose, saveResult, genMEX
        %
        % If no optionSet is provided, then 'default' is used.
        %
        % The options themselves control the code generation and user information:
        %
        %  'verbose'           write code generation progress to command window
        %  'saveResult         save results to hard disk (always enabled, when genMFun and genSLBlock are set)
        %  'logFile',logfile   write code generation progress to specified logfile
        %  'genMFun'           generate robot specific m-functions
        %  'genSLBlock'        generate real-time capable robot specific Simulink blocks
        %  'genccode'          generate robot specific C-functions and -headers
        %  'mex'               generate robot specific MEX-functions as replacement for the m-functions
        %  'compilemex'        select whether generated MEX-function should be compiled directly after generation
        %
        %  Any option may also be modified individually as optional parameter value pairs.
        %
        % Author::
        %  Joern Malzahn
        %  2012 RST, Technische Universitaet Dortmund, Germany.
        %  http://www.rst.e-technik.tu-dortmund.de

            if ~isa(rob,'SerialLink')
                error('CodeGenerator:wrongConstructorInput','The input variable %s must be a SerialLink object.',inputname(1));
            end

            if ~rob.issym
                CGen.rob = rob.sym;
            else
                CGen.rob = rob;
            end

            % defaults
            CGen.basepath = fullfile(CGen.getrobfname);
            CGen.robjpath = fullfile(CGen.basepath,['@',CGen.getrobfname]);
            CGen.sympath = fullfile(CGen.basepath,'symbolicexpressions');
            CGen.slib = [CGen.getrobfname,'slib'];
            CGen.slibpath = fullfile(CGen.basepath,CGen.slib);
            CGen.verbose = false;
            CGen.saveresult = false;
            CGen.logfile = '';
            CGen.genmfun = false;
            CGen.genslblock = false;
            CGen.debug = false;
            CGen.genccode = false;
            CGen.ccodepath = fullfile(CGen.basepath,'c');
            CGen.cppcodepath = fullfile(CGen.basepath,'cpp');
            CGen.genmex = false;
            CGen.compilemex = true;

            if nargin < 2
                varargin{1} = 'default';
            end

            % Determine code generation option set
            switch lower(varargin{1})
                case 'default'
                    CGen = tb_optparse(CGen,...
                        [{'verbose','saveresult','genmfun','genslblock'},varargin(2:end)]);
                case 'debug'
                    CGen = tb_optparse(CGen,...
                        [{'verbose','saveresult','genmfun','genslblock','logfile','robModel.log'},varargin(2:end)]);
                case 'silent'
                    CGen = tb_optparse(CGen,...
                        [{'saveresult','genmfun','genslblock'},varargin(2:end)]);
                case 'disk'
                    CGen = tb_optparse(CGen,...
                        [{'verbose','saveresult'},varargin(2:end)]);
                case 'workspace'
                    CGen = tb_optparse(CGen,...
                        [{'verbose'},varargin(2:end)]);
                case 'mfun'
                    CGen = tb_optparse(CGen,...
                        [{'verbose','saveresult','genmfun'},varargin(2:end)]);
                case 'slblock'
                    CGen = tb_optparse(CGen,...
                        [{'verbose','saveresult','genslblock'},varargin(2:end)]);
                case 'ccode'
                    CGen = tb_optparse(CGen,...
                        [{'verbose','saveresult','genmfun','logfile','robModel.log','genccode'},varargin(2:end)]);
                case 'mex'
                    CGen = tb_optparse(CGen,...
                        [{'verbose','saveresult','genmfun','logfile','robModel.log','genmex'},varargin(2:end)]);
                otherwise
                    CGen = tb_optparse(CGen,varargin);
            end

            if any([CGen.genmfun, CGen.genslblock, CGen.genccode, CGen.genmex])
                CGen.saveresult = true;
            end

            if CGen.genmex
                CGen.genccode = true;
            end

            if ~isempty(CGen.logfile)
                logfid = fopen(CGen.logfile,'w+'); % open or create file, discard existing contents
                fclose(logfid);
            end
            CGen.logmsg([datestr(now),' +++++++++++++++++++++++++++++++++++\n']);
            CGen.logmsg([datestr(now),'\tLog for ',CGen.getrobfname,'\n']);
            CGen.logmsg([datestr(now),' +++++++++++++++++++++++++++++++++++\n']);

        end

        function robName = getrobfname(CGen)

        % Use regular expression \W to replace any character
        % that is not alphabetic, numeric, or underscore.
        % For English character sets, this is equivalent to [^a-zA-Z_0-9].
        % This yields proper variable and function names!
            robName = regexprep(CGen.rob.name, '\W', '');

            if numel(robName)>4 && strcmp(robName(end-3:end),'copy')
                robName = robName(1:end-4);
            end
        end

        function savesym(CGen,sym2save, symname, fname)
            if ~exist(CGen.sympath,'dir')
                mkdir(CGen.sympath)
            end

            eval([symname,'= sym2save;']);
            save(fullfile(CGen.sympath,fname),symname);
        end

        function [] = geneverything(CGen)
            [t,allT] = CGen.genfkine;
            [J0,Jn] = CGen.genjacobian;
            [G] = CGen.gengravload;
            [I] = CGen.geninertia;
            [C] = CGen.gencoriolis;
            [F] = CGen.genfriction;
            [Iqdd] = CGen.genfdyn;
            [tau] = CGen.geninvdyn;
        end

        function CGen = set.genmfun(CGen,value)
            CGen.genmfun = value;
            if value == true
                CGen.saveresult = value;
            end

            if ~exist(fullfile(CGen.robjpath,CGen.getrobfname),'file')
                CGen.logmsg([datestr(now),'\tCreating ',CGen.getrobfname,' m-constructor ']);
                CGen.createmconstructor;
                CGen.logmsg('\t%s\n',' done!');
            end
        end

        function CGen = set.genslblock(CGen,value)
            CGen.genslblock = value;
            if value == true
                CGen.saveresult = true;
            end
        end
        function [] = addpath(CGen)
        %CodeGenerator.addpath Adds generated code to search path
        %
        % cGen.addpath() adds the generated m-functions and block library to the
        % MATLAB function search path.
        %
        % Author::
        %  Joern Malzahn
        %  2012 RST, Technische Universitaet Dortmund, Germany.
        %  http://www.rst.e-technik.tu-dortmund.de
        %
        % See also addpath.
        addpath(CGen.basepath);
        end

        function [] = rmpath(CGen)
        %CodeGenerator.rmpath Removes generated code from search path
        %
        % cGen.rmpath() removes generated m-functions and block library from the
        % MATLAB function search path.
        %
        % Author::
        %  Joern Malzahn
        %  2012 RST, Technische Universitaet Dortmund, Germany.
        %  http://www.rst.e-technik.tu-dortmund.de
        %
        % See also rmpath.
        rmpath(CGen.basepath);
        end

        function [] = purge(CGen,varargin)
        %CodeGenerator.purge  Cleanup generated files
        %
        % cGen.purge() deletes all generated files, first displays a question dialog to
        % make sure the user really wants to delete all generated files.
        %
        % cGen.purge(1) as above but skips the question dialog.
        %
        % Author::
        %  Joern Malzahn
        %  2012 RST, Technische Universitaet Dortmund, Germany.
        %  http://www.rst.e-technik.tu-dortmund.de
            dopurge = 0;

            if exist(CGen.basepath,'dir')
                if nargin > 1
                    dopurge = varargin{1}
                else
                    qstn = ['Do you really want to delete ',CGen.basepath, ' and all of it''s contents?'];
                    tit = ['Purge: ',CGen.getrobfname];
                    str1 = 'Yes';
                    str2 = 'No';
                    button = questdlg(qstn,tit,str1,str2,str1)
                    dopurge = strcmp(button,str1);
                end
            end

            if dopurge
                bdclose all

                warning off;
                CGen.rmpath;
                warning on;

                rmdir(CGen.basepath,'s')
                if ~isempty(CGen.logfile) && exist(CGen.logfile,'file')
                    delete(CGen.logfile);
                end
            end
        end
    end
end


text:
function pot = set_domain_pot(pot, domain)
% SET_DOMAIN_POT Change the domain of a potential (cgpot)
% pot = set_domain_pot(pot, domain)

delta = domain(1) - pot.domain(1);
assert(all(domain == pot.domain + delta));
pot.domain = pot.domain + delta;
pot.ddom = pot.ddom + delta;
pot.cdom = pot.cdom + delta;

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
function [varargout]=coarsepatch(F,V,f)

% function [F,V,Eb]=coarsepatch(F,V,f)
%-------------------------------------------------------------------------
%
%
%
% Change log:
% 2019/06/25 Added variable output handling as well as outputting of
% boundary edges
%-------------------------------------------------------------------------
%%
% Run reducepatch
[F,V] = reducepatch(F,V,f,'fast');

%%
% Avoid/fix reducepatch bugs
[F,V]=mergeVertices(F,V); %Merge vertices
F=patchRemoveCollapsed(F); %remove collapsed (edges)
[F,V]=triSurfRemoveThreeConnect(F,V);
[F,V]=patchCleanUnused(F,V); %Remove unused points
F=uniqueIntegerRow(F); %Removing double faces

%%

varargout{1}=F;
varargout{2}=V;

if nargout==3
    %Also compute boundary
    varargout{3}=patchBoundary(F,V);
end

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% 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 3 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, see <http://www.gnu.org/licenses/>.

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


text:
function K = covSum(cov, hyp, x, z, i)

% covSum - compose a covariance function as the sum of other covariance
% functions. This function doesn't actually compute very much on its own, it
% merely does some bookkeeping, and calls other covariance functions to do the
% actual work.
%
% Copyright (c) by Carl Edward Rasmussen & Hannes Nickisch 2010-09-10.
%
% See also COVFUNCTIONS.M.

if ~isempty(cov)==0, error('We require at least one summand.'), end
for ii = 1:numel(cov)                        % iterate over covariance functions
  f = cov(ii); if iscell(f{:}), f = f{:}; end   % expand cell array if necessary
  j(ii) = cellstr(feval(f{:}));                          % collect number hypers
end

if nargin<3                                        % report number of parameters
  K = char(j(1)); for ii=2:length(cov), K = [K, '+', char(j(ii))]; end, return
end
if nargin<4, z = []; end                                   % make sure, z exists
[n,D] = size(x);

v = [];               % v vector indicates to which covariance parameters belong
for ii = 1:length(cov), v = [v repmat(ii, 1, eval(char(j(ii))))]; end

if nargin<5                                                        % covariances
  K = 0; if nargin==3, z = []; end                                 % set default
  for ii = 1:length(cov)                      % iteration over summand functions
    f = cov(ii); if iscell(f{:}), f = f{:}; end % expand cell array if necessary
    K = K + feval(f{:}, hyp(v==ii), x, z);              % accumulate covariances
  end
else                                                               % derivatives
  if i<=length(v)
    vi = v(i);                                       % which covariance function
    j = sum(v(1:i)==vi);                    % which parameter in that covariance
    f  = cov(vi);
    if iscell(f{:}), f = f{:}; end         % dereference cell array if necessary
    K = feval(f{:}, hyp(v==vi), x, z, j);                   % compute derivative
  else
    error('Unknown hyperparameter')
  end
end

author: benfulcher

repo: hctsa

save_path: github-repos/MATLAB/benfulcher-hctsa


text:
function y = identity_mapping(x, varargin)
%IDENTITY_MAPPING  Copies first argument to output, ignoring additional
%arguments.

y = x;

end

author: sakaridis


text:
function point_num = levels_index_size_onn ( dim_num, level_max )

%*****************************************************************************80
%
%% LEVELS_INDEX_SIZE_ONN sizes a sparse grid made from ONN 1D rules.
%
%  Discussion:
%
%    The sparse grid is presumed to have been created from products
%    of OPEN NON-NESTED 1D quadrature rules.
%
%    ONN rules include Gauss Laguerre.
%
%    The sparse grid is the logical sum of product grids with total LEVEL
%    between LEVEL_MIN and LEVEL_MAX.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 July 2008
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Fabio Nobile, Raul Tempone, Clayton Webster,
%    A Sparse Grid Stochastic Collocation Method for Partial Differential
%    Equations with Random Input Data,
%    SIAM Journal on Numerical Analysis,
%    Volume 46, Number 5, 2008, pages 2309-2345.
%
%  Parameters:
%
%    Input, integer DIM_NUM, the spatial dimension.
%
%    Input, integer LEVEL_MAX, the maximum value of LEVEL.
%
%    Output, integer POINT_NUM, the number of points in the grid.
%

%
%  Special case.
%
  if ( level_max == 0 )
    point_num = 1;
    return
  end
%
%  The outer loop generates LEVELs from LEVEL_MIN to LEVEL_MAX.
%
  level_min = max ( 0, level_max + 1 - dim_num );

  point_num = 0;

  for level = level_min : level_max
%
%  The middle loop generates the next partition that adds up to LEVEL.
%
    level_1d = [];
    more = 0;
    h = 0;
    t = 0;

    while ( 1 )

      [ level_1d, more, h, t ] = comp_next ( level, dim_num, level_1d, more, h, t );
%
%  Transform each 1D level to a corresponding 1D order.
%
      order_1d = level_to_order_open ( dim_num, level_1d );

      point_num = point_num + prod ( order_1d(1:dim_num) );

      if ( ~more )
        break
      end

    end
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function tic(t)
% TIMETIC/TIC Implement the TIC operation on a timetic object
%
% The tic function duplicates the behavior of the global tic command in
% matlab on a timetic object.  It sets the current time to 0 and starts the
% timer.  (Notice the different from the start function which does not set
% the time to 0.)
%
% Using tic and toc on t allow for nested timers analogous to tic and toc.
%
% Example:
%   t = timetic();
%   tic(t);
%   toc(t);
%
% See also TIC, TIMETIC/TOC, TIMETIC/START

%
% David Gleich
% Stanford University
% 27 September 2006
%

t.set(0);
t.start();

author: Sable

repo: mcbench-benchmarks


text:
function [y,fs,bits]=wavread(fn,n)
%WAVREAD  Legacy MATLAB function to read .WAV file [Y,FS,BITS]=(FILENAME,NMAX)
% wavread supports multichannel data, with up to 32 bits per sample, and supports reading 24- and 32-bit .wav files.
%
% Usage:
% y = wavread('filename')               loads a WAVE file specified by the string filename, returning
%                                       the sampled data in y. The .wav extension is appended if no
%                                       extension is given. Amplitude values are in the range [-1,+1].
% [y,Fs,bits] = wavread('filename')     returns the sample rate (Fs) in Hertz and the number of bits
%                                       per sample (bits) used to encode the data in the file.
% [...] = wavread('filename',N)         returns only the first N samples from each channel in the file.
% [...] = wavread('filename',[N1 N2])   returns only samples N1 through N2 from each channel in the file.
% siz = wavread('filename','size')      returns the size of the audio data contained in the file in place
%                                       of the actual audio data, returning the vector siz = [samples channels].

%	   Copyright (C) Mike Brookes 2018
%      Version: $Id: wavread.m 10457 2018-03-28 14:32:59Z dmb $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   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 can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin<2
    [y,fs,wm,fx]=readwav(fn);
elseif ischar(n)
    if strcmp(n,'size')
        [y,fs,wm,fx]=readwav(fn,'',0);
        y=fx(4:5); % number of samples and channels
    else
        error('%s is invalid option',n);
    end
elseif length(n)<2
    [y,fs,wm,fx]=readwav(fn,'',n);
else
    [y,fs,wm,fx]=readwav(fn,'',n(2)-n(1)+1,n(1)-1);
end
bits=fx(7); % bits precision

author: jtkim-kaist

repo: Speech-enhancement


text:
function [C, sigma] = dataset3Params(X, y, Xval, yval)
%DATASET3PARAMS returns your choice of C and sigma for Part 3 of the exercise
%where you select the optimal (C, sigma) learning parameters to use for SVM
%with RBF kernel
%   [C, sigma] = DATASET3PARAMS(X, y, Xval, yval) returns your choice of C and
%   sigma. You should complete this function to return the optimal C and
%   sigma based on a cross-validation set.
%

% You need to return the following variables correctly.
C = 1;
sigma = 0.3;

% ====================== YOUR CODE HERE ======================
% Instructions: Fill in this function to return the optimal C and sigma
%               learning parameters found using the cross validation set.
%               You can use svmPredict to predict the labels on the cross
%               validation set. For example,
%                   predictions = svmPredict(model, Xval);
%               will return the predictions on the cross validation set.
%
%  Note: You can compute the prediction error using
%        mean(double(predictions ~= yval))
%

% C_vec = [0.01,0.03,0.1,0.3,1,3,10,30];
% sigma_vec = [0.01,0.03,0.1,0.3,1,3,10,30];
% error = zeros(8,8);
%
% for i=1:8
%     for j=1:8
%         model= svmTrain(X, y, C_vec(i), @(x1, x2) gaussianKernel(x1, x2, sigma_vec(j)));
%         predictions = svmPredict(model, Xval);
%         error(i,j) = mean(double(predictions ~= yval));
%     end
% end
%
% temp= min(min(error));
%
% [row, colume ] = find(error == temp)

C = 1;
sigma = 0.1;

% =========================================================================

end

author: zzlyw

repo: machine-learning-exercises


text:
function r83col_print_part_test ( )

%*****************************************************************************80
%
%% R83COL_PRINT_PART_TEST tests R83COL_PRINT_PART.
%
%  Discussion:
%
%    An R82COL is an (N,3) array of R8's.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2015
%
%  Author:
%
%    John Burkardt
%
  n = 10;
%
%  Set up the array by rows.
%
  v = [ ...
    11.0,  12.0,  13.0; ...
    21.0,  22.0,  23.0; ...
    31.0,  32.0,  33.0; ...
    41.0,  42.0,  43.0; ...
    51.0,  52.0,  53.0; ...
    61.0,  62.0,  63.0; ...
    71.0,  72.0,  73.0; ...
    81.0,  82.0,  83.0; ...
    91.0,  92.0,  93.0; ...
   101.0, 102.0, 103.0 ];

  fprintf ( 1, '\n' );
  fprintf ( 1, 'R83COL_PRINT_PART_TEST\n' );
  fprintf ( 1, '  R83COL_PRINT_PART prints part of an R83COL.\n' );

  max_print = 2;
  r83col_print_part ( n, v, max_print, '  Output with MAX_PRINT = 2' );

  max_print = 5;
  r83col_print_part ( n, v, max_print, '  Output with MAX_PRINT = 5' );

  max_print = 25;
  r83col_print_part ( n, v, max_print, '  Output with MAX_PRINT = 25' );

  return
end


text:
function test_bug2727

% WALLTIME 00:10:00
% MEM 2gb
% DEPENDENCY ft_clusterplot topoplot_common

%%

label = {
  'MLC11'    'MLC12'    'MLC13'    'MLC14'    'MLC15'    'MLC21'    'MLC22'    'MLC23'    'MLC24'    'MLC31'    'MLC32'    'MLC33'    'MLC41'    'MLC42' ...
  'MLC43'    'MLF11'    'MLF12'    'MLF21'    'MLF22'    'MLF23'    'MLF31'    'MLF32'    'MLF33'    'MLF34'    'MLF41'    'MLF42'    'MLF43'    'MLF44' ...
  'MLF45'    'MLF51'    'MLF52'    'MLO11'    'MLO12'    'MLO21'    'MLO22'    'MLO31'    'MLO32'    'MLO33'    'MLO41'    'MLO42'    'MLO43'    'MLP11' ...
  'MLP12'    'MLP13'    'MLP21'    'MLP22'    'MLP31'    'MLP32'    'MLP33'    'MLP34'    'MLT11'    'MLT12'    'MLT13'    'MLT14'    'MLT15'    'MLT16' ...
  'MLT21'    'MLT22'    'MLT23'    'MLT24'    'MLT25'    'MLT26'    'MLT31'    'MLT32'    'MLT33'    'MLT34'    'MLT35'    'MLT41'    'MLT42'    'MLT43' ...
  'MLT44'    'MRC11'    'MRC12'    'MRC13'    'MRC14'    'MRC15'    'MRC21'    'MRC22'    'MRC23'    'MRC24'    'MRC31'    'MRC32'    'MRC33'    'MRC41' ...
  'MRC42'    'MRC43'    'MRF11'    'MRF12'    'MRF21'    'MRF22'    'MRF23'    'MRF31'    'MRF32'    'MRF33'    'MRF34'    'MRF41'    'MRF42'    'MRF43' ...
  'MRF44'    'MRF45'    'MRF51'    'MRF52'    'MRO11'    'MRO12'    'MRO21'    'MRO22'    'MRO31'    'MRO32'    'MRO33'    'MRO41'    'MRO42'    'MRO43' ...
  'MRP11'    'MRP12'    'MRP13'    'MRP21'    'MRP22'    'MRP31'    'MRP32'    'MRP33'    'MRP34'    'MRT11'    'MRT12'    'MRT13'    'MRT14'    'MRT15' ...
  'MRT16'    'MRT21'    'MRT22'    'MRT23'    'MRT24'    'MRT25'    'MRT26'    'MRT31'    'MRT32'    'MRT33'    'MRT34'    'MRT35'    'MRT41'    'MRT42' ...
  'MRT43'    'MRT44'    'MZC01'    'MZC02'    'MZF01'    'MZF02'    'MZF03'    'MZO01'    'MZO02'    'MZP01'    'MZP02'
  };

stat = [];
stat.label = label;
stat.prob = rand(151,1);
stat.stat = stat.prob;
stat.dimord = 'chan';
stat.posclusterslabelmat = stat.prob<0.05;
stat.posclusters(1).prob = 0;
% stat.posclusters(1).clusterstat = nan;
% stat.posclusters(1).stddev      = nan;
% stat.posclusters(1).cirange     = nan;

statT = [];
statT.label = label;
statT.prob = rand(151,10);
statT.stat = statT.prob;
statT.time = (1:10)/10; % in seconds
statT.dimord = 'chan_time';
statT.posclusterslabelmat = statT.prob<0.05;
statT.posclusters(1).prob = 0;

statF = [];
statF.label = label;
statF.prob = rand(151,20);
statF.stat = statF.prob;
statF.freq = 1:20; % in Hz
statF.dimord = 'chan_freq';
statF.posclusterslabelmat = statF.prob<0.05;
statF.posclusters(1).prob = 0;

statTF = [];
statTF.label = label;
statTF.prob = rand(151,20,10);
statTF.stat = statTF.prob;
statTF.freq = 1:20; % in Hz
statTF.time = (1:10)/10; % in seconds
statTF.dimord = 'chan_freq_time';
statTF.posclusterslabelmat = statTF.prob<0.05;
statTF.posclusters(1).prob = 0;

statT1F = [];
statT1F.label = label;
statT1F.prob = rand(151,20,1);
statT1F.stat = statT1F.prob;
statT1F.freq = 1:20; % in Hz
statT1F.time = 0.5; % in seconds
statT1F.dimord = 'chan_freq_time';
statT1F.posclusterslabelmat = statT1F.prob<0.05;
statT1F.posclusters(1).prob = 0;

statTF1 = [];
statTF1.label = label;
statTF1.prob = rand(151,1,10);
statTF1.stat = statTF1.prob;
statTF1.freq = 1; % in Hz
statTF1.time = (1:10)/10; % in seconds
statTF1.dimord = 'chan_freq_time';
statTF1.posclusterslabelmat = statTF1.prob<0.05;
statTF1.posclusters(1).prob = 0;

%%

cfg = [];
cfg.layout = 'CTF151.lay';
ft_clusterplot(cfg, stat);
ft_clusterplot(cfg, statT);
ft_clusterplot(cfg, statF);
ft_clusterplot(cfg, statTF1); % single frequency
ft_clusterplot(cfg, statT1F); % single latency

try
  figure; ft_clusterplot(cfg, statTF);
  failed = false;
catch
  failed = true;
end
assert(failed==true, 'this should have failed');


text:
% Demo script on various ways to create an ellipse.
%
%   output = create_ellipse_demo(input)
%
%   Example
%   create_ellipse_demo
%
%   See also
%

% ------
% Author: David Legland
% e-mail: david.legland@inrae.fr
% INRAE - BIA Research Unit - BIBS Platform (Nantes)
% Created: 2022-09-09,    using Matlab 9.12.0.1884302 (R2022a)
% Copyright 2022 INRAE.

%% Use explicit representation

center = [50 50];
radii = [40 20];
theta = 30;
elli0 = [center radii theta];

figure; hold on; axis square; axis([0 100 0 100]);
drawEllipse(elli0, 'lineWidth', 2, 'color', 'b');

%% Fit an ellipse to a set of points

% choose several points on the ellipse, and add some noise
nPoints = 100;
ti = rand(nPoints, 1) * 2 * pi;
pts = ellipsePoint(elli0, ti) + randn(nPoints, 2) * 2;

% fit the ellipse to the set of points
elli = fitEllipse(pts);

% display points and fit result
figure; hold on; axis square; axis([0 100 0 100]);
drawPoint(pts, 'linewidth', 1, 'color', 'b');
drawEllipse(elli, 'lineWidth', 2, 'color', 'm');

%% Equivalent ellipse from a set of points

% generate random points within the ellipse,
% with a density equal to 1 (1 point per unit square on average)
nPoints = round(ellipseArea(elli));
pts0 = zeros(nPoints, 2);
for iPoint = 1:nPoints
    while true
        pt = rand([1 2]) * 100;
        if isPointInEllipse(pt, elli0)
            pts(iPoint,:) = pt;
            break;
        end
    end
end

% computes equivalent ellipse
elli = equivalentEllipse(pts);

% display result
figure; hold on; axis square; axis([0 100 0 100]);
drawPoint(pts, 'b.');
drawEllipse(elli, 'lineWidth', 2, 'color', 'm');
drawEllipseAxes(elli, 'lineWidth', 2, 'color', 'm');

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function [GAmp,GTime]=GxRadial(p)

global VCtl;
global VObj;
global VVar;

t1Start=p.t1Start;
t2Middle=p.t2Middle;
t3Start=p.t3Start;
tRamp=p.tRamp;
Gx1Sign=p.Gx1Sign;
Gx2Sign=p.Gx2Sign;
Gx3Sign=p.Gx3Sign;

% 2D radial encoding
FOV = VCtl.FOVFreq; % choose FOVFreq as real FOV
Res = VCtl.ResFreq; % choose ResFreq as real resolution

switch VCtl.R_AngPattern
    case 'Linear'
       eval(['R_AngRange=' VCtl.R_AngRange ';']);
       AngInc = R_AngRange / VCtl.R_SpokeNum;
    case 'Golden'
       AngInc = 111.246 * (pi/180); % Golden-angle sample
end

GxAmp=(1/FOV)/((VObj.Gyro/(2*pi))*(1/VCtl.BandWidth));
tHalf=1/(2*(VObj.Gyro/(2*pi))*GxAmp*(FOV/Res));
[GAmp1,GTime1]=StdTrap(t1Start-tRamp,          ...
                       t1Start+tHalf+tRamp,    ...
                       t1Start,                          ...
                       t1Start+tHalf,                    ...
                       GxAmp*cos(AngInc * (VVar.PhaseCount - 1))*Gx1Sign,2,2,2);
[GAmp2,GTime2]=StdTrap(t2Middle+VCtl.TEAnchorTime-tHalf-tRamp, ...
                       t2Middle+VCtl.TEAnchorTime+tHalf+tRamp, ...
                       t2Middle+VCtl.TEAnchorTime-tHalf,               ...
                       t2Middle+VCtl.TEAnchorTime+tHalf,               ...
                       GxAmp*cos(AngInc * (VVar.PhaseCount - 1))*Gx2Sign,2,2,2);
[GAmp3,GTime3]=StdTrap(t3Start-tRamp,            ...
                       t3Start+tHalf+tRamp,      ...
                       t3Start,                          ...
                       t3Start+tHalf,                    ...
                       GxAmp*cos(AngInc * (VVar.PhaseCount - 1))*Gx3Sign,2,2,2);

GAmp=GAmp2;
GTime=GTime2;

if Gx1Sign~=0
    GAmp=[GAmp1, GAmp];
    GTime=[GTime1, GTime];
end

if Gx3Sign~=0
    GAmp=[GAmp, GAmp3];
    GTime=[GTime, GTime3];
end

[GTime,m,n]=unique(GTime);
GAmp=GAmp(m);

end

author: leoliuf

repo: MRiLab

save_path: github-repos/MATLAB/leoliuf-MRiLab


text:
% @authors:     Ahmad Humayun
% @contact:     ahumayun@cc.gatech.edu
% @affiliation: Georgia Institute of Technology
% @date:        Fall 2013 - Summer 2014

function [val] = compute_sp_unary_values(abst_obj, seed_region)
    % convert from superpixel to pixel level seeds
    pxl_seed_region = ismember(abst_obj.seg_obj.sp_data.sp_seg, ...
                               find(seed_region));
    pxl_seed_region = pxl_seed_region(:);

    % compute affinities based on pixel seed region
    I = abst_obj.seg_obj.I;
    if(size(I, 3) ~= 3)
        I(:,:,2) = I(:,:,1);
        I(:,:,3) = I(:,:,1);
    end

    %val = obj.compute_unary_values_patch_rgb(seed_region);
    % compute inverse distance (capacity) for each pixel from seed region
    val = compute_unary_values_rgb(I, pxl_seed_region, ...
                                   abst_obj.graph_seed_frame_weight, ...
                                   abst_obj.graph_unary_exp_scale);

    % sum values over whole superpixels
    val = accumarray(abst_obj.seg_obj.sp_data.sp_seg(:), val);
end

function val = compute_unary_values_rgb(I, seed_region, multiplier, ...
                                        exp_scale)
    K = 5; % 10

    %%%%%% RGB space %%%%%%%%%%%
    pix = reshape(I, size(I,1)*size(I,2), 3);

    %%%%%%% HSV space %%%%%%%%%%%
    %pix = uint8(255*reshape(rgb2hsv(obj_I), size(obj_I,1)* size(obj_I,2), 3));

    %%%%%%% LAB space %%%%%%%%%%%%
    %pix = reshape(rgb2lab(obj_I), size(obj_I,1)* size(obj_I,2), 3);
    %pix(:,1) = pix(:,1)*2.55;
    %pix(:,[2 3]) = 255*((pix(:,[2 3]) + 110) / 220);
    %pix = uint8(pix);
    %t = tic();

    % get color values for the seed region
    seed_pix = pix(seed_region,:)';

    if K > size(seed_pix,2)
        K = size(seed_pix,2);
%        seed_pix = [seed_pix, seed_pix];
    end

    % get K representative colors from the seed region
    centers = vl_ikmeans(seed_pix, K, 'Method', 'lloyd');  % centers in columns!
    %toc(t);
    %obj.show_centers_colors(centers);

    %center = mean(double(pix_rgb(seed_region,:)));
    %dists = sum(abs(pix_rgb - center(ones(size(obj_I,1)* size(obj_I,2),1),:)),2);

    %ext_pix_rgb = pix(:,:,ones(K,1));

    dists = inf(size(pix,1),1);
    pix = single(pix);

    % compute the l1 norm of each pixel from one of the K cluster centers.
    % Store it if its the shortest distance seen so far
    for i=1:K
        center = single(centers(:,i)');
        dists = min(dists, sum(abs(bsxfun(@minus, pix, center)),2));
    end
    % exp(-dists x const) inverts the distance - high values will become
    % low (values will range between 0 and 1)
    val = double(0.3 * multiplier * exp(-dists*exp_scale));
end

author: Cloud-CV

repo: object-proposals


text:
impts=zeros(yw*exf,xw*exf);
n_rendered=0;
weight=str2double(get(handles.weight,'String'));
size_fac=str2double(get(handles.size_fac_edit,'String'));

for i=nstart:nend
    if xc(i)>=1 && yc(i)>=1 && xc(i)<xw*exf && yc(i)<yw*exf && N(i)>0
      wide=ceil(size_fac*lppix(i)*1.5+1);
%       if wide>20
%           wide=20;
%       end
      if xc(i)-wide>=1 && xc(i)+wide<xw*exf && yc(i)-wide>=1 && yc(i)+wide<yw*exf
        n_rendered=n_rendered+1;
        for j=xc(i)-wide:xc(i)+wide
          for k=yc(i)-wide:yc(i)+wide
            dx=double(j)-xf(i);
            dy=double(k)-yf(i);
            int=pi*lp2pix(i)*size_fac;
            a=exp(-2*(dx*dx+dy*dy)/(size_fac*size_fac*lp2pix(i)))*N(i)*weight/int;
            impts(k,j)=impts(k,j)+a;
          end
        end
      end
    end
    waitbarxmod(i/nend,w); %update
end

thresh=impts*0+1;
impts=thresh.*(impts>thresh)+impts.*(impts<=thresh);
clear thresh;

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function [vw,pos] = addROI(vw,ROI,select)
% Adds an ROI to the ROIs list of a view.
%
% [vw,pos] = addROI(vw,ROI,[select])
%
% If select is non-zero (the default), selects it.
% If requested, the position of the ROI in the list is passed
% back.
%
% If you change this function make parallel changes in:
%   all addROI*.m functions
%
% djh, 8/98
%
% AW/BW:  11.14.00 Modified for R12
%         When the vw.ROIs is initialized to [], we cannot
%         assign it a structure in Matlab R12.  So, when it is null,
%         we remove the ROIs field before assigning.
if notDefined('select'), select=1; end

pos = 1;
if isfield(vw,'ROIs')
    if isempty(vw.ROIs),     vw = rmfield(vw,'ROIs');
    else                       pos = length(vw.ROIs)+1;
    end
end

% check ROI format
roiFields = {'color' 'coords' 'name' 'viewType' ...
            'created' 'modified' 'comments'};
extra = setdiff(fieldnames(ROI), roiFields);
if ~isempty(extra)
    for f = extra, ROI = rmfield(ROI, f{1}); end
end

for f = fieldnames(ROI)'
    vw.ROIs(pos).(f{1}) = ROI.(f{1});
end

if select
    vw = selectROI(vw,pos);
    % for volume views, find the ROI as it's loaded
    viewType = viewGet(vw,'viewType');
    if (isequal(viewType,'Volume') || isequal(viewType,'Gray'))
        if checkfields(vw, 'ui', 'sliceNumFields') && ~isempty(ROI.coords)
            vw = selectCurROISlice(vw);
            vw = refreshScreen(vw);
        end
    end
end

% Set the ROI popup menu
if checkfields(vw, 'ui', 'popup')
    setROIPopup(vw, {vw.ROIs.name}, vw.selectedROI);
end

return;

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function value = year_is_leap_gregorian ( y )

%*****************************************************************************80
%
%% YEAR_IS_LEAP_GREGORIAN returns TRUE if the Gregorian year was a leap year.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 December 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, the year to be checked.
%
%    Output, logical VALUE, TRUE if the year was a leap year,
%    FALSE otherwise.
%
  if ( y == 0 )
    value = 0;
    return
  end
%
%  BC years have to have 1 added to them to make a proper leap year evaluation.
%
  y2 = y_common_to_astronomical ( y );

  if ( mod ( y2, 400 ) == 0 )
    value = 1;
  elseif ( mod ( y2, 100 ) == 0 )
    value = 0;
  elseif ( mod ( y2, 4 ) == 0 )
    value = 1;
  else
    value = 0;
  end

  return
end


text:
%% Models
% Instantiate a Transitionamic model
transition_model = ConstantVelocityX('NumDims',2,'VelocityErrVariance',0.0001);

% Instantiate an Observation model
measurement_model = LinearGaussianX('NumMeasDims',2,'NumStateDims',4,'MeasurementErrVariance',0.02,'Mapping',[1 3]);
%measurement_model = RangeBearing2CartesianX('NumStateDims',4,'MeasurementErrVariance',[0.001,0.02],'Mapping',[1 3]);

% Compile the State-Space model
model = StateSpaceModelX(transition_model,measurement_model);

%% Groud-Truth Simulator
num_timesteps = 100;
timestep_duration = duration(0,0,5);
initial_state = GroundTruthStateX([0; 0; 0; 0], datetime());
gnd_sim = SingleTargetGroundTruthSimulatorX('Model',model, ...
                                            'InitialState', initial_state,...
                                            'NumTimesteps', num_timesteps,...
                                            'TimestepDuration', timestep_duration);

%% Simulate Ground-Truth
track = gnd_sim.simulate();

%% Measurement simulator
det_sim = SingleTargetMeasurementSimulatorX(model);

%% Simulate measurements
measurements = det_sim.simulate(track);

%% Plot the output
plotter = BasicPlotterX(model);

plotter.figure();
plotter.plotObject(track);
plotter.plotObject(measurements);

author: sglvladi

repo: TrackingX

save_path: github-repos/MATLAB/sglvladi-TrackingX


text:
% This file is part of the project NILM-Eval (https://github.com/beckel/nilm-eval).
% Licence: GPL 2.0 (http://www.gnu.org/licenses/gpl-2.0.html)
% Copyright: ETH Zurich, 2014
% Author: Romano Cicchetti

function [events] = getEvents(total_consumption, threshold)

% extract events

% define parameters and data structures
eventsTotalStep = zeros(length(total_consumption), 1);
eventsMaxStep = zeros(length(total_consumption), 1);
eventsDuration = ones(length(total_consumption), 1);
eventsStartTime = ones(length(total_consumption), 1);
maxEventDuration = 20; % maximum duration of an event in seconds
minEventDuration = 5;
delta_p_prev = 0;      % previous difference between two consecutive power values
p_t_prev = 0;          % previous power value
index = 0;             % index of an event
startTime = 1;         % start time of an event

% for each time step
for i = 1:length(total_consumption)
    p_t = total_consumption(i, 1);
    delta_p = p_t - p_t_prev;

    % a power step between two consecutive power values is ignored if the
    % difference between the two power values is smaller than a threshold
    if (abs(delta_p) > threshold)
        signsEqual = sign(delta_p) == sign(delta_p_prev);
        if (( i - startTime > maxEventDuration || ~signsEqual) && (i - startTime > minEventDuration || startTime == 1))
            % create a new event and assign power step to it
            index = index + 1;
            startTime = i;
            eventsStartTime(index) = startTime;
            delta_p_prev = delta_p;
        end

        % update/initialized maximum power step of the existing/new event
        % if necessary
        if (abs(delta_p) > abs(eventsMaxStep(index)))
            eventsMaxStep(index) = delta_p;
        end
        % update/initialize duration and total power step of the existing/new
        % event
        eventsDuration(index) = i - startTime + 1;
        eventsTotalStep(index) = eventsTotalStep(index) + delta_p;
    end
    p_t_prev = p_t;
end

% cut the event data structures to only include the extracted events
eventsTotalStep = eventsTotalStep(1:index, 1);
eventsMaxStep = eventsMaxStep(1:index, 1);
eventsDuration = eventsDuration(1:index, 1);
eventsStartTime = eventsStartTime(1:index, 1);
events = [eventsTotalStep, eventsMaxStep, eventsDuration, eventsStartTime];
wrong_sign_idx = sign(events(:,1)) ~= sign(events(:,2));
events(wrong_sign_idx,2) = -1*events(wrong_sign_idx,2);
idx_over_10 = abs(eventsTotalStep(:,1)) > 5;
events = events(idx_over_10, :);
end

author: beckel

repo: nilm-eval

save_path: github-repos/MATLAB/beckel-nilm-eval


text:
function uh = CurlCurl2dNd0(node,elem,bdFlag,pde)
%% CURLCURL2DND0 curlcurl equation: lowest order edge element on triangular mesh
% rot(\mu^{-1} curl u) + \kappa u = f in \Omega
% u\times n = 0 on \Gamma_D
% \mu^{-1} curl u = g_N on \Gamma_N

% Solve u_h in Nd0 \cap {u \times n = 0 on \Gamma_D} = V_h
% (\mu^{-1} curl u_h, curl v_h) + (\kappa u_h, v_h)
% = (f, v_h) + <v_h \cdot \tau, g_N>_{\Gamma_N} for any v_h \in V_h

% basis function associated with an edge |e|
% \phi_e = \frac{|e|}{2|K|} (\lamda_{i+1} n_{i-1} - \lambda_{i+1} n_{i-1})
% implented based on an older iFEM circa 2010.
%
% For 3D curl-curl problems
% See also Maxwell, cubeMaxwell
%
%
% Copyright (C) Long Chen. See COPYRIGHT.txt for details.
%%
NT = size(elem,1);
T = auxstructure(elem);
elem2edge = T.elem2edge;
edge = T.edge;
elem2edgeSign = ones(NT,3);
totalEdge = uint32([elem(:,[2,3]); elem(:,[3,1]); elem(:,[1,2])]);
idx = (totalEdge(:,1)>totalEdge(:,2));
elem2edgeSign(idx) = -1;

if ~isfield(pde,'mu'), pde.mu = 1; end
if ~isfield(pde,'kappa'), pde.kappa = 1; end
if ~isfield(pde,'g_D'), pde.g_D = []; end
if ~isfield(pde,'g_N'), pde.g_N = []; end

NE = size(edge,1);
uh = zeros(NE,1);
g_D = pde.g_D;
g_N = pde.g_N;
f_x = pde.f_x;
f_y = pde.f_y;
mu = pde.mu;
kappa = pde.kappa;

%% Boundary
idxD = (bdFlag(:) == 1);     % all Dirichlet edges in bdFlag
isFixedEdge = false(NE,1);
isFixedEdge(elem2edge(idxD)) = true;  % index of fixed boundary edges
freeEdge = ~isFixedEdge;

idxN = (bdFlag(:) == 2);     % all Neumann edges in bdFlag
Neumann = edge(elem2edge(idxN),:);

%% geometric quantities
%edge vector which follows elem2edge counterclockwisely
ve(:,:,1) = node(elem(:,3),:)-node(elem(:,2),:);
ve(:,:,2) = node(elem(:,1),:)-node(elem(:,3),:);
ve(:,:,3) = node(elem(:,2),:)-node(elem(:,1),:);
area = 0.5*abs(-ve(:,1,3).*ve(:,2,2)+ve(:,2,3).*ve(:,1,2));

%length_ve(:,:,i) is the length of i^th edge
length_ve = sqrt(sum(ve.^2,2));
length_ve = reshape(length_ve,NT,3);

%outer normal vector of each edge which follows the index of elem2edge
ne = [ve(:,2,:), -ve(:,1,:)];

%%
%M is the mass matrix M_{ij} = (\kappa \phi_i, \phi_j)
%B is the stiffness matrix B_{ij} = (\mu^{-1} curl \phi_i, curl \phi_j)
c = [3 1 2 3 1];
%cyclic group of {1,2,3}: c(i)=i-1, c(i+2)=i+1

M = sparse(NE,NE);
B = sparse(NE,NE);
muinv = 1/mu;

for i = 1:3
    for j = 1:3
        sij = elem2edgeSign(:,i).*elem2edgeSign(:,j);

        if i==j
            nini = length_ve(:,i).^2;
            njnk = dot(ne(:,:,c(i)),ne(:,:,c(i+2)),2);
            Mij = kappa.*length_ve(:,i).*(nini - 3*njnk)./(24*area);
        else
            ninj = dot(ne(:,:,i),ne(:,:,j),2);
            ni2 = length_ve(:,i).^2;
            nj2 = length_ve(:,j).^2;
            Mij = -sij.*kappa.*length_ve(:,i).*length_ve(:,j).*(ni2 + nj2 + 3*ninj)./(24*area);
        end

        Bij = muinv.*sij.*length_ve(:,i).*length_ve(:,j)./area;

        M = M + sparse(elem2edge(:,i),elem2edge(:,j),Mij,NE,NE);
        B = B + sparse(elem2edge(:,i),elem2edge(:,j),Bij,NE,NE);
    end
end

A = M+B;

%% rhs (old hard-coded implementation)
Fx = quadelem2node(node,elem,f_x);
Fy = quadelem2node(node,elem,f_y);

bt1x = -0.5*elem2edgeSign(:,1).*length_ve(:,1)...
    .*(Fx(:,2).*ne(:,1,3) - Fx(:,3).*ne(:,1,2))./area;
bt2x = -0.5*elem2edgeSign(:,2).*length_ve(:,2)...
    .*(Fx(:,3).*ne(:,1,1) - Fx(:,1).*ne(:,1,3))./area;
bt3x = -0.5*elem2edgeSign(:,3).*length_ve(:,3)...
    .*(Fx(:,1).*ne(:,1,2) - Fx(:,2).*ne(:,1,1))./area;

bt1y = -0.5*elem2edgeSign(:,1).*length_ve(:,1)...
    .*(Fy(:,2).*ne(:,2,3) - Fy(:,3).*ne(:,2,2))./area;
bt2y = -0.5*elem2edgeSign(:,2).*length_ve(:,2)...
    .*(Fy(:,3).*ne(:,2,1) - Fy(:,1).*ne(:,2,3))./area;
bt3y = -0.5*elem2edgeSign(:,3).*length_ve(:,3)...
    .*(Fy(:,1).*ne(:,2,2) - Fy(:,2).*ne(:,2,1))./area;

bt1 = bt1x + bt1y;
bt2 = bt2x + bt2y;
bt3 = bt3x + bt3y;

F = accumarray(elem2edge(:),[bt1;bt2;bt3],[NE 1]);

%% Dirichlet Boundary
if ~isempty(pde.g_D)
    fixedEdge = edge(isFixedEdge,:);
    signFixedEdge = elem2edgeSign(idxD);
    Nve = node(fixedEdge(:,1),:) - node(fixedEdge(:,2),:);
    NveLength = sqrt(sum(Nve.^2,2));
    GD = quadedge(node,fixedEdge,g_D).*signFixedEdge./NveLength;
    uh(isFixedEdge) = GD;
end

%% Neumann Boundary
if (~isempty(Neumann) && ~isempty(pde.g_N))
    signNeumannEdge = elem2edgeSign(idxN);
    GN = quadedge(node,Neumann,g_N).*signNeumannEdge;
    F = F + accumarray(idxN(:),GN(:),[NE,1]);
end

%direct solver
uh(freeEdge) = A(freeEdge,freeEdge)\F(freeEdge);

repo: ifem


text:
 function g = huber_dpot(t, d)
%function g = huber_dpot(t, d)
% huber potential derivative function
g = t;
ii = abs(t) > d;
g(ii) = d * sign(t(ii));

author: JeffFessler

repo: mirt

save_path: github-repos/MATLAB/JeffFessler-mirt


text:
function [ out ] = opt_selectField( in, field )
% opt_selectField:
%
% Description:
%     This function takes fields of input data structure altogether
%
% Example:
%     field={'x','t','fs','y_dec','y_logic','y_class','class', 'chan'};
%     out=opt_selectField(EEG,field);
%
% Input:
%     in    - EEG data structure
%     field - Fields you want to take
% Output:
%     out   - Data structure with fields combined
%
% Min-Ho, Lee
% mhlee@image.korea.ac.kr
%

if isempty(field)
    out=struct;
else
    for i=1:length(field)
        if isfield(in,field{i})
            out.(field{i})=in.(field{i});
        end
    end

end

end

author: PatternRecognition

repo: OpenBMI


text:
function value = r4_tan ( x )

%*****************************************************************************80
%
%% R4_TAN evaluates the tangent of an R4 argument.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 September 2011
%
%  Author:
%
%    Original FORTRAN77 version by Wayne Fullerton.
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Wayne Fullerton,
%    Portable Special Function Routines,
%    in Portability of Numerical Software,
%    edited by Wayne Cowell,
%    Lecture Notes in Computer Science, Volume 57,
%    Springer 1977,
%    ISBN: 978-3-540-08446-4,
%    LC: QA297.W65.
%
%  Parameters:
%
%    Input, real X, the argument.
%
%    Output, real VALUE, the tangent of X.
%
  persistent nterms
  persistent sqeps
  persistent tancs
  persistent xmax
  persistent xsml

  pi2rec = 0.0116197723675813430;

  if ( isempty ( nterms ) )
    tancs = [ ...
      0.226279327631293578, ...
      0.0430179131465489618, ...
      0.0006854461068256508, ...
      0.0000110453269475970, ...
      0.0000001781747790392, ...
      0.0000000028744968582, ...
      0.0000000000463748541, ...
      0.0000000000007481760, ...
      0.0000000000000120704, ...
      0.0000000000000001947, ...
      0.0000000000000000031 ]';
    nterms = r4_inits ( tancs, 11, 0.1 * r4_mach ( 3 ) );
    xmax = 1.0 / r4_mach ( 4 );
    xsml = sqrt ( 3.0 * r4_mach ( 3 ) );
    sqeps = sqrt ( r4_mach ( 4 ) );
  end

  y = abs ( x );

  if ( xmax < y )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R4_TAN - Warning!\n' );
    fprintf ( 1, '  No precision because |X| is big.\n' );
    value = 0.0;
    return
  end
%
%  Carefully compute y * (2/pi) = (aint(y) + rem(y)) * (.625 + pi2rec)
%  = aint(.625*y) + rem(.625*y) + y*pi2rec  =  aint(.625*y) + z
%  = aint(.625*y) + aint(z) + rem(z)
%
  ainty = floor ( y );
  yrem = y - ainty;
  prodbg = 0.625 * ainty;
  ainty = floor ( prodbg );
  y = ( prodbg - ainty ) + 0.625 * yrem + y * pi2rec;
  ainty2 = floor ( y );
  ainty = ainty + ainty2;
  y = y - ainty2;

  ifn = floor ( mod ( ainty, 2.0 ) );

  if ( ifn == 1 )
    y = 1.0 - y;
  end

  if ( 1.0 - y < abs ( x ) * sqeps )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R4_TAN - Warning!\n' );
    fprintf ( 1, '  Answer < half precision.\n' );
    fprintf ( 1, '  |X| big or X near pi/2 or 3*pi/2.\n' );
  end

  if ( y == 1.0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R4_TAN - Fatal error!\n' );
    fprintf ( 1, '  X is pi/2 or 3*pi/2.\n' );
    error ( 'R4_TAN - Fatal error!' )
  end

  if ( y <= 0.25 )

    value = y;
    if ( xsml < y )
      value = y * ( 1.5 ...
        + r4_csevl ( 32.0 * y * y - 1.0, tancs, nterms ) );
    end

  elseif ( y <= 0.5 )

    value = 0.5 * y * ( 1.5 ...
      + r4_csevl ( 8.0 * y * y - 1.0, tancs, nterms ) );

    value = 2.0 * value / ( 1.0 - value * value );

  else

    value = 0.25 * y * ( 1.5 ...
      + r4_csevl ( 2.0 * y * y - 1.0, tancs, nterms ) );
    value = 2.0 * value / ( 1.0 - value * value );
    value = 2.0 * value / ( 1.0 - value * value );

  end

  if ( x < 0.0 )
    value = - abs ( value );
  elseif ( 0.0 < x )
    value = + abs ( value );
  end

  if ( ifn == 1 )
    value = - value;
  end

  return
end


text:
function idx = findClosestCentroids(X, centroids)
%FINDCLOSESTCENTROIDS computes the centroid memberships for every example
%   idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids
%   in idx for a dataset X where each row is a single example. idx = m x 1
%   vector of centroid assignments (i.e. each entry in range [1..K])
%

% Set K
K = size(centroids, 1);

% You need to return the following variables correctly.
idx = zeros(size(X,1), 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Go over every example, find its closest centroid, and store
%               the index inside idx at the appropriate location.
%               Concretely, idx(i) should contain the index of the centroid
%               closest to example i. Hence, it should be a value in the
%               range 1..K
%
% Note: You can use a for-loop over the examples to compute this.
%

t = zeros(1, K);
for i = 1:length(idx)
    for j = 1:K
        temp = centroids(j, :) - X(i, :);
        t(j) = temp * temp';
    end
    [~, index] = min(t);
    idx(i) = index;
end

% =============================================================

end

repo: machine-learning


text:
function wtime_test02 ( )

%*****************************************************************************80
%
%% TEST02 times the vectorized EXP routine.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 August 2010
%
%  Author:
%
%    John Burkardt
%
  n_log_min = 12;
  n_log_max = 22;
  n_min = 2^n_log_min;
  n_max = 2^n_log_max;
  n_rep = 5;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST02\n' );
  fprintf ( 1, '  Time vectorized operations:\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '    y(1:n) =        x(1:n)  \n' );
  fprintf ( 1, '    y(1:n) = PI *   x(1:n) )\n' );
  fprintf ( 1, '    y(1:n) = sqrt ( x(1:n) )\n' );
  fprintf ( 1, '    y(1:n) = exp  ( x(1:n) )\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Data vectors will be of minimum size %d\n', n_min );
  fprintf ( 1, '  Data vectors will be of maximum size %d\n', n_max );
  fprintf ( 1, '  Number of repetitions of the operation: %d\n', n_rep );

  for func = 1 : 4

    for i_rep = 1 : n_rep

      for n_log = n_log_min : n_log_max

        n = 2^( n_log );

        x = rand ( n, 1 );

        seconds = wtime ( );

        if ( func == 1 )
          y(1:n) = x(1:n);
        elseif ( func == 2 )
          y(1:n) = pi * x(1:n);
        elseif ( func == 3 )
          y(1:n) = sqrt ( x(1:n) );
        elseif ( func == 4 )
          y(1:n) = exp ( x(1:n) );
        end

        delta(n_log,i_rep) = wtime ( ) - seconds;

      end

    end

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Timing results:\n' );
    fprintf ( 1, '\n' );
    fprintf ( 1, '    Vector Size  Rep #1        Rep #2        ' );
    fprintf ( 1, 'Rep #3        Rep #4        Rep #5\n' );
    fprintf ( 1, '\n' );
    for n_log = n_log_min : n_log_max
      n = 2^( n_log );
      fprintf ( 1, '  %8d  %12f  %12f  %12f  %12f  %12f\n', ...
        n, delta(n_log,1:n_rep) );
    end

  end

  return
end


text:
function b = subset_complement ( n, a )

%*****************************************************************************80
%
%% SUBSET_COMPLEMENT computes the complement of a set.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 August 2011
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Donald Kreher, Douglas Simpson,
%    Combinatorial Algorithms,
%    CRC Press, 1998,
%    ISBN: 0-8493-3988-X,
%    LC: QA164.K73.
%
%  Parameters:
%
%    Input, integer N, the order of the master set, of which A is
%    a subset.  N must be positive.
%
%    Input, integer A(N), a subset of the master set.
%    A(I) = 0 if the I-th element is in the subset A, and is
%    1 otherwise.
%
%    Output, integer B(N), the complement of A.
%

%
%  Check.
%
  subset_check ( n, a );

  b(1:n) = 1 - a(1:n);

  return
end


text:
function [gIX, numK] = SqueezeGroupIX(gIX)
U = unique(gIX);
numK = length(U);
for i = 1:numK
    old = U(i);
    gIX(gIX==old) = i;
end
end

author: xiuyechen

repo: FishExplorer


text:
function result = polygon_integral_yy ( n, v )

%*****************************************************************************80
%
%% POLYGON_INTEGRAL_YY integrates the function Y*Y over a polygon.
%
%  Discussion:
%
%    The polygon is bounded by the points (X(1:N), Y(1:N)).
%
%    INTEGRAL = (1/12) * sum ( 1 <= I <= N )
%      - ( Y(I)^3 + Y(I)^2 * Y(I-1) + Y(I) * Y(I-1)^2 + Y(I-1)^3 )
%      * ( X(I) - X(I-1) )
%
%    where X(0) and Y(0) should be replaced by X(N) and Y(N).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 March 2005
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    S F Bockman,
%    Generalizing the Formula for Areas of Polygons to Moments,
%    American Mathematical Society Monthly,
%    1989, pages 131-132.
%
%  Parameters:
%
%    Input, integer N, the number of vertices of the polygon.
%    N should be at least 3 for a nonzero result.
%
%    Input, real V(2,N), the coordinates of the vertices
%    of the polygon.  These vertices should be given in
%    counter-clockwise order.
%
%    Output, real RESULT, the value of the integral.
%
  result = 0.0;

  if ( n < 3 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'POLYGON_INTEGRAL_YY - Warning!\n' );
    fprintf ( 1, '  The number of polygonal vertices must be\n' );
    fprintf ( 1, '  at least 3, but the input polygon has N = %d\n', n );
    error ( 'POLYGON_INTEGRAL_YY - Warning!' );
  end

  for i = 1 : n

    if ( i == 1 )
      im1 = n;
    else
      im1 = i - 1;
    end

    result = result - ( v(2,i).^3 + v(2,i).^2 * v(2,im1) ...
      + v(2,i) * v(2,im1).^2 + v(2,im1).^3 ) * ( v(1,i) - v(1,im1) );

  end

  result = result / 12.0;

  return
end


text:
% Fix ac-pc origin misalignment in t1's and tensors. (y1)
spm_defaults; global defaults;
estParams = defaults.coreg.estimate;
estParams.params = [0 0 0];
bd = '/biac3/wandell4/data/reading_longitude/dti_y1';
od = '/biac3/wandell4/data/reading_longitude/dti_y1_old';
d = dir(bd);
for(ii=1:length(d))
  dtFn = fullfile(od,d(ii).name,[d(ii).name '_dt6_noMask.mat']);
  t1Fn = fullfile(bd,d(ii).name,'t1','t1.nii.gz');
  dtiFn = fullfile(bd,d(ii).name,'dti06','bin');
  if(d(ii).isdir && exist(dtFn,'file'))
	dt = load(dtFn,'anat');
	Vdst.uint8 = uint8(mrAnatHistogramClip(double(dt.anat.img), 0.4, 0.99)*255+0.5);
	Vdst.mat = dt.anat.xformToAcPc;
	clear dt;
	if(~exist(t1Fn,'file'))
	  disp(['ERROR: t1 not found- skipping t1 for ' d(ii).name '.']);
	else
	  disp(['Processing t1 for ' d(ii).name '...']);
	  t1 = niftiRead(t1Fn);
	  Vsrc.uint8 = uint8(mrAnatHistogramClip(double(t1.data), 0.4, 0.99)*255+0.5);
	  Vsrc.mat = t1.qto_xyz;
	  x = spm_coreg(Vdst,Vsrc,estParams);
	  x = round(x);
	  if(any(x~=0))
		xf = t1.qto_xyz;
		xf(1:3,4) = xf(1:3,4)-x';
		% o=mrAnatXformCoords(inv(xf),[0 0 0]); imagesc(t1.data(:,:,o(3))); axis image; colormap gray; hold on; plot(o(2),o(1),'ro'); hold off
		t1 = niftiSetQto(t1, xf);
		writeFileNifti(t1);
	  end
	  clear t1;
	end
	if(~exist(dtiFn,'dir')||~exist(fullfile(dtiFn,'b0.nii.gz'),'file'))
	  disp(['ERROR: dti dir not found- skipping tensors for ' d(ii).name '.']);
	else
	  disp(['Processing tensors for ' d(ii).name '...']);
	  b0 = niftiRead(fullfile(dtiFn,'b0.nii.gz'));
	  Vsrc.uint8 = uint8(mrAnatHistogramClip(double(b0.data), 0.4, 0.99)*255+0.5);
	  Vsrc.mat = b0.qto_xyz;
	  clear b0;
	  x = spm_coreg(Vdst,Vsrc,estParams);
	  x = round(x);
	  if(any(x~=0))
		xf = Vsrc.mat;
		xf(1:3,4) = xf(1:3,4)-x';
		% o=mrAnatXformCoords(inv(xf),[0 0 0]); imagesc(b0.data(:,:,o(3))); axis image; colormap gray; hold on; plot(o(2),o(1),'ro'); hold off
		tf = dir(fullfile(dtiFn,'*.nii.gz'));
		for(jj=1:length(tf))
		   ni = niftiRead(fullfile(dtiFn,tf(jj).name));
		   if(all(ni.qto_xyz(:)==Vsrc.mat(:)))
			 disp(['  Fixing xform in ' tf(jj).name '...']);
			 ni = niftiSetQto(ni, xf);
			 writeFileNifti(ni);
		   else
			 disp(['  ERROR: xform mismatch in ' tf(jj).name '- xform not fixed.']);
		   end
		end
	  end
	end
  end
end

%
% Fix ac-pc origin misalignment in t1's and tensors. (y2 & up)
%
spm_defaults; global defaults;
estParams = defaults.coreg.estimate;
estParams.params = [0 0 0];
d2Dir = '/biac3/wandell4/data/reading_longitude/dti_y3';
d1Dir = '/biac3/wandell4/data/reading_longitude/dti_y2';
d2 = dir(fullfile(d2Dir,'*06*'));
d1 = dir(fullfile(d1Dir,'*05*'));
d1 = {d1.name}; d2 = {d2.name};
for(ii=1:length(d2))
  y2sc = d2{ii};
  sc = explode('0',y2sc); sc = sc{1};
  y1sc = strmatch(sc,d1);
  if(isempty(y1sc)||numel(y1sc)>1)
	disp(['Problem locating previous year data for ' y2sc '- skipping.']);
	continue;
  end
  y1sc = d1{y1sc};
  y1T1Fn = fullfile(d1Dir,y1sc,'t1','t1.nii.gz');
  y2T1Fn = fullfile(d2Dir,y2sc,'t1','t1.nii.gz');
  y2DtFn = fullfile(d2Dir,y2sc,'dti06','bin');
  if(exist(y1T1Fn,'file'))
	ni = niftiRead(y1T1Fn);
	Vdst.uint8 = uint8(mrAnatHistogramClip(double(ni.data), 0.4, 0.99)*255+0.5);
	Vdst.mat = ni.qto_xyz;
	clear ni;
	if(~exist(y2T1Fn,'file'))
	  disp(['ERROR: t1 not found- skipping t1 for ' y2sc '.']);
	else
	  disp(['Processing t1 for ' y2sc '...']);
	  ni = niftiRead(y2T1Fn);
	  Vsrc.uint8 = uint8(mrAnatHistogramClip(double(ni.data), 0.4, 0.99)*255+0.5);
	  Vsrc.mat = ni.qto_xyz;
	  x = spm_coreg(Vdst,Vsrc,estParams);
	  x = round(x);
	  if(any(x~=0))
		xf = ni.qto_xyz;
		xf(1:3,4) = xf(1:3,4)-x';
        % o=mrAnatXformCoords(inv(xf),[0 0 0]); imagesc(ni.data(:,:,o(3))); axis image; colormap gray; hold on; plot(o(2),o(1),'ro'); hold off
		ni = niftiSetQto(ni, xf);
		writeFileNifti(ni);
	  end
	  clear ni;
	end
	if(~exist(y2DtFn,'dir')||~exist(fullfile(y2DtFn,'b0.nii.gz'),'file'))
	  disp(['ERROR: dti bin dir not found- skipping tensors for ' y2sc '.']);
	else
	  disp(['Processing tensors for ' y2sc '...']);
	  b0 = niftiRead(fullfile(y2DtFn,'b0.nii.gz'));
	  Vsrc.uint8 = uint8(mrAnatHistogramClip(double(b0.data), 0.4, 0.99)*255+0.5);
	  Vsrc.mat = b0.qto_xyz;
	  clear b0;
	  x = spm_coreg(Vdst,Vsrc,estParams);
	  x = round(x);
	  if(any(x~=0))
        xf = Vsrc.mat;
        xf(1:3,4) = xf(1:3,4)-x';
		% o=mrAnatXformCoords(inv(xf),[0 0 0]); imagesc(b0.data(:,:,o(3))); axis image; colormap gray; hold on; plot(o(2),o(1),'ro'); hold off
		tf = dir(fullfile(y2DtFn,'*.nii.gz'));
		for(jj=1:length(tf))
		   ni = niftiRead(fullfile(y2DtFn,tf(jj).name));
		   if(all(ni.qto_xyz(:)==Vsrc.mat(:)))
			 disp(['  Fixing xform in ' tf(jj).name '...']);
			 ni = niftiSetQto(ni, xf);
			 writeFileNifti(ni);
		   else
			 disp(['  ERROR: xform mismatch in ' tf(jj).name '- xform not fixed.']);
		   end
		end
	  end
	end
  end
end

%
% Making an fMRI movie:
%
ni = niftiRead('214_visual_mcf.nii.gz');
sliceNum = 10;
sz = size(ni.data);
ni.data = uint8(mrAnatHistogramClip(single(ni.data),0.4,0.99)*255);
M = squeeze(ni.data(:,:,sliceNum,:));
clear ni;
M = flipdim(permute(M,[2,1,3]),1);

% Autocrop the movie frames
mask = imblur(mean(M,3),2)>40;
tmp = find(sum(mask,2));
crop(:,1) = [min(tmp) max(tmp)];
tmp = find(sum(mask,1));
crop(:,2) = [min(tmp) max(tmp)];
pad = 5;
if(any(diff(crop)./sz([1:2]) < 0.8))
    crop(1,:) = max([1 1],crop(1,:)-pad);
    crop(2,:) = min(sz([1:2]),crop(2,:)+pad);
    [X,Y,Z] = ndgrid([crop(1,1):crop(2,1)],[crop(1,2):crop(2,2)],[1:sz(3)]);
    x = sub2ind(sz,X(:), Y(:), Z(:)); clear X Y Z;
    newSz = [diff(crop)+1 sz(3)];
    M = reshape(M(x),newSz);
end

outBaseName = '/tmp/fmri2_mcf';
%mpOrig = mplay(int2struct(M),10);
% Save a gif. Cropping and using only 64 colors makes for a
% fairly compact file, suitable for a website. Using 256 colors
% might make a slightly nicer image.
M = M./4; M(M>63) = 63;
% The gif writer wants a 4d dataset (???)
M = reshape(M,[size(M,1),size(M,2),1,size(M,3)]);
imwrite(M,gray(64),[outBaseName '.gif'],'DelayTime',0.1,'LoopCount',65535);

%
% Hack to allow old CINCH to read new-format data
%
bd = '/biac3/wandell4/data/reading_longitude/dti_y4/';
d = dir(fullfile(bd,'*0*'));
for(ii=1:length(d))
   binDir = fullfile(bd,d(ii).name,'dti06','bin');
   t1 = fullfile(bd,d(ii).name,'t1','t1.nii.gz');
   bkDir = fullfile(binDir,'backgrounds');
   if(exist(binDir,'dir')&&exist(t1,'file')&&~exist(bkDir))
      disp(['Processing ' d(ii).name '...']);
      mkdir(bkDir);
      ni = niftiRead(t1);
      ni.data = single(mrAnatHistogramClip(double(ni.data),0.4,0.99));
      ni.fname = fullfile(bkDir,'t1.nii.gz');
      writeFileNifti(ni);
   else
      disp(['Skipping ' d(ii).name '.']);
   end
end


text:
function [cnmfAnalysisOutput] = computeCnmfSignalExtraction_v2(inputMovie,numExpectedComponents,varargin)
	% Brapper function for CNMF, update for most recent versions.
	% Building off of demo_script.m in CNMF github repo
	% Most recent commit tested on: https://github.com/epnev/ca_source_extraction/commit/187bbdbe66bca466b83b81861b5601891a95b8d1
	% https://github.com/epnev/ca_source_extraction/blob/master/demo_script_class.m
	% Biafra Ahanonu
	% started: 2016.01.20
	% inputs
		% inputMovie - a string or a cell array of strings pointing to the movies to be analyzed (recommended). Else, [x y t] matrix where t = frames.
		% numExpectedComponents - number of expected components
	% outputs
		% cnmfAnalysisOutput - structure containing extractedImages and extractedSignals along with input parameters to the algorithm
	% READ BEFORE RUNNING
		% Get CVX from http://cvxr.com/cvx/doc/install.html
		% Run the below commands in Matlab after unzipping
		% cvx_setup
		% cvx_save_prefs (permanently stores settings)

	[cnmfAnalysisOutput] = ciapkg.signal_extraction.computeCnmfSignalExtraction_v2(inputMovie,numExpectedComponents,'passArgs', varargin);
end

author: bahanonu

repo: ciatah

save_path: github-repos/MATLAB/bahanonu-ciatah


text:
function generateDoc
%generateDoc Publish the example scripts in the doc directory

%   Steven L. Eddins
%   Copyright 2008-2009 The MathWorks, Inc.

doc_dir = fullfile(fileparts(which('runtests')), '..', 'doc');
addpath(doc_dir);
cd(doc_dir)
mfiles = dir('*.m');
for k = 1:numel(mfiles)
    publish(mfiles(k).name);
    cd(doc_dir)
end

author: ricedsp


text:
function test_bug2137

% MEM 2gb
% WALLTIME 00:30:00
% DEPENDENCY

% the following lines are for interactive/manual testing
if false
  restoredefaultpath
  clear all
  addpath(dccnpath('/home/common/matlab/fieldtrip'));
  ft_defaults
end

cfg = [];
cfg.dataset = dccnpath('/home/common/matlab/fieldtrip/data/ftp/test/ctf/Subject01.ds');
data = ft_preprocessing(cfg);

cfg            = [];
cfg.detrend    = 'no';
cfg.resamplefs = 150;
data           = ft_resampledata(cfg, data);

cfg            = [];
cfg.channel    = {'MEG'};
cfg.numcomponent = 60;
comp           = ft_componentanalysis(cfg, data);

author: fieldtrip

repo: fieldtrip


text:
function [y,n] = audspacebw(fmin,fmax,varargin)
%AUDSPACEBW  Auditory scale points specified by bandwidth
%   Usage: y=audspacebw(fmin,fmax,bw,hitme);
%          y=audspacebw(fmin,fmax,bw);
%          y=audspacebw(fmin,fmax);
%          [y,n]=audspacebw(...);
%
%   `audspacebw(fmin,fmax,bw,scale)` computes a vector containing values
%   equistantly scaled between frequencies *fmin* and *fmax* on the
%   selected auditory scale.  All frequencies are specified in Hz.The
%   distance between two consecutive values is *bw* on the selected scale,
%   and the points will be centered on the scale between *fmin* and *fmax*.
%
%   See the help on |freqtoaud| to get a list of the supported values of the
%   *scale* parameter.
%
%   `audspacebw(fmin,fmax,bw,hitme,scale)` will do as above, but one of
%   the points is quaranteed to be the frequency *hitme*.
%
%   `[y,n]=audspacebw(...)` additionally returns the number of points *n* in
%   the output vector *y*.
%
%   See also: freqtoaud, audspace, audfiltbw

%   AUTHOR : Peter L. Søndergaard

% ------ Checking of input parameters ---------

if nargin<2
  error('%s: Too few input parameters.',upper(mfilename));
end;

if ~isnumeric(fmin) || ~isscalar(fmin) || fmin<0
  error('%s: fmin must be a non-negative scalar.',upper(mfilename));
end;

if ~isnumeric(fmax) || ~isscalar(fmax) || fmax<0
  error('%s: fmax must be a non-negative scalar.',upper(mfilename));
end;

if fmin>fmax
  error('%s: fmin must be less than or equal to fmax.',upper(mfilename));
end;

definput.import={'freqtoaud'};
definput.keyvals.hitme=[];
definput.keyvals.bw=1;

[flags,kv,bw]=ltfatarghelper({'bw','hitme'},definput,varargin);

if ~isnumeric(bw) || ~isscalar(bw) || bw<=0
  error('%s: bw must be a positive scalar.',upper(mfilename));
end;

%% ------ Computation --------------------------

if isempty(kv.hitme)
  % Convert the frequency limits to auds.
  audlimits = freqtoaud([fmin,fmax],flags.audscale);
  audrange  = audlimits(2)-audlimits(1);

  % Calculate number of points, excluding final point
  n         = floor(audrange/bw);

  % The remainder is calculated in order to center the points
  % correctly between fmin and fmax.
  remainder = audrange-n*bw;

  audpoints = audlimits(1)+(0:n)*bw+remainder/2;

  % Add the final point
  n=n+1;

else

  % Convert the frequency limits to auds.
  audlimits    = freqtoaud([fmin,fmax,kv.hitme],flags.audscale);
  audrangelow  = audlimits(3)-audlimits(1);
  audrangehigh = audlimits(2)-audlimits(3);

  % Calculate number of points, exluding final point.
  nlow = floor(audrangelow/bw);
  nhigh = floor(audrangehigh/bw);

  audpoints=(-nlow:nhigh)*bw+audlimits(3);
  n=nlow+nhigh+1;
end;

y = audtofreq(audpoints,flags.audscale);

author: ltfat

repo: ltfat

save_path: github-repos/MATLAB/ltfat-ltfat