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

% Last Modified by GUIDE v2.5 14-Dec-2013 21:53:39

% Begin initialization code - DO NOT EDIT
    gui_Singleton = 1;
    gui_State = struct('gui_Name',       mfilename, ...
                       'gui_Singleton',  gui_Singleton, ...
                       'gui_OpeningFcn', @rts_VesselSelectGUI_OpeningFcn, ...
                       'gui_OutputFcn',  @rts_VesselSelectGUI_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
% End initialization code - DO NOT EDIT

% --- Executes just before rts_VesselSelectGUI is made visible.
function rts_VesselSelectGUI_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 rts_VesselSelectGUI (see VARARGIN)
    global rHost;

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

    % Update handles structure
    guidata(hObject, handles);

    setappdata(hObject,'mainGUIFig',varargin{1});

    rHost = varargin{2};
    if(~isempty(rHost)) %should always be populated
        set(handles.remoteHostText,'String',rHost);
        setappdata(handles.rts_VesselSelectGUI, 'RHost',rHost);
    end

    % UIWAIT makes rts_VesselSelectGUI wait for user response (see UIRESUME)
    uiwait(handles.rts_VesselSelectGUI);
end

function testConnection(handles)
    port = 8282;
    role = 'Client';
    rHost = get(handles.remoteHostText,'String');
    set(handles.couldNotConnectLabel,'Visible', 'off');
    drawnow;

    try
        resolveip(rHost);
    catch ME
        warndlg(['Could not resolve remote host: ', getReport(ME,'extended','hyperlinks','off')]);
        return;
    end

    try
        tcpipClient = createTcpIpClient(port, role, rHost);
        writeDataToKSPTOTConnect('ConnectionCheck', [1 2 3 4 5], 'd', tcpipClient);
        set(handles.couldNotConnectLabel,'Visible', 'off');
    catch ME
%         warndlg(['Connection check failed: ', getReport(ME,'extended','hyperlinks','off')]);
        set(handles.couldNotConnectLabel,'Visible', 'on');
        disp(getReport(ME,'extended','hyperlinks','off'))
        return;
    end

    populateVesselSelectCombo(handles);
    setappdata(handles.rts_VesselSelectGUI, 'RHost', rHost);

    mainGUIFig = getappdata(handles.rts_VesselSelectGUI,'mainGUIFig');
    updateAppOptions(mainGUIFig, 'ksptot', 'rtshostname', rHost);
end

function populateVesselSelectCombo(handles)
    port = 8282;
    role = 'Client';
    rHost = get(handles.remoteHostText,'String');
    tcpipClient = createTcpIpClient(port, role, rHost);

    try
        guids = readManyStringsFromKSPTOTConnect('GetVesselIDList', '', 32, true, tcpipClient);
        if(isempty(guids))
            error('Error reading vessels from KSP.');
        end
        vesselNames = {};
        storageGUIDS = {};
        for(i=1:length(guids))
            guid = guids{i};
            fclose(tcpipClient);
            delete(tcpipClient);
            tcpipClient = createTcpIpClient(port, role, rHost);
            vesselNames{i} = [readStringFromKSPTOTConnect('GetVesselNameByGUID', guid, true, tcpipClient), ' - ', guid(1:4)];
            storageGUIDS{i} = guid;
        end

        hVesselComboBox = handles.vesselSelectComboBox;
        set(hVesselComboBox,'String',vesselNames);

        vesselGUIDData = {storageGUIDS, vesselNames};
        set(handles.rts_VesselSelectGUI,'UserData',vesselGUIDData);

        set(handles.couldNotConnectLabel,'Visible', 'off');
        set(handles.vesselSelectComboBox, 'Enable', 'on');
        set(handles.connectToRealTimeSystemButton, 'Enable', 'on');
    catch ME
        set(handles.couldNotConnectLabel,'Visible', 'on');
        set(handles.connectToRealTimeSystemButton, 'Enable','off');
        set(handles.vesselSelectComboBox, 'Enable', 'off');
        disp(ME.message);
    end
end

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

% Get default command line output from handles structure
    if(~isempty(handles))
        contents = cellstr(get(handles.vesselSelectComboBox,'String'));
        selVesselName = contents{get(handles.vesselSelectComboBox,'Value')};

        vesselGUIDData = get(handles.rts_VesselSelectGUI, 'UserData');
        vesselNames = vesselGUIDData{2};
        storageGUIDS = vesselGUIDData{1};
        selGUID = '';
        for(i=1:length(vesselNames)) %#ok<*NO4LP>
            if(strcmp(vesselNames{i}, selVesselName))
                selGUID = storageGUIDS{i};
                break;
            end
        end

        rHost = getappdata(handles.rts_VesselSelectGUI, 'RHost');
        mainGUIFig = getappdata(handles.rts_VesselSelectGUI,'mainGUIFig');
        updateAppOptions(mainGUIFig, 'ksptot', 'rtshostname', rHost);

        varargout{1} = selGUID;
        varargout{2} = rHost;
        close(hObject);
    else
        varargout{1} = [];
        varargout{2} = [];
    end
end

% --- Executes on selection change in vesselSelectComboBox.
function vesselSelectComboBox_Callback(hObject, eventdata, handles)
% hObject    handle to vesselSelectComboBox (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 vesselSelectComboBox contents as cell array
%        contents{get(hObject,'Value')} returns selected item from vesselSelectComboBox
end

% --- Executes during object creation, after setting all properties.
function vesselSelectComboBox_CreateFcn(hObject, eventdata, handles)
% hObject    handle to vesselSelectComboBox (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
end

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

% --- Executes when user attempts to close rts_VesselSelectGUI.
function rts_VesselSelectGUI_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to rts_VesselSelectGUI (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
    if(~isempty(instrfind))
        fclose(instrfind);
        delete(instrfind);
    end

    delete(hObject);
end

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

% --- Executes during object creation, after setting all properties.
function remoteHostText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to remoteHostText (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
end

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

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function vl_help(mode)
% VL_HELP VLFeat Toolbox
%   The VLFeat MATLAB toolbox provides implementations of common
%   computer vision algorithms (HOG, SIFT, dense SIFT, MSER, AIB,
%   KMEANS, learning large scale SVMs...) and many utility functions
%   (e.g. precision-recall, ROC, DET curve calculation, plotting
%   functions). To get started:
%
%   * Type vl_help doc
%   * Type vl_help online
%   * Use the help command to get information about any VLFeat function
%   * Directly check the documentation online: http://www.vlfeat.org

% Author: Andrea Vedaldi

% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

if nargin == 0
  help vl_help ;
else
  switch lower(mode)
    case 'doc', web(fullfile(vl_root, 'doc', 'index.html'), '-helpbrowser') ;
    case 'online', web('http://www.vlfeat.org/') ;
    otherwise
      error('Unkown help mode %s', mode);
  end
end

author: Cloud-CV

repo: object-proposals


text:
function compass_search_test ( )

%*****************************************************************************80
%
%% COMPASS_SEARCH_TEST tests the COMPASS_SEARCH library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 January 2012
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'COMPASS_SEARCH_TEST\n' );
  fprintf ( 1, '  MATLAB version.\n' );
  fprintf ( 1, '  Test the COMPASS_SEARCH library.\n' );

  beale_test ( );
  bohach1_test ( );
  bohach2_test ( );
  broyden_test ( );
  extended_rosenbrock_test ( );
  goldstein_price_test ( );
  himmelblau_test ( );
  local_test ( );
  mckinnon_test ( );
  powell_test ( );
  rosenbrock_test ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'COMPASS_SEARCH_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
% Copyright (C) 2018  Symeon Symeonidis, Stefanos Tsantilas, Stelios Mitilineos
% simos421@gmail.com, steftsantilas@gmail.com, smitil@gmail.com
% 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.

%This is a step by step tutorial on how to use the CST-Matlab-API
%The steps you'll see here can be applied in all of the examples that are
%found in the example folder

%First of all you need to include the main path where the m.files of the
%api are found in your computer, using the command addpath(genpath('your_path_here'))
%instead of just addpath('your_path_here') helps
%a lot because it includes subfolders also.

addpath(genpath('...\cst api')); %For instance, my path is: addpath(genpath('C:\Users\simos\Dropbox\cst api'));

%This command is used to initiate the CST application, as you can see here, it is assigned to
%the cst variable.
cst = actxserver('CSTStudio.application');

%This command is used to open a new CST project. From now on this mws
%variable will be used to operate any matlab function that is used for the
%control of CST
mws = cst.invoke('NewMWS');

%Sets default units for your project. mm, GHz e.t.c you can open
%CSTDefaultUnits to see the exact selections or if you want I have
%CSTDefineUnits function in the api Home folder that you can use to assign you own units
CstDefaultUnits(mws)

%The frequency sweep of your simulation. Here in GHz, remember that the
%CSTDefaulttUnits from before uses GHz
CstDefineFrequencyRange(mws,1.5,3.5)

%Initiates the auto-meshing
CstMeshInitiator(mws)

%This one defines your boundaries, here we are using expanded open since
%our structure is not some kind of waveguide or unit cell

%Remember that you must define your boundary according to your
%lowest frequency of simulation (minfrequency), here it's 1.5GHz
Xmin='expanded open';
Xmax='expanded open';
Ymin='expanded open';
Ymax='expanded open';
Zmin='expanded open';
Zmax='expanded open';
minfrequency = 1.5;
CstDefineOpenBoundary(mws,minfrequency,Xmin,Xmax,Ymin,Ymax,Zmin,Zmax)

%This function defines the Backround material, here we are using the
%default assignment of CST which is vacuum (permittivity=permeability=1)
%Once again, XminSpace, Xmaxspace e.t.c are the default assignments of CST
%for antennas
XminSpace = 0;
XmaxSpace = 0;
YminSpace = 0;
YmaxSpace = 0;
ZminSpace = 0;
ZmaxSpace = 0;
CstDefineBackroundMaterial(mws,XminSpace,XmaxSpace, YminSpace, YmaxSpace, ZminSpace, ZmaxSpace)

%These two functions are material properties functions. Here there is a
%little trick: You can't call and assign a material from the CST library using matlab or any kind of code (besides PEC).
%It is a bit more complicated, you need to see the properties of the
%desired material in CST library and make a matlab function with all these properties, name the material and call it in your code by that name.
%This is a painfull process but I've managed to replicate some of the most
%important. You can find them in the materials folder of the API, once you
%get a grip of how my code works feel free to add more materials to that
%folder

%Here I am calling Copper annealed lossy and FR4 lossy, after these two
%function I can just write their names as a string and assign them to any
%desired shape
CstCopperAnnealedLossy(mws)
CstFR4lossy(mws)

W = 28.45; %Width of the patch
L = 28.45; %Lenght of the patch
Fi = 9; %Depth of the cut inside the microstrip
Wf = 1.137;%Width of the feedline
Gpf=1; %Width of the empty space slot
Lg = 2*L;%Length of the ground
Wg = 2*W;%Width of the ground
Ht = 0.035;%Height of the copper
Hs = 1.6;% Height of the substrate

%Cstbrick creates a brick for the groundplane. Notice how I just need to do this:
%material ='Copper (annealed)'; and the material of the brick will be
%copper, that's because I already called CstCopperAnnealedLossy(mws) before
Name = 'Groundplane';
component = 'component1';
material = 'Copper (annealed)';
Xrange = [-0.5*Wg 0.5*Wg];
Yrange = [-0.5*Lg 0.5*Lg];
Zrange = [0 Ht];
Cstbrick(mws, Name, component, material, Xrange, Yrange, Zrange)

%This creates the substrate
Name = 'Substrate';
component = 'component1';
material = 'FR-4 (lossy)';
Xrange = [-0.5*Wg 0.5*Wg];
Yrange = [-0.5*Lg 0.5*Lg];
Zrange = [Ht Ht+Hs];
Cstbrick(mws, Name, component, material, Xrange, Yrange, Zrange)

%This one creates the patch
Name = 'Patch';
component = 'component1';
material = 'Copper (annealed)';
Xrange = [-W/2 W/2];
Yrange = [-L/2 L/2];
Zrange = [Ht+Hs Ht+Hs+Ht];
Cstbrick(mws, Name, component, material, Xrange, Yrange, Zrange)

%Here I am cutting the patch to fit the feedline
Name = 'Empty space';
component = 'component1';
material = 'Copper (annealed)';
Xrange = [-((Wf/2)+Gpf)  ((Wf/2)+Gpf)];
Yrange = [-L/2+Fi -L/2];
Zrange = [Ht+Hs Ht+Hs+Ht];
Cstbrick(mws, Name, component, material, Xrange, Yrange, Zrange)

%This subtracts two components
component1 = 'component1:Patch';
component2 = 'component1:Empty space';
CstSubtract(mws,component1,component2)

%This creates the feedline
Name = 'FeedLine';
component = 'component1';
material = 'Copper (annealed)';
Xrange = [-Wf/2 Wf/2];
Yrange = [-L/2+Fi -Lg/2];
Zrange = [Ht+Hs Ht+Hs+Ht];
Cstbrick(mws, Name, component, material, Xrange, Yrange, Zrange)

%This adds the feedline to the patch
component1 = 'component1:Patch';
component2 = 'component1:FeedLine';
CstAdd(mws,component1,component2)

%Here I pick the substrate to assign the port, there is more than one way
%to assign a port in your geometry i.e you can use coordinates and not
%picks, I think coordinates are easier cause pics are generated according
%to your design. i.e id = 3; is how CST names the area I am selecting
%because there are at least 3 faces in my design but that is not standard,
%it depends on your design. Better use coordinates to be sure.
Name = 'Substrate';
id = 3;
CstPickFace(mws,Name,id)

%Here I am assigning a waveguide port (I think I have most of the possible CST ports as functions in my api)
PortNumber = 1;
Xrange = [-36 36];
Yrange = [-36 -36];
Zrange = [0.035 1.635];
XrangeAdd =[3*Wf 3*Wf];
YrangeAdd =[0 0];
ZrangeAdd =[Ht+Hs 4*Hs];
Coordinates = 'Picks';
Orientation = 'positive';
CstWaveguidePort(mws,PortNumber, Xrange, Yrange, Zrange, XrangeAdd, YrangeAdd, ZrangeAdd,Coordinates,Orientation)

%Here I am assigning monitors for the e-field, h-field and farfield at 2.45GHz
CstDefineEfieldMonitor(mws,strcat('e-field', '2.45'),2.45);
CstDefineHfieldMonitor(mws,strcat('h-field', '2.45'), 2.45);
CstDefineFarfieldMonitor(mws,strcat('Farfield','2.45'), 2.45);

%Saves the project
CstSaveProject(mws)

%Defines the solver and starts simulation (I also have frequency domain solver and Integral solver)
%-40 corresponds to accuracy
CstDefineTimedomainSolver(mws,-40)

%Here you need to define the path that you want your s parametters to be
%exported and the name of your file. Mine for instance are:
% exportpath = 'C:\Users\simos\Dropbox\cst api\microstrip';
% filenameTXT = 'microstrip';
exportpath = '...\microstrip';
filenameTXT = 'microstrip';

%Here the S11 is exported as a .txt file and plotted
CstExportSparametersTXT(mws, exportpath)
[Frequency, Sparametter] = CstLoadSparametterTXT(filenameTXT);
plot(Frequency,Sparametter,'-'); grid on;
legend('S11 (dB)')
title('patch antenna at 2.45GHz')
xlabel('Frequency (GHz)')

%In the API's folders you'll find many more functions that do all kinds of stuff in CST.
%As you've seen in this tutorial the name of each function prety much describes what it does
%Always remember first to call the function of your desired material before you assing it into a
%geometry
%Feel free to experiment with them! Have fun!

repo: CST-MATLAB-API


text:
function [backpanel, frontpanel] = read_ctf_trigger(dataset)

% READ_CTF_TRIGGER reads the STIM channel from a dataset and detects
% the trigger moments and values
%
% [backpanel, frontpanel] = read_ctf_trigger(dataset)
%
% This returns all samples of the STIM channel, converted to backpanel
% and frontpanel trigger values. Triggers are placed at the rising flank
% of the STIM channel.
%
% Triggers should be at least 9 samples long (for 1200Hz samplerate) and
% should not overlap each other.
%
% See also READ_CTF_MEG4, READ_CTF_RES4

% Copyright (C) 2003, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: read_ctf_trigger.m 945 2010-04-21 17:41:20Z roboos $

[path, file, ext] = fileparts(dataset);
datafile   = fullfile(dataset, [file '.meg4']);
headerfile = fullfile(dataset, [file '.res4']);

% read the header from the raw CTF data
hdr = read_ctf_res4(headerfile);

% number of samples to shift the assesment of the trigger value
% this is needed because it takes some time for the rising flank to get to the correct value
trigshift = fix(hdr.Fs * 9/1200);

% read the stimulus channel from raw CTF data: with the new electronics
% control console used at NIH, there is now no longer any channel
% named "STIM". Instead, there are a variety of channel names. The
% electronics used at FCDC still uses the "STIM" channel.
stimindx = find(strcmp(hdr.label, 'UPPT001'));
if isempty(stimindx)
  stimindx = find(strcmp(hdr.label, 'USPT001'));
end
if isempty(stimindx)
  stimindx = find(strcmp(hdr.label, 'UTRG001'));
end
if isempty(stimindx)
  stimindx = find(strcmp(hdr.label, 'STIM'));
end
stim =  read_ctf_meg4(datafile, hdr, 1, hdr.nTrials*hdr.nSamples, stimindx);

% correct for reading stimulus channel as signed integer, whereas it should be an unsigned int
stim(find(stim<0)) = stim(find(stim<0)) + 2^32;

% split backpanel and frontpanel data
bpstim = fix(stim / 2^16);
fpstim = double(bitand(uint32(stim), 2^16-1));

% determine the precise timing of the triggers
bpupflank = [0 (diff(bpstim)>0 & bpstim(1:(end-1))==0)];
backpanel = bpupflank(1:(end-trigshift)).*bpstim((1+trigshift):end);
fpupflank = [0 (diff(fpstim)>0 & fpstim(1:(end-1))==0)];
frontpanel = fpupflank(1:(end-trigshift)).*fpstim((1+trigshift):end);

% pad with zeros to ensure same length as data
backpanel(length(stim)) = 0;
frontpanel(length(stim)) = 0;

author: PatternRecognition

repo: OpenBMI


text:
function r = sec(a)
%SEC          Taylor secans  sec(a)
%
%Thanks to George Corliss for providing the Taylor expansion
%

% written  06/03/09     S.M. Rump
% modified 08/26/12     S.M. Rump  global variables removed
%

  e = 1e-30;
  if 1+e==1-e                   % fast check for rounding to nearest
    rndold = 0;
  else
    rndold = getround;
    setround(0)
  end

  K = getappdata(0,'INTLAB_TAYLOR_ORDER');

  ct = a.t;
  st = a.t;
  r = a;
  N = size(a.t,2);
  st(1,:) = sin(a.t(1,:));
  ct(1,:) = cos(a.t(1,:));
  r.t(1,:) = 1 ./ cos(a.t(1,:));
  ct1 = -ct(1,:);
  for j=2:K+1
    at_ = a.t(2:j,:);           % some 3 % faster
    if j~=K+1
      st(j,:) = sum( repmat((1:j-1)',1,N).*ct(j-1:-1:1,:).*at_ , 1 ) ./ (j-1);
    end
    ct(j,:) = - sum( repmat((1:j-1)',1,N).*st(j-1:-1:1,:).*at_ , 1 ) ./ (j-1);
    r.t(j,:) = sum( r.t(1:j-1,:).*ct(j:-1:2,:) , 1 ) ./ ct1;
  end

  if rndold
    setround(rndold)
  end

repo: OpenMAS


text:
function f = clearPointValues(f)
%   F = CLEARPOINTVALS(F) sets the .POINTVALS(j) to the average of the right and
%   left limits of its neighbouring funs for interior breaks and the limits from
%   the left and right for the POINTVALS(1) and VALS(end), respectively.
for k = 1:numel(f)
    f(k).pointValues = chebfun.getValuesAtBreakpoints(f(k).funs);
end

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function calendar_nyt_test03 ( )

%*****************************************************************************80
%
%% CALENDAR_NYT_TEST03 tests JED_TO_NYT.
%
%  Discussion:
%
%    The routine JED_TO_NYT has been checked against the somewhat
%    erratic printing history of the New York Times in the 19th century.
%    This function seems to be delivering the correct answer for the
%    dates we have checked.
%
%    The "inverse" function NYT_TO_JED has not been written to handle th
%    nightmare of the 19th century issue numbering, however.
%
%  Volume  Issue   D M         Y
%  ------  -----  -- --------- ----
%       1      1  18 September 1851
%       1     92   3 January   1852
%       2    404   3 January   1853
%       2    416  17 January   1853
%       3    856  15 June      1854
%
%       4   1210   4 August    1855
%       5   1259   1 October   1855
%       5   1491  28 June      1856
%       6   1706   9 March     1857
%       7   2155  17 August    1858
%
%       8   2421  23 June      1859
%       9   2586   4 January   1860
%      10   2897   3 January   1861
%      10   3000   1 May       1861
%      12   3432  23 September 1862
%
%      13   3794  20 November  1863
%      14   4130  19 December  1864
%      14   4230  16 April     1865
%      15   4576  26 May       1866
%      17   5034  13 November  1867
%
%      17   5250  22 July      1868
%      20   6189  22 July      1871
%      47  14499   5 February  1898
%      47  15000   7 February  1898
%      52  16579  24 February  1903
%
%      53  16909  15 March     1904
%      54  17292  29 May       1905
%      55  17561  22 February  1906
%      57  18164  18 October   1907
%      58  18856   9 September 1909
%
%      66  21619   3 April     1917
%      74  24651  22 July      1925
%      89  29827  23 September 1939
%      89  30000  14 March     1940
%      94  31881   8 May       1945
%
%      94  31980  15 August    1945
%     113  38864  20 June      1964
%     114  39317  16 September 1965
%     117  40076  15 October   1967
%     118  40721  21 July      1969
%
%     120  41418  18 June      1971
%     127  44027   9 August    1978
%     128  44028   6 November  1978
%     141  48939  17 April     1992
%     144  50000  14 March     1995
%
%     147  50939   8 October   1997
%     149  51753  31 December  1999
%     149  51254   1 January   2000
%     150  51599  11 December  2000
%     154  53108  28 January   2005
%
%     157  54136  22 November  2007
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%   19 January 2009
%
%  Author:
%
%    John Burkardt
%
  test_num = 51;
  issue_test = [ ...
        1,    92,   404,   416,   856, ...
     1210,  1259,  1491,  1706,  2155, ...
     2421,  2586,  2897,  3000,  3432, ...
     3794,  4130,  4230,  4576,  5034, ...
     5250,  6189, 14499, 15000, 16579, ...
    16909, 17292, 17561, 18164, 18856, ...
    21619, 24651, 29827, 30000, 31881, ...
    31980, 38864, 39317, 40076, 40721, ...
    41418, 44027, 44028, 48939, 50000, ...
    50939, 51753, 51254, 51599, 53108, ...
    54136 ];
  jed_test = [ ...
   2397383.50, 2397490.50, 2397856.50, 2397870.50, 2398384.50, ...
   2398799.50, 2398857.50, 2399128.50, 2399382.50, 2399908.50, ...
   2400218.50, 2400413.50, 2400778.50, 2400896.50, 2401406.50, ...
   2401829.50, 2402224.50, 2402342.50, 2402747.50, 2403283.50, ...
   2403535.50, 2404630.50, 2414325.50, 2414327.50, 2416169.50, ...
   2416554.50, 2416994.50, 2417263.50, 2417866.50, 2418558.50, ...
   2421321.50, 2424353.50, 2429529.50, 2429702.50, 2431583.50, ...
   2431682.50, 2438566.50, 2439019.50, 2439778.50, 2440423.50, ...
   2441120.50, 2443729.50, 2443818.50, 2448729.50, 2449790.50, ...
   2450729.50, 2451543.50, 2451544.50, 2451889.50, 2453398.50, ...
   2454426.50 ];
  volume_test = [ ...
       1,    1,    2,    2,    3, ...
       4,    5,    5,    6,    7, ...
       8,    9,   10,   10,   12, ...
      13,   14,   14,   15,   17, ...
      17,   20,   47,   47,   52, ...
      53,   54,   55,   57,   58, ...
      66,   74,   89,   89,   94, ...
      94,  113,  114,  117,  118, ...
     120,  127,  128,  141,  144, ...
     147,  149,  149,  150,  154, ...
     157 ];

  fprintf ( 1, '\n' );
  fprintf ( 1, 'CALENDAR_NYT_TEST03\n' );
  fprintf ( 1, '  For the New York Times issue date:\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  JED -> NYT1 by historical record.\n' );
  fprintf ( 1, '  JED -> NYT2 by "JED_TO_NYT"\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  JED         Date   =>      Volume    Issue (lookup)\n' );
  fprintf ( 1, '                     =>      Volume    Issue (compute)\n' );
  fprintf ( 1, '                             Error     Error\n' );
  fprintf ( 1, '\n' );

  for test = 1 : test_num

    jed = jed_test(test);

    [ y, m, d, f ] = jed_to_ymdf_common ( jed );
    s = ymdf_to_s_common ( y, m, d, f );

    issue1 = issue_test(test);
    volume1 = volume_test(test);

    [ volume2, issue2 ] = jed_to_nyt ( jed );

    fprintf ( 1, '\n' );
    fprintf ( 1, '  %11.2f  %25s  %8d  %8d\n', jed, s, volume1, issue1 );
    fprintf ( 1, '                                          %8d  %8d\n',         volume2, issue2 );
    fprintf ( 1, '                                          %8d  %8d\n',         volume2 - volume1, issue2 - issue1 );

  end

  return
end


%==============================================================================
% This code is part of the Matlab-based toolbox
% FAIR - Flexible Algorithms for Image Registration.
% For details see
% - https://github.com/C4IR and
% - http://www.siam.org/books/fa06/
%==============================================================================
%
% Tutorial for FAIR: 2D interpolation and visualization
%
% generic example for usage of interpolation and visualization
% loads data, initializes viewer and interpolator, shows some results
%
% - load data ('US.jpg')
% - display and visualize data  (viewImage2D)
% - view image in high resolution and low resolution
%==============================================================================

clear, close all, help(mfilename);

fprintf('%s\n','generic interpolation and visualization')

fprintf('%s\n','load data, setup image viewer')
dataT = double(imread('US.jpg'));
m     = size(dataT);
omega = [0,size(dataT,1),0,size(dataT,2)];

% setup image viewer
viewImage('reset','viewImage','viewImage2D','colormap',gray(256));

% shortcuts for labeling off plots
dimstr  = @(m) sprintf('%s=[%s]',inputname(1),sprintf(' %d',m));
lblstr  = @(str,m) sprintf('%s, %s',str,dimstr(m));

fprintf('%s\n','visualize original data')
FAIRfigure(1,'figname',mfilename); clf;
viewImage(dataT,omega,m);
title(lblstr('highres',m),'fontsize',20); set(gca,'fontsize',20); FAIRpause;

fprintf('%s\n','setup interpolator')
imgModel('reset','imgModel','splineInter','regularizer','moments','theta',1e-2);
T = getSplineCoefficients(dataT,'out',0);

fprintf('%s\n','generate some points and interpolate')
m  = [256,128]/4;
xc = getCellCenteredGrid(omega,m);
Tc = imgModel(T,omega,xc);

FAIRfigure(2,'figname',mfilename); clf;
viewImage(Tc,omega,m);
title(lblstr('lowres',m),'fontsize',20);  set(gca,'fontsize',20);

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


text:
function isoplot(xx,yy,zz,u)

% red
redvals = [1.5:0.2:2.1];
red=[0.5 0 0];
for i=1:length(redvals)
    pH = patch(isosurface(xx,yy,zz,u,redvals(i)));
    set(pH,'facecolor',red,'edgecolor','none','facealpha',0.95);
end

% yellow
yelvals= [1:0.25:1.25];
yellow=[0.8 0.8 0];
for i=1:length(yelvals)
    pH= patch(isosurface(xx,yy,zz,u,yelvals(i)));
    set(pH,'facecolor',yellow,'edgecolor','none','facealpha',0.3)
end

% blue
bluevals= [0.5:0.2:0.7];
blue = [0 0 0.5];
for i=1:length(bluevals)
    pH= patch(isosurface(xx,yy,zz,u,bluevals(i)));
    set(pH,'facecolor',blue,'edgecolor','none','facealpha',0.05);
end

% lighting
light('pos',[-100,50,100]);
light('pos',[50,-100,100]);
light('pos',[-100,-100,1]);
light('pos',[1,0,1]);
lighting phong
%set(gca,'view',[-109,9],'projection','orth')
% cameramenu on

author: Sable

repo: mcbench-benchmarks


text:
function Z = desvec(Zv,M)
% PURPOSE: Creates a matrix unstacking a vector
% ------------------------------------------------------------
% SYNTAX:  Z = desvec(Zv,M);
% ------------------------------------------------------------
% OUTPUT:  Z = matrix with M cols.
% ------------------------------------------------------------
% INPUT: Zv    : a vector nx1
%	     M	   : number of cols.
% ------------------------------------------------------------
% written by:
%  Enrique M. Quilis
%  Macroeconomic Research Department
%  Ministry of Economy and Competitiveness
%  <enrique.quilis@mineco.es>

% Version 1.1 [August 2006]

[n,m] = size(Zv);

if (m ~= 1)
   error (' *** NUMBER OF COLUMNS GREATER THAN ONE *** ')
end

N = round(n/M);

Z(:,1) = Zv(1:N,1);
j=2;
while (j <= M)
   Z = [ Z  Zv( (j-1)*N+1 : j*N , 1)];
   j=j+1;
end


text:
%% Exporting Vectors
%
%%
% Large lists of vectors can be imported from a text file by the command

fname = fullfile(mtexDataPath,'vector3d','vectors.txt');
v = vector3d.load(fname,'ColumnNames',{'polar angle','azimuth angle'})

%%
% and exported by the command

export(v,fname,'polar')

author: mtex-toolbox

repo: mtex

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


text:
function d=edit_distance_damerau(s,t)
  % EDIT_DISTANCE_DAMERAU calculates the Damerau-Levenshtein edit distance.
  %
  % This code is part of the work described in [1]. In [1], edit distances
  % are applied to match linguistic descriptions that occur when referring
  % to objects (in order to achieve joint attention in spoken human-robot /
  % human-human interaction).
  %
  % [1] B. Schauerte, G. A. Fink, "Focusing Computational Visual Attention
  %     in Multi-Modal Human-Robot Interaction," in Proc. ICMI,  2010.
  %
  % @author: B. Schauerte
  % @date:   2010
  % @url:    http://cvhci.anthropomatik.kit.edu/~bschauer/

  % Copyright 2010 B. Schauerte. All rights reserved.
  %
  % Redistribution and use in source and binary forms, with or without
  % modification, are permitted provided that the following conditions are
  % met:
  %
  %    1. Redistributions of source code must retain the above copyright
  %       notice, this list of conditions and the following disclaimer.
  %
  %    2. Redistributions in binary form must reproduce the above copyright
  %       notice, this list of conditions and the following disclaimer in
  %       the documentation and/or other materials provided with the
  %       distribution.
  %
  % THIS SOFTWARE IS PROVIDED BY B. SCHAUERTE ''AS IS'' AND ANY EXPRESS OR
  % IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  % WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  % DISCLAIMED. IN NO EVENT SHALL B. SCHAUERTE OR CONTRIBUTORS BE LIABLE
  % FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  % CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  % SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  % BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  % WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  % OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  % ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  %
  % The views and conclusions contained in the software and documentation
  % are those of the authors and should not be interpreted as representing
  % official policies, either expressed or implied, of B. Schauerte

  m=numel(s);
  n=numel(t);

  d=zeros(m+1,n+1);

  % initialize distance matrix
  for i=0:m % deletion
    d(i+1,1)=i;
  end
  for j=0:n % insertion
    d(1,j+1)=j;
  end

  for j=2:n+1
    for i=2:m+1
      if s(i-1) == t(j-1)
        cost = 0;
      else
        cost = 1;
      end

      d(i,j)=min([ ...
        d(i-1,j) + 1, ...     % deletion
        d(i,j-1) + 1, ...     % insertion
        d(i-1,j-1) + cost ... % substitution
        ]);

      if (i-1)>1 && (j-1)>1 && s((i-1))==t((j-1)-1) && s((i-1)-1) == t(j-1)
        d(i,j) = min([ ... % transposition
          d(i,j), ...
          d(i-2,j-2), ...
          ]);
      end
    end
  end

  d=d(m+1,n+1);


text:
% ________________________________________________________________________%
%
% Breathing Learning Task (BLT)
%
% Originally coded: May 2018 by F.H. Petzschner and O.K. Harrison
% Contact: O.K. Harrison (faull@biomed.ee.ethz.ch)
%
% ________________________________________________________________________%
% Info: This is the laboratory version of the BLT
% This task runs a cue-learning sequence that is coupled to a manually
% applied breathing stimulus.
% ________________________________________________________________________%

% Clear the workspace and the screen
sca;
close all;
clearvars;

% Check folder location is main BLT folder
[~,dir_name] = fileparts(pwd);
if ~strcmp(dir_name,'BLT')
   error('Not currently in main BLT folder. Please move to BLT folder and try again.');
end

% Add relevant paths
addpath('utils');
addpath('images');
addpath(fullfile('utils','helper'));
addpath('outputfiles');
KbName('UnifyKeyNames');

%% _______________________________________________________________________%
%
%
%                                  INIT
%
% ________________________________________________________________________%

% determine game mode
expMode          = input('Options (task,train_4,train_6,debug):','s');

% init experimental parameters
params           = tapas_BLT_initParams(expMode);

% init screen
params.screen    = tapas_BLT_initScreen(params);

% init visual stimuli
params.text      = tapas_BLT_initVisuals(params);

% init data file
tapas_BLT_initDatafile(params);

% init cogent & parallel ports if in MRI scanner
if params.doMRI == 1
    tapas_BLT_initCogent(params);
    tapas_BLT_initParallelPorts(params);
else
    load(params.path.datafile)
    data.events.start_protocol = GetSecs();
    save(params.path.datafile, 'data', 'params');
end

%% _______________________________________________________________________%
%
%
%                            INTRO & TRAINING
%
% ________________________________________________________________________%

if params.doIntroMain == 1
    tapas_BLT_runIntroMain(params);
end

if params.doIntroTrain == 1
    tapas_BLT_runIntroTrain(params);
end

%% _______________________________________________________________________%
%
%
%                                MAIN LOOP
%
% ________________________________________________________________________%

ticTime = tic(); % get the time
data.events.start_sequence = GetSecs();
save(params.path.datafile, 'data', 'params');

% run buffer ITI if required
tapas_BLT_runBuffer(params);

% RUN MAIN LOOP
nTrial = length(params.cue);

for iTrial = 1:nTrial

    % Print the trial number to the screen
    fprintf('TRIAL NUMBER = %d\n', iTrial);

    % run prediction
    if params.predMode == 1
        tapas_BLT_runPrediction(params, iTrial);
    elseif params.predMode == 2
        tapas_BLT_runPredictionScale(params, iTrial);
    end

    % Can run a pause here if required
    if params.pauseMode == 1
        tapas_BLT_runPause(params);
    end

    % run Stimulus
    tapas_BLT_runStimulus(params, iTrial);

    % run stimulus question
    if params.stimAnsMode == 1
        tapas_BLT_runStimAnswer(params);
    elseif params.stimAnsMode == 2
        tapas_BLT_runRating(params, 1);
    end

    % run ITI
    tapas_BLT_runITI(params, iTrial);

end

%% _______________________________________________________________________%
%
%
%                          FINAL ANXIETY RATING
%
% ________________________________________________________________________%

% run end (almost)
tapas_BLT_runEnd_almost(params);

% run Rating for intensity (= 1) if wasn't asked throughout task
if params.stimAnsMode == 1
    tapas_BLT_runRating(params, 1);
end

% run Rating for anxiety (= 2)
tapas_BLT_runRating(params, 2);

%% _______________________________________________________________________%
%
%
%                                FINISH
%
% ________________________________________________________________________%

% show end if needed
if params.doIntroMain == 1
    tapas_BLT_runEnd(params);
else
    Screen('CloseAll');
end

author: translationalneuromodeling

repo: tapas


text:
% Usage: strvec = vect2colon(vec, options)
%
% Converts a vector into a string using MATLAB colon notation (single resolution).
%
% Options are:
%
% 'Delimiter'   -   'on','yes','off','no' {default on}  :  Including square brackets []
%                                     (or curly brackets {} when output's dimensions are not consistent)
%                                            'auto' by default.
% 'Sort'        -   'on','yes','off','no' {default off} :  Sort elements in ascending order
%
% 'Precision'   -   'double','single' {default single}
%
% 'Repeat'      -   'on','yes','off','no' {default on}  :  Keep repeated elements
%
% MATLAB colon notation is a compact way to refer to ranges of matrix elements.
% It is often used in copy operations and in the creation of vectors and matrices.
% Colon notation can be used to create a vector as follows
%                           x = xbegin:dx:xend
%                                   or
%                          x2 = xbegin:xend
% where xbegin and xend are the range of values covered by elements of the x
% vector, and dx is the (optional) increment. If dx is omitted a value of 1
% (unit increment) is used. The numbers xbegin, dx, and xend need not be
% integers.
%
% Example 1:
% >> x = [  50 1000 1100 1200 2 3 4 5 6 10 20 30 40]
% >> vect2colon(x)
%
% ans =
%
% [ 50 1000:100:1200 2:6 10:10:40]
%
% or
%
% >> vect2colon(x, 'Sort', 'on')
%
% ans =
%
% [ 2:6 10:10:50 1000:100:1200]
%
% Example 2:
% >> x = [ 2 3 4 5 6 10 10.1 10.2 10.3 10.4 1000 1100 1200]
% >> s = vect2colon(x)
%
% s =
%
% [ 2:6 10:0.1:10.4 1000:100:1200 ]
%
% Example 3:
% >> x = [ 2 3 4 5 6 10 1000 1100 1200 10.1 10.2 10.3 10.4]
% >> s = vect2colon(x, 'Delimiter', 'no')
%
% s =
%
%  2:6 10 1000:100:1200 10.1:0.1:10.4
%
% See also:  mat2colon, eval, str2num
%
% Author: Javier Lopez-Calderon
% 2008-2011
%
% Feedback is appreciated.
% fixed bug where the increment is negative
% Checks numeric input
% Allows to keep repeated values

function strvec = vect2colon(vec, varargin)

p = inputParser;
p.FunctionName  = mfilename;
p.CaseSensitive = false;
p.addRequired('vec', @isnumeric);
p.addParamValue('Delimiter', 'auto', @ischar);
p.addParamValue('Sort', 'off', @ischar);
p.addParamValue('Precision', 'single');
p.addParamValue('Repeat', 'on', @ischar);
p.parse(vec, varargin{:});
strvec   = '';
if nargin<1
        help vect2colon
        return
end
if isempty(vec)
        if ismember_bc2({lower(p.Results.Delimiter)},{'yes','on','auto'})
                strvec = '[]';
        end
        return
end
[dime] = size(vec); % input size
if length(dime)>2
        error('Error: vect2colon only works for row or column vector. Use mat2colon instead.')
else
        if dime(1)>1 && dime(2)==1 % feb 2011
                apo = '''';
        elseif dime(1)==1 && dime(2)>=1
                apo = '';
        else
                error('Error: vect2colon only works for row or column vector. Use mat2colon instead.')
        end
end
if ismember_bc2({lower(p.Results.Sort)},{'yes','on'})
        if strcmpi(p.Results.Repeat,'off')
                vecuni = unique_bc2(vec);    % repeated numbers are not allowed. sorted
        else
                vecuni = sort(vec);           % repeated numbers are allowed. sorted  --> previous bug
        end
else
        if ismember_bc2({lower(p.Results.Repeat)}, {'off','no'})
                [v, a, b] = unique_bc2(vec', 'first');
                ia = sort(a);
                vecuni = vec(ia); % repeated numbers are not allowed. no sorted
        else
                vecuni = vec; % repeated numbers are allowed. no sorted  --> previous bug
        end
end
precision = p.Results.Precision;
if ischar(precision)
        precnum = str2num(precision);
        if isempty(precnum)
                if strcmpi(precision,'single')
                        dvec = single(diff(vecuni));
                else
                        dvec = double(diff(vecuni));
                end
        else
                dvec = (round(diff(vecuni)*10^precnum))/10^precnum;
        end

else
        dvec = (round(diff(vecuni)*10^precision))/10^precision;
end
% basepnts = find(diff(dvec));
holdc    = 0;
iexpress = 0;
k = 1;
while k <= numel(vecuni)
        if k>1 && k <= numel(vecuni) - 1
                if dvec(k) ~=0 && dvec(k) == dvec(k-1) && ~holdc
                        holdc = 1;
                        iexpress = iexpress + 1; % group counter
                        if dvec(k) ~= 1  % march 2011
                                if abs(abs(dvec(k))-pi)<1e-6
                                        if dvec(k)<0
                                                dvstr = '-pi';
                                        else
                                                dvstr = 'pi';
                                        end
                                else
                                        dvstr = sprintf('%g', dvec(k));
                                end
                                %strvec = [ strvec ':' dvstr ':' ];     % starts a group with step>1
                                strvec = sprintf('%s:%s:',strvec, dvstr); %   [ strvec ':' dvstr ':' ];
                        else
                                %strvec = [ strvec ':' ];               % starts a group with step=1
                                strvec = sprintf('%s:',strvec);
                        end
                elseif (dvec(k) ~= dvec(k-1) || (dvec(k)==0 && dvec(k) == dvec(k-1))) && ~holdc
                        strvec = sprintf('%s %g', strvec, vecuni(k));
                        %strvec   = [ strvec ' ' num2str(vecuni(k)) ];   % discret element
                        iexpress = iexpress + 1;
                elseif dvec(k) ~= dvec(k-1) && holdc
                        strvec = sprintf('%s%g', strvec, vecuni(k));
                        %strvec = [ strvec num2str(vecuni(k)) ];       % ends a group with step=1
                        iexpress = iexpress + 1;
                        holdc    = 0;
                        dvec(k)  = 0; % since repeated numbers are not allowed...
                end
        else
                if holdc
                        %strvec = [ strvec num2str(vecuni(k)) ];      % last element
                        strvec = sprintf('%s%g', strvec, vecuni(k));
                else
                        strvec = sprintf('%s %g', strvec, vecuni(k));
                        %strvec = [ strvec ' ' num2str(vecuni(k)) ];  % first(last) element (discrete)
                        iexpress = iexpress + 1;
                end
        end
        k = k + 1;
end
% strvec = strtrim(strvec);
if ismember_bc2({lower(p.Results.Delimiter)},{'yes','on'})
        %strvec = [ '[' strvec ']' apo];
        strvec = sprintf('[%s]%s',strvec,apo);
        return
end
if ((iexpress-1)>1 || ((iexpress-1)==1 && numel(vecuni)==2))...
                && (strcmp(p.Results.Delimiter,'auto'))
        %strvec = [ '[' strvec ']' apo];
        strvec = sprintf('[%s]%s',strvec,apo);
end
return

author: ucdavis

repo: erplab

save_path: github-repos/MATLAB/ucdavis-erplab


text:
function results = vl_test_gmm(varargin)
% VL_TEST_GMM

% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

vl_test_init ;

end

function s = setup()
  randn('state',0) ;
  s.X = randn(128, 1000) ;
end

function test_multithreading(s)
  dataTypes = {'single','double'} ;

  for dataType = dataTypes
    conversion = str2func(char(dataType)) ;
    X = conversion(s.X) ;
    vl_twister('state',0) ;
    vl_threads(0) ;
    [means, covariances, priors, ll, posteriors] = ...
        vl_gmm(X, 10, ...
               'NumRepetitions', 1, ...
               'MaxNumIterations', 10, ...
               'Initialization', 'rand') ;
    vl_twister('state',0) ;
    vl_threads(1) ;
    [means_, covariances_, priors_, ll_, posteriors_] = ...
        vl_gmm(X, 10, ...
               'NumRepetitions', 1, ...
               'MaxNumIterations', 10, ...
               'Initialization', 'rand') ;

    vl_assert_almost_equal(means, means_, 1e-2) ;
    vl_assert_almost_equal(covariances, covariances_, 1e-2) ;
    vl_assert_almost_equal(priors, priors_, 1e-2) ;
    vl_assert_almost_equal(ll, ll_, 1e-2 * abs(ll)) ;
    vl_assert_almost_equal(posteriors, posteriors_, 1e-2) ;
  end
end

author: jianxiongxiao

repo: ProfXkit


text:
% GeoPDEs: An Octave/Matlab research tool for IsoGeometric Analysis of PDEs
%  Version 3.2.0  17-Dec-2019
%
% To run the first examples, use the following scripts
%   geopdes_base_examples
%   geopdes_elasticity_examples
%   geopdes_fluid_examples
%   geopdes_maxwell_examples
%
% The package contains the following functions. A detailed help for each function is available typing "help <function_name>"
%
% Solve: solvers for some simple problems, that you can modify to solve your own problem
%   solve_laplace
%   solve_laplace_iso
%   solve_laplace_eig
%   solve_laplace_collocation
%   solve_bilaplace_2d_iso
%   solve_bilaplace_gradgrad_2d_iso
%   solve_adv_diff_2d
%   solve_linear_elasticity
%   solve_maxwell_eig
%   solve_maxwell_eig_mixed1
%   solve_maxwell_eig_mixed2_2d
%   solve_maxwell_src
%   solve_navier_stokes
%   solve_stokes
%   solve_kirchhoff_love_shell
%
% Geometry: read geometry files, that can be created with the NURBS package
%   geo_nurbs
%   geo_load
%   geo_read_nurbs
%   geo_convert_format
%   geo_deform
%
% Mesh: functions to generate and compute quadrature points in the NURBS geometry
%   msh_gauss_nodes
%   msh_set_quad_nodes
%   msh_set_breaks
%   msh_cartesian
%   msh_restrict_to_cells
%   @msh_cartesian/msh_eval_boundary_side
%   @msh_cartesian/msh_evaluate_col
%   @msh_cartesian/msh_evaluate_element_list
%   @msh_cartesian/msh_precompute
%   @msh_cartesian/msh_boundary_side_from_interior
%
% Space: functions to generate and compute discrete spline and NURBS spaces
%   sp_bspline
%   sp_nurbs
%   sp_h2_error
%   sp_h1_error
%   sp_l2_error
%   sp_hcurl_error
%   sp_eval_msh
%   sp_to_vtk_b64
%   sp_to_vtk_raw
%   sp_bspline_fluid
%   sp_bspline_1d_param
%   sp_grad_preserving_transform
%   sp_integral_preserving_transform
%   sp_vector_grad_preserving_transform
%   sp_vector_curl_preserving_transform
%   sp_vector_div_preserving_transform
%   sp_scalar
%   @sp_scalar/sp_eval_boundary_side
%   @sp_scalar/sp_evaluate_col
%   @sp_scalar/sp_evaluate_col_param
%   @sp_scalar/sp_evaluate_element_list
%   @sp_scalar/sp_evaluate_element_list_param
%   @sp_scalar/sp_h2_error
%   @sp_scalar/sp_h1_error
%   @sp_scalar/sp_l2_error
%   @sp_scalar/sp_precompute
%   @sp_scalar/sp_precompute_param
%   @sp_scalar/sp_eval
%   @sp_scalar/sp_to_vtk
%   @sp_scalar/sp_drchlt_l2_proj
%   @sp_scalar/sp_weak_drchlt_bc_laplace
%   @sp_scalar/sp_get_basis_functions
%   @sp_scalar/sp_get_cells
%   @sp_scalar/sp_get_neighbors
%   sp_vector
%   @sp_vector/sp_eval_boundary_side
%   @sp_vector/sp_eval
%   @sp_vector/sp_evaluate_col
%   @sp_vector/sp_evaluate_col_param
%   @sp_vector/sp_evaluate_element_list
%   @sp_vector/sp_evaluate_element_list_param
%   @sp_vector/sp_h2_error
%   @sp_vector/sp_h1_error
%   @sp_vector/sp_l2_error
%   @sp_vector/sp_hcurl_error
%   @sp_vector/sp_precompute
%   @sp_vector/sp_precompute_param
%   @sp_vector/sp_to_vtk
%   @sp_vector/sp_drchlt_l2_proj
%   @sp_vector/sp_weak_drchlt_bc_stokes
%   @sp_vector/sp_get_basis_functions
%   @sp_vector/sp_get_cells
%   @sp_vector/sp_get_neighbors
%
% Operators: functions to assemble different matrices and vectors
%   op_f_v
%   op_u_v
%   op_gradu_gradv
%   op_laplaceu_laplacev
%   op_vel_dot_gradu_v
%   op_mat_stab_SUPG
%   op_rhs_stab_SUPG
%   op_curlu_curlv_2d
%   op_curlu_curlv_3d
%   op_curlv_p
%   op_div_v_q
%   op_divu_divv
%   op_eu_ev
%   op_fdotn_vdotn
%   op_fdotn_v
%   op_f_vxn_2d
%   op_f_vxn_3d
%   op_uxn_vxn_2d
%   op_uxn_vxn_3d
%   op_gradgradu_gradgradv
%   op_gradu_v_otimes_n
%   op_gradv_n_f
%   op_gradv_n_u
%   op_gradu_n_gradv_n
%   op_pn_v
%   op_su_ev
%   op_udotn_vdotn
%   op_ugradu_v
%   op_ugradu_jac_v
%   op_u_otimes_n_v_otimes_n
%   op_v_gradp
%   op_KL_shells
%   op_KL_bending_stress
%   op_KL_membrane_stress
%
% Multipatch: functions of different kinds to solve problems in domains defined by multiple NURBS patches
%   mp_geo_load
%   mp_geo_read_nurbs
%   mp_interface
%   mp_interface_vector
%   mp_interface_hcurl
%   mp_interface_hdiv
%   mp_solve_laplace
%   mp_solve_linear_elasticity
%   mp_solve_maxwell_eig
%   mp_solve_maxwell_eig_mixed1
%   mp_solve_stokes
%   mp_solve_stokes_div_conforming
%   msh_multipatch
%   @msh_multipatch/msh_evaluate_element_list
%   sp_multipatch
%   @sp_multipatch/sp_l2_error
%   @sp_multipatch/sp_h1_error
%   @sp_multipatch/sp_hcurl_error
%   @sp_multipatch/sp_to_vtk
%   @sp_multipatch/sp_evaluate_element_list
%   @sp_multipatch/sp_get_cells
%   @sp_multipatch/sp_get_basis_functions
%   @sp_multipatch/sp_get_neighbors
%   @sp_multipatch/sp_drchlt_l2_proj
%   @sp_multipatch/sp_drchlt_l2_proj_udotn
%   @sp_multipatch/sp_weak_drchlt_bc_laplace
%   @sp_multipatch/sp_weak_drchlt_bc_stokes
%
% Utilities: other functions in the package
%   collocation_csp
%   knt_derham
%   msh_to_vtk
%   newtons_method
%

author: rafavzqz

repo: geopdes

save_path: github-repos/MATLAB/rafavzqz-geopdes


text:
function treepack_test17 ( )

%*****************************************************************************80
%
%% TREEPACK_TEST17 tests TREE_ROOTED_ENUM.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 June 2013
%
%  Author:
%
%    John Burkardt
%
  nnode = 10;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TREEPACK_TEST17\n' );
  fprintf ( 1, '  TREE_ROOTED_ENUM counts unlabeled rooted trees.\n' );

  ntree = tree_rooted_enum ( nnode );

  i4vec_print ( nnode, ntree, ...
    '  Number of trees with given number of nodes:' );

  return
end


text:
function r = addToMap(L, P_LL, P_LX, r)

% ADDTOMAP  Add Gaussian to Map.
%   ADDTOMAP(L,P_LL) adds the Gaussian N(L,P_LL) to the global EKF-map Map,
%   at positions that are empty, and returns the range of positions where
%   it has been added. ADDTOMAP adds mean L in Map.x and covariances P_LL
%   in the block-diagonal of Map.P.
%
%   For example, in the case of a map which has all used states contiguous,
%   the new state and covariance are appended at the end of the existing
%   one:
%
%           | x |        | P     0   |
%       x = |   |    P = |           |
%           | L |        | 0    P_LL |
%
%
%   Map is a global structure, containing:
%       .used   a vector of logicals indicating used positions
%       .x      the state vector
%       .P      the covariances matrix
%       .size   the Map's maximum size, numel(Map.x)
%
%   ADDTOMAP(L,P_LL,P_LX) accepts the cross variance matrix between L and the
%   currently used states in Map.x, so that the covariance is augmented
%   with
%
%           |   P     P_LX' |
%       P = |               |
%           | P_LX    P_LL  |
%
%   ADDTOMAP(L,P_LL,P_LX,R) or ADDTOMAP(L,P_LL,[],R) permits forcing the
%   range R as input.
%
%   See also NEWRANGE, USEDRANGE.
%
%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.

global Map

% parse inputs
if nargin == 2
    P_LX = [] ;
end
if nargin <= 3
    r = newRange(numel(L));
end

% add to map
Map.x(r)    = L;

Map.P(r,r)  = P_LL;
if(size(P_LX)~=0)
    mr = usedRange();
    Map.P(r,mr) =  P_LX ;
    Map.P(mr,r) =  P_LX' ;
    Map.used(r) = true;
end

% ========== End of function - Start GPL license ==========

%   # START GPL LICENSE

%---------------------------------------------------------------------
%
%   This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
%   SLAMTB 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.
%
%   SLAMTB 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 SLAMTB.  If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------

%   SLAMTB is Copyright:
%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
%   Copyright (c) 2010-2013, Joan Sola,
%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
%   SLAMTB is Copyright 2009
%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
%   @ LAAS-CNRS.
%   See on top of this file for its particular copyright.

%   # END GPL LICENSE

author: joansola

repo: slamtb

save_path: github-repos/MATLAB/joansola-slamtb


text:
function result  = omp_ar(Dict, X, K, epsilon, options)
    if(isobject(Dict))
        Dict = double(Dict);
    end
    if ~isa(Dict, 'double')
        error('Dict must be a double matrix');
    end
    if nargin < 4
        epsilon = 1e-3;
    end
    if nargin < 5
        options = struct;
    end
    if ~isfield(options, 'threshold_factor')
        options.threshold_factor = 2;
    end
    if ~isfield(options, 'reset_cycle')
        options.reset_cycle = 5;
    end
    if ~isfield(options, 'verbose')
        options.verbose = 0;
    end
    if ~isfield(options, 'sparse_output')
        options.sparse_output = 1;
    end

    [M, S] = size(X);
    N = size(Dict, 2);

    result = mex_omp_ar(Dict, X, K, epsilon, ...
        options.threshold_factor, ...
        options.reset_cycle, ...
        options.sparse_output, ...
        options.verbose);
end

author: indigits

repo: sparse-plex


text:
% run_simMegaSpecialShaped.m
% Jamie Near, McGill University 2014.
%
% USAGE:
% This script is run simply by editing the input parameters and then
% clicking "Run".
%
% DESCRIPTION:
% This script simulates a MEGA-SPECIAL experiment with fully shaped editing
% and refocusing pulses.  Phase cycling of both the editing and refocusing
% pulses is performed.  Furthermore, simulations are run at various
% locations in space to account for the within-voxel spatial variation of
% the GABA signal.  Summation across phase cycles and spatial positions is
% performed.  As a result of the phase cycling and spatially resolved simulations,
% this code takes a long time to run.  Therefore, the MATLAB parallel computing
% toolbox (parfor loop) was used to accelerate the siumulations.  Accelration
% is performed in the direction of the slice selective pulse (along
% the x-direction).  Up to a factor of 12 acceleration can be achieved using
% this approach.  To enable the use of the MATLAB parallel computing toolbox,
% initialize the multiple worked nodes using "matlabpool size X" where "X"
% is the number of available processing nodes.  If the parallel processing
% toolbox is not available, then replace the "parfor" loop with a "for" loop.
%
% INPUTS:
% To run this script, edit the parameters below as desired and then click
% "run":
% refocWaveform     = name of refocusing pulse waveform.
% editWaveform      = name of editing pulse waveform.
% editOnFreq        = freqeucny of edit on pulse[ppm]
% editOffFreq       = frequency of edit off pulse[ppm]
% refTp             = duration of refocusing pulses[ms]
% editTp            = duration of editing pulses[ms]
% Bfield            = Magnetic field strength in [T]
% Npts              = number of spectral points
% sw                = spectral width [Hz]
% Bfield            = magnetic field strength [Tesla]
% lw                = linewidth of the output spectrum [Hz]
% thkX              = slice thickness of x refocusing pulse [cm]
% x                 = vector of X positions to simulate [cm]
% taus              = vector of pulse sequence timings  [ms]
% spinSys           = spin system to simulate
% editPhCyc1        = vector of phase cycling steps for 1st editing pulse [degrees]
% editPhCyc2        = vector of phase cycling steps for 2nd editing pulse [degrees]
% refPhCyc          = vector of phase cycling steps for 1st refocusing pulse [degrees]
%
% OUTPUTS:
% outON_posx        = Simulated MEGA-SPECIAL edit-ON spectrum, spatially resolved.
% outOFF_posx       = Simulated MEGA-SPECIAL edit-OFF spectrum, spatially resolved.
% outDIFF_posx      = Simulated MEGA-SPECIAL difference spectrum, spatially resolved.
% outON             = Simulated MEGA-SPECIAL edit-ON spectrum, summed over
%                     all positions.
% outOFF            = Simulated MEGA-SPECIAL edit-OFF spectrum, summed over
%                     all positions.
% outDIFF           = Simulated MEGA-SPECIAL difference spectrum, summed over
%                     all positions.

% ************INPUT PARAMETERS**********************************
refocWaveform='sampleRefocPulse.pta'; %name of refocusing pulse waveform.
editWaveform='sampleEditPulse.pta'; %name of editing pulse waveform.
editOnFreq=1.88; %freqeucny of edit on pulse[ppm]
editOffFreq=7.5; %frequency of edit off pulse[ppm]
refTp=5; %duration of refocusing pulses[ms]
editTp=14; %duration of editing pulses[ms]
Npts=2048; %number of spectral points
sw=2000; %spectral width [Hz]
Bfield=3; %magnetic field strength [T]
lw=2; %linewidth of the output spectrum [Hz]
thkX=3; %slice thickness of x refocusing pulse [cm]
x=linspace(-2.2,2.2,12); %X positions to simulate [cm]
taus=[17,...    %Time from excitation pulse to 1st editing pulse [ms]
    17,...      %Time from 1st editing pulse to refoc pulse [ms]
    17,...      %Time from refoc pulse to 2nd editing pulse [ms]
    17];...     %Time from 2nd editing pulse to ADC onset [ms]
spinSys='GABA'; %spin system to simulate
centreFreq=3.0; %Centre frequency of the MR spectrum [ppm]
editPhCyc1=[0 90]; %phase cycling steps for 1st editing pulse [degrees]
editPhCyc2=[0 90 180 270]; %phase cycling steps for 2nd editing pulse [degrees]
refPhCyc=[0,90]; %phase cycling steps for 1st refocusing pulse [degrees]
% ************END OF INPUT PARAMETERS**********************************

%Load RF waveforms
refRF=io_loadRFwaveform(refocWaveform,'ref',0);
editRF=io_loadRFwaveform(editWaveform,'inv',0);

gamma=42577000; %gyromagnetic ratio

%Load spin systems
load spinSystems
sys=eval(['sys' spinSys]);

%Resample refocusing RF pulse from 400 pts to 100 pts to reduce
%computational workload
refRF=rf_resample(refRF,100);

%This is the step where the editing pulse waveform (initially a pulse with
%zero-frequency) is frequency shifted to produce and edit-on and an
%edit-off pulse;
editRFon=rf_freqshift(editRF,editTp,(centreFreq-editOnFreq)*Bfield*gamma/1e6);
editRFoff=rf_freqshift(editRF,editTp,(centreFreq-editOffFreq)*Bfield*gamma/1e6);

Gx=(refRF.tbw/(refTp/1000))/(gamma*thkX/10000); %[G/cm]

%n=1;
%totalIters=length(x)*length(y)*length(editPhCyc1)*length(editPhCyc2)*length(refPhCyc1)*length(refPhCyc2);

%Initialize structures:
outON_posx_epc_rpc=cell(length(x),length(editPhCyc1),length(editPhCyc2),length(refPhCyc));
outOFF_posx_epc_rpc=cell(length(x),length(editPhCyc1),length(editPhCyc2),length(refPhCyc));
outON_posx_epc=cell(length(x),length(editPhCyc1),length(editPhCyc2));
outOFF_posx_epc=cell(length(x),length(editPhCyc1),length(editPhCyc2));
outON_posx=cell(length(x),1);
outOFF_posx=cell(length(x),1);
outDIFF_posx=cell(length(x),1);
outON=struct([]);
outOFF=struct([]);

%loop through space: Don't forget to initialize the parallel processing
%toolbox workers using 'matlabpool open N' (for N workers, 12 max).

%for X=1:length(x);
parfor X=1:length(x);
    for EP1=1:length(editPhCyc1)
        for EP2=1:length(editPhCyc2)
            for RP=1:length(refPhCyc)
                disp(['Executing X-position ' num2str(X) ' of ' num2str(length(x)) ', '...
                    'First Edit phase cycle ' num2str(EP1) ' of ' num2str(length(editPhCyc1)) ', '...
                    'Second Edit phase cycle ' num2str(EP2) ' of ' num2str(length(editPhCyc2)) ', '...
                    'Refoc phase cycle ' num2str(RP) ' of ' num2str(length(refPhCyc)) '!!!']);
                outON_posx_epc_rpc{X}{EP1}{EP2}{RP}=sim_megaspecial_shaped(Npts,sw,Bfield,lw,taus,sys,...
                    editRFon,editTp,editPhCyc1(EP1),editPhCyc2(EP2),...
                    refRF,refTp,Gx,x(X),refPhCyc(RP));
                outOFF_posx_epc_rpc{X}{EP1}{EP2}{RP}=sim_megaspecial_shaped(Npts,sw,Bfield,lw,taus,sys,...
                    editRFoff,editTp,editPhCyc1(EP1),editPhCyc2(EP2),...
                    refRF,refTp,Gx,x(X),refPhCyc(RP));
                if RP==1
                    outON_posx_epc{X}{EP1}{EP2}=outON_posx_epc_rpc{X}{EP1}{EP2}{RP};
                    outOFF_posx_epc{X}{EP1}{EP2}=outOFF_posx_epc_rpc{X}{EP1}{EP2}{RP};
                else
                    outON_posx_epc{X}{EP1}{EP2}=op_subtractScans(outON_posx_epc{X}{EP1}{EP2},outON_posx_epc_rpc{X}{EP1}{EP2}{RP});
                    outOFF_posx_epc{X}{EP1}{EP2}=op_subtractScans(outOFF_posx_epc{X}{EP1}{EP2},outOFF_posx_epc_rpc{X}{EP1}{EP2}{RP});
                end
            end %end of refocusing phase cycle loop.
            if EP1==1 && EP2==1
                outON_posx{X}=outON_posx_epc{X}{EP1}{EP2};
                outOFF_posx{X}=outOFF_posx_epc{X}{EP1}{EP2};
            else
                outON_posx{X}=op_addScans(outON_posx{X},outON_posx_epc{X}{EP1}{EP2});
                outOFF_posx{X}=op_addScans(outOFF_posx{X},outOFF_posx_epc{X}{EP1}{EP2});
            end
            outDIFF_posx{X}=op_subtractScans(outON_posx{X},outOFF_posx{X});
        end %end of 1st editing phase cycle loop.
    end %end of 2nd editing phase cycle loop.
    outON=op_addScans(outON,outON_posx{X});
    outOFF=op_addScans(outOFF,outOFF_posx{X});
end %end of spatial loop (parfor) in x direction.

outDIFF=op_subtractScans(outON,outOFF);

figure
hold
for n=1:length(x)
plot(outON_posx{n}{1}.ppm,outON_posx{n}{1}.specs+5*n);
plot(outOFF_posx{n}{1}.ppm,outOFF_posx{n}{1}.specs+5*n);
end

author: CIC-methods

repo: FID-A

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


text:
function halton_step_set ( step )

%*****************************************************************************80
%
%% HALTON_STEP_SET sets the step of the leaped Halton subsequence.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 January 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer STEP, the step of the leaped Halton subsequence.
%
  global halton_BASE
  global halton_LEAP
  global halton_DIM_NUM
  global halton_SEED
  global halton_STEP

  step = floor ( step );

  if ( ~halham_step_check ( step ) )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'HALTON_STEP_SET - Fatal error!\n' );
    error ( 'HALTON_STEP_SET - Fatal error!' );
  end

  halton_STEP = step;

  return
end


text:
%  Uses the network `net` to extract image representations from a list
%  of image filenames `imageFns`.
%  `imageFns` is a cell array containing image file names relative
%  to the `imPath` (i.e. `[imPath, imageFns{i}]` is a valid JPEG image).
%  The representations are saved to `outFn` (single 4-byte floats).
%
%  Additional options:
%
%  `useGPU': Use the GPU or not
%
%  `batchSize': The number of images to process in a batch. Note that if your
%       input images are not all of same size (they are in place recognition
%       datasets), you should set `batchSize` to 1.

function cnnfeat = at_serialAllFeats_convfeat(net, imPath, imageFns, varargin)

opts= struct(...
  'useGPU', true, ...
  'numThreads', 12, ...
  'batchSize', 1 ...
  );
opts= vl_argparse(opts, varargin);
simpleNnOpts= {'conserveMemory', false, 'mode', 'test'};

relja_display('cnn desciption: Start'); %tic

if opts.useGPU
  net= relja_simplenn_move(net, 'gpu');
else
  net= relja_simplenn_move(net, 'cpu');
end

thisImageFns= fullfile( imPath, imageFns );

ims = single(imread(thisImageFns));

% fix non-colour images
if size(ims,3)==1
  ims= cat(3,ims,ims,ims);
end

ims(:,:,1)= ims(:,:,1) - net.meta.normalization.averageImage(1,1,1);
ims(:,:,2)= ims(:,:,2) - net.meta.normalization.averageImage(1,1,2);
ims(:,:,3)= ims(:,:,3) - net.meta.normalization.averageImage(1,1,3);

ims = at_imageresize(ims);

if opts.useGPU
  ims= gpuArray(ims);
end

% isz = size(ims(:,:,1));
% if (1920*1440) < prod(isz)
%   ims = imresize(ims,sqrt((1920*1440)/prod(isz)));
% end

% ---------- extract features
res = vl_simplenn(net, ims, [], [], simpleNnOpts{:});
clear ims;

cnnfeat = cell(1,5);
cnnfeat{5}.x = gather(res(31).x);
cnnfeat{4}.x = gather(res(25).x);
cnnfeat{3}.x = gather(res(18).x);
cnnfeat{2}.x = gather(res(11).x);
cnnfeat{1}.x = gather(res(6).x);
clear res

relja_display('cnn desciption: End');
% fprintf(1,'%f\n',toc);

end

author: HajimeTaira


text:
function deg = rad2deg(rad)

% rad2deg (rad)
%
% Keith Brady 18-08-2010
%
% Conversion function from Radians to Degrees.
% an alterative form to the functions by Richard Medlock renamed as
% suggested in the blog article
%
% http://blogs.mathworks.com/pick/2009/11/27/degrees-and-radians/

deg = rad./(pi/180);


text:
function test_suite=test_test_outcome
    try % assignment of 'localfunctions' is necessary in Matlab >= 2016
        test_functions=localfunctions();
    catch % no problem; early Matlab versions can use initTestSuite fine
    end
    initTestSuite;

function test_test_outcome_abstract_class
    test_=rand(3);
    duration=rand(1);
    outcome=MOxUnitTestOutcome(test_,duration);

    assertEqual(test_,getTest(outcome));
    assertEqual(duration,getDuration(outcome));

    if moxunit_util_platform_is_octave
        undef_err_id='Octave:undefined-function';
    else
        undef_err_id='MATLAB:UndefinedFunction';
    end

    assertExceptionThrown(@()getSummaryStr(outcome,'text'),undef_err_id);
    assertExceptionThrown(@()getSummaryStr(outcome,'xml'),undef_err_id);
    assertExceptionThrown(@()getProgressStr(outcome,'text'),undef_err_id);

function test_test_passed_outcome
    helper_test_outcome(@MOxUnitPassedTestOutcome,{},...
                            [],'',...
                            true,true,...
                            {'','.','passed'});

function test_test_skipped_outcome
    reason=rand_str();

    helper_test_outcome(@MOxUnitSkippedTestOutcome,{reason},...
                            reason,['skipped: ' reason],...
                            false,true,...
                            {'','s','skipped'});

function test_test_error_outcome
    [error_,msg]=rand_error_struct_and_msg();

    helper_test_outcome(@MOxUnitErroredTestOutcome,{error_},...
                            error_,['error: ' msg],...
                            false,false,...
                            {'','E','error'});

function test_test_failure_outcome
    [error_,msg]=rand_error_struct_and_msg();

    helper_test_outcome(@MOxUnitFailedTestOutcome,{error_},...
                            error_,['failure: ' msg],...
                            false,false,...
                            {'','F','failure'});

function [error_,msg_text, msg_xml_cell]=rand_error_struct_and_msg()
    error_=struct();
    error_.message=rand_str();
    error_.identifier=rand_str();

    stack=struct();
    stack.name=rand_str();
    stack.line=round(rand()*10);
    stack.file=rand_str();
    error_.stack=stack;

    msg_text=sprintf('%s\n  %s:%d (%s)',...
                        error_.message,...
                        stack.name, stack.line, stack.file);

function helper_test_outcome(class_,args,...
                                content,summary_text,...
                                is_success,is_non_failure,...
                                outcome_cell)

    name=rand_str();
    test_=MOxUnitFunctionHandleTestCase(name,rand_str,@abs);
    duration=rand(1);
    c=class_(test_,duration,args{:});
    assertEqual(getSummaryContent(c),content);
    assertEqual(getSummaryStr(c,'text'),summary_text);

    str_xml=getSummaryStr(c,'xml');
    xml_sub_str=sprintf('name="%s"',name);
    assert_contains(str_xml, xml_sub_str);
    if ~is_non_failure
        % must have failed
        xml_sub_str=sprintf('<%s message=',outcome_cell{3});
        assert_contains(str_xml,xml_sub_str);
    elseif ~is_success
        xml_sub_str=sprintf('<%s',outcome_cell{3});
        assert_contains(str_xml,xml_sub_str);
    end

    assertEqual(isSuccess(c),is_success);
    assertEqual(isNonFailure(c),is_non_failure);

    for verbosity=1:3
        assertEqual(getOutcomeStr(c,verbosity-1),outcome_cell{verbosity});
    end

function s=rand_str()
    s=char(20*rand(1,10)+65);

function assert_contains(a,b)
    assert(~isempty(strfind(a,b)))

author: qMRLab

repo: qMRLab

save_path: github-repos/MATLAB/qMRLab-qMRLab


text:
function A = psfMatrix(varargin)
%
%  CONSTRUCTOR FOR psfMatrix OBJECT
%
%  This new version uses Kronecker products, and should correct a bug
%  in the old version, which gave incorrect results for A'*x with
%  a non-symmetric PSF and refexive boundary conditions.
%
%  The psfMatrix class is based on a structure with six fields:
%    psf      - psf object
%    matdata  - matrix data needed to do matrix vector multiplications
%    transp_matdata - needed for multiplying by transpose.
%    type     - character string indicating:
%                 'invariant', 'variant', 'separable'
%    boundary - character string array indicating type of boundary conditions
%               to be used.  Choices are:
%                 'zero', 'periodic', 'reflexive' (or 'neumann')
%               The default is reflexive.
%    transpose- indicates if the matrix has been transposed.
%    imsize   - indicates the size of the image.  This might be
%               needed for some space variant problems.
%
%  Calling Syntax:
%       A = psfMatrix             (returns object with empty fields)
%       A = psfMatrix(psfMatrixObj)
%       A = psfMatrix(PSF, boundary, center, imsize)
%
%    where
%       * psfMatrixObj is an already existing psfMatrix object
%       * psfObj       is a psf object (see help psf for more information)
%       * PSF          can be either a double array containing one PSF
%                      image, or a cell array containing one or more
%                      PSF images
%       * boundary     is a character string indicating desired boundary
%                      condition. (see above)
%       * center       is either a double array or a cell array containing
%                      the (i,j) locations of the point sources of the
%                      PSF images
%       * imsize       size of reconstructed image in deblurring problem
%                      While it is not necessary to give this value, it
%                      can improve speed of iterative methods because it
%                      allows pre-computation of certain terms
%

%  J. Nagy & K. Lee  1/12/02
%  11/20/06 -- made reflexive default BC
%  7/5/16 fixed reflexive boundary conditions transpose mult
%

switch nargin

case 0
  A.psf = psf;
  A.matdata = [];
  A.transp_matdata = [];
  A.type = '';
  A.boundary = '';
  A.transpose = 0;
  A.imsize = [];
  A = class(A, 'psfMatrix');
  return

case 1
  if ( isa( varargin{1}, 'psfMatrix' ) )
    A = varargin{1};
    return
  end
  PSF = varargin{1};
  boundary = [];
  center = [];
  imsize = [];
case 2
  PSF = varargin{1};
  boundary = varargin{2};
  center = [];
  imsize = [];
case 3
  PSF = varargin{1};
  boundary = varargin{2};
  center = varargin{3};
  imsize = [];
case 4
  PSF = varargin{1};
  boundary = varargin{2};
  center = varargin{3};
  imsize = varargin{4};
end
if isempty(boundary), boundary = 'reflexive'; end
if isempty(imsize)
    if isa(PSF, 'double')
        imsize = size(PSF);
    end
end
if isa(PSF, 'cell')
    A.type = 'variant';
else
    A.type = 'invariant';
end
if isempty(center)
    P = psf(PSF);
else
    P = psf(PSF, center);
end
A.psf = P;
A.boundary = boundary;
if strcmp(A.type, 'variant')
    A.matdata = constructMatrix( P.image, P.center );
    A.transp_matdata = constructTranspMatrix(P.image, P.center);
else
    centerP = P.center;
    center = centerP{1};
    A.center = center;
    A.psf = P;
    [A.matdata, A.p] = constructMatrix_new( PSF, center, boundary, imsize );
end
A.transpose = 0;
A.imsize = imsize;
A = class(A, 'psfMatrix');

repo: IRtools


text:
function [V1_trace]=triSurfRaySetIntersect(V1,N1,F2,V2,optStruct)

numSteps=size(V1,1);
V1_trace=nan(numSteps,3);
c=1;
% hw=waitbar(c/numSteps,['Ray tracing...',num2str(round(100.*c/numSteps)),'%']);
L1=false(numSteps,1);
logicShot=false(size(F2,1),1);
for q=1:1:numSteps
    v1=V1(q,:);
    n1=N1(q,:);
    [V_intersect,logicIntersect,~] = triangleRayIntersection(v1(ones(size(F2,1),1),:),n1(ones(size(F2,1),1),:),V2,F2,optStruct);
    logicShot=logicShot | logicIntersect;
    V_intersect=V_intersect(logicIntersect,:);

    if nnz(logicIntersect)>0
%         [~,indMin]=minDist(v1,V_intersect);
        d=sqrt(sum(v1(ones(size(V_intersect,1),1),:)-V_intersect,2));
        [~,indMin]=min(d);
        V1_trace(q,:)=V_intersect(indMin,:);
        L1(q)=1;
    end
%     waitbar(c/numSteps,hw,['Ray tracing...',num2str(round(100.*c/numSteps)),'%']);
    c=c+1;
end
% close(hw);

end

author: MultiDIC

repo: MultiDIC

save_path: github-repos/MATLAB/MultiDIC-MultiDIC


text:
% closest fly, based on anglesub
function [data,units,maxanglesub] = compute_closestfly_anglesub(trx,n,dosave_d)

if nargin < 3,
  dosave_d = true;
end

flies = trx.exp2flies{n};
nflies = numel(flies);
closestfly = cell(1,nflies);
maxanglesub = cell(1,nflies);

parfor i1 = 1:nflies,
  fly1 = flies(i1);
  fprintf('fly1 = %d\n',fly1);
  flies2 = flies(trx.roi(fly1)==trx.roi(flies));
  anglesub = nan(numel(flies2),trx(fly1).nframes);
  for i2 = 1:numel(flies2),
    fly2 = flies2(i2);
    if fly1 == fly2,
      continue;
    end
    anglesub(i2,:) = anglesub_pair(trx,fly1,fly2);
  end
  [maxanglesub{i1},closesti] = max(anglesub,[],1);
  closestfly{i1} = flies2(closesti);
  closestfly{i1}(isnan(maxanglesub{i1})) = nan;
end

% so that we don't compute dcenter twice
if dosave_d,
  data = maxanglesub; %#ok<NASGU>
  units = parseunits('rad'); %#ok<NASGU>
  filename = trx.GetPerFrameFile('anglesub',n);
  try
    save(filename,'data','units');
  catch ME
    warning('Could not save anglesub data to %s: %s',filename,getReport(ME));
  end
end

data = closestfly;
units = parseunits('unit');

author: kristinbranson

repo: JAABA


text:
function S = extractvoxel(S,Voxel,fields)
if ~exist('fields','var'), fields = fieldnames(S); end
if ~exist('Voxel','var') || isempty(Voxel), disp('interactive voxel selection not implemented yet. Please contribute on github.com/neuropoly/qMRLab.'); end
if length(Voxel)<3, Voxel(3)=1; end
for ff = 1:length(fields)
    S.(fields{ff}) = squeeze(S.(fields{ff})(Voxel(1),Voxel(2),Voxel(3),:));
end


text:
% Template Matlab script to create a BIDS compatible:
%
%   sub-01_ses-01_task-FullExample_pet.json
%
% This example lists all REQUIRED, RECOMMENDED and OPTIONAL fields.

% Writing json files relies on the JSONio library
% https://github.com/bids-standard/bids-matlab
%
% Make sure it is in the matab/octave path
try
    bids.bids_matlab_version;
catch
    warning('%s\n%s\n%s\n%s', ...
            'Writing the JSON file seems to have failed.', ...
            'Make sure that the following library is in the matlab/octave path:', ...
            'https://github.com/bids-standard/bids-matlab');
end

clear;

this_dir = fileparts(mfilename('fullpath'));
root_dir = fullfile(this_dir, '..', filesep, '..');

project = 'templates';

sub_label = '01';
ses_label = '01';
task_label = 'FullExample';

name_spec.modality = 'pet';
name_spec.suffix = 'pet';
name_spec.ext = '.json';
name_spec.entities = struct('sub', sub_label, ...
                            'ses', ses_label, ...
                            'task', task_label);

% using the 'use_schema', true
% ensures that the entities will be in the correct order
bids_file = bids.File(name_spec, 'use_schema', true);

% Contrust the fullpath version of the filename
json_name = fullfile(root_dir, project, bids_file.bids_path, bids_file.filename);

% get the definition of each column,
% use the bids.Schema class from bids matlab
% example:
%
% schema = bids.Schema;
% def = schema.get_definition('TaskName');

json.TaskName = task_label;
json.Manufacturer = '';
json.ManufacturersModelName = '';
json.Units = '';
json.InstitutionName = '';
json.InstitutionAddress = '';
json.InstitutionalDepartmentName = '';
json.BodyPart = '';
json.TracerName = '';
json.TracerRadionuclide = '';
json.InjectedRadioactivity = '';
json.InjectedRadioactivityUnits = '';
json.InjectedMass = '';
json.InjectedMassUnits = '';
json.SpecificRadioactivity = '';
json.SpecificRadioactivityUnits = '';
json.ModeOfAdministration = '';
json.TracerRadLex = '';
json.TracerSNOMED = '';
json.TracerMolecularWeight = '';
json.TracerMolecularUnits = '';
json.InjectedMassPerWeight = '';
json.InjectedMassPerWeightUnits = '';
json.SpecificRadioactivityMeasTime = '';
json.MolarActivity = '';
json.MolarActivityUnits = '';
json.MolarActivityMeasTime = '';
json.InfusionRadioActivity = '';
json.InfusionStart = '';
json.InfusionSpeed = '';
json.InfusionSpeedUnits = '';
json.InjectedVolume = '';
json.Purity = '';
json.PharamceuticalName = '';
json.PharmaceuticalDoseAmount = [];
json.PharmaceuticalDoseUnits = '';
json.PharmaceuticalDoseRegimen = '';
json.PharmaceuticalDoseTime = [];
json.Anaesthesia = '';
json.TimeZero = '';
json.ScanStart = '';
json.InjectionStart = '';
json.FrameTimesStart = [];
json.FrameDuration = [];
json.ScanDate = '';
json.InjectionEnd = '';
json.AcquisitionMode = '';
json.ImageDecayCorrected = '';
json.ImageDecayCorrectionTime = '';
json.ReconMethodName = '';
json.ReconMethodParameterLabels = [];
json.ReconMethodParameterUnits = [];
json.ReconMethodParameterValues = [];
json.ReconFilterType = [];
json.ReconFilterSize = [];
json.AttenuationCorrection = '';
json.ReconMethodImplementationVersion = '';
json.AttenuationCorrectionMethodReference = '';
json.ScaleFactor = [];
json.ScatterFraction = [];
json.DecayCorrectionFactor = [];
json.PromptRate = [];
json.RandomRate = [];
json.SinglesRate = [];

%% Write JSON
% Make sure the directory exists
bids.util.mkdir(fileparts(json_name));
bids.util.jsonencode(json_name, json);

author: bids-standard

repo: bids-starter-kit


text:
function signal = set_picktrials(varargin)
% Select trials whose target variable satisfies a certain condition.
% Result-Set = set_picktrials(Signal, Arguments...)
%
% This function can be used to obtain a subset of the data set, reduced to those epochs that have
% target values matching the supplied criteria.
%
% In:
%   Signal      : Epoched data set with a target variable.
%
%   Arguments...: selection criteria (name-value pairs):
%                    'value': target value or cell array of alternative target values
%                             -> select by value
%                    'range': 2-element cell array of the lower and higher end of the range
%                             -> select by range
%                    'rank' : value rank or cell array of alternative values ranks
%                             -> select by rank
%                    currently, only one criterion is supported at a time
%
% Out:
%   Signal  :  Epoched data set which contains only the selected trials.
%
% Notes:
%   This function (in rank-selection mode) is used by methods that need to extract the trials of the
%   first class, second class, etc. from the data.
%
% Examples:
%   % for an epoched data set with target values per epoch, retain only those epochs that
%   % have target value 5 or 7
%   eeg = set_picktrials('Signal',eeg,'ValueSelection',[5 7])
%
%   % for an epoched data set with target values per epoch, retain only those epochs that
%   % have target values between -100 and -50, or between 30 and 40
%   eeg = set_picktrials('Signal',eeg,'RangeSelection',[-100 -50; 30 40])
%
%   % for an epoched data set with target values per epoch, retain only those epochs that
%   % have the smallest and 2nd smallest target value
%   eeg = set_picktrials('Signal',eeg,'RankSelection',[1 2])
%
% See also:
%   set_picktrials, set_makepos, set_targetmarkers
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2010-04-01

% set_picktrials_version<1.0> -- for the cache

% sort name-value pairs according to name
if ~exp_beginfun('editing') return; end %#ok<SEPEX>

declare_properties('independent_channels',true,'independent_trials',false);

arg_define([0 1],varargin,...
    arg_norep({'signal','Signal'}), ...
    arg({'valuesel','ValueSelection','value'},[],[],'Set of selected values. Either a single value or a cell array of values.','type','expression','shape','row'), ...
    arg({'rangesel','RangeSelection','range'},[],[],'Range of target values. Two-element cell array of the lower and higher end of the range (inclusive).','type','expression','shape','row'), ...
    arg({'ranksel','RankSelection','rank'},[],[],'Set of selected ranks. Either a single rank value or a cell array of rank values.','type','expression','shape','row'));

utl_check_fields(signal,{'epoch','data'},'signal','signal'); %#ok<NODEF>
if isempty(signal.epoch) && ~size(signal.data,3) > 1
    error('The given signal is epoched but has an empty .epoch field; this is not permitted (do not use pop_epoch for epoching but set_makepos).'); end

if ~isempty(signal.epoch)
    if ~isfield(signal.epoch,'target')
        error('The data set does not contain the required field .epoch.target; see set_gettarget for more info.'); end
    if ~isempty(ranksel) + ~isempty(valuesel) + ~isempty(rangesel) ~= 1 %#ok<NODEF>
        error('Exactly a single criterion is allowed at a time.'); end

    variable = vertcat(signal.epoch.target);

    if ~isempty(ranksel)
        if ~iscell(ranksel)
            ranksel = {ranksel}; end
        if any(round([ranksel{:}]) ~= [ranksel{:}]) || any([ranksel{:}] < 1)
            error('Rank-based selection requires positive integer values.'); end
        % do rank-based selection
        if size(variable,2) > 1
            error('Rank-based selection is only supported for one-dimensional target values.'); end
        % rank-transform the variable
        [a,b,variable] = unique(variable); %#ok<ASGLU>
        valuesel = ranksel;
    end

    if ~isempty(valuesel)
        % do value-based selection
        if ~iscell(valuesel)
            valuesel = {valuesel}; end
        inds = [];
        for i=1:length(valuesel)
            inds = [inds; find(prod(single(variable == repmat(valuesel{i},size(variable,1),1)),2))]; end         %#ok<AGROW>
    end

    if ~isempty(rangesel)
        % do range-based selection
        if ~iscell(rangesel)
            error('Range-based testing requires pairs (two-element cell arrays) of values.'); end
        if ~iscell(rangesel{1})
            rangesel = {rangesel}; end
        inds = [];
        for i=1:length(rangesel)
            if length(rangesel{i}) ~= 2
                error('Range-based testing requires pairs (two-element cell arrays) of values.'); end
            inds = [inds; intersect(find(prod(single(variable >= repmat(rangesel{i}{1},size(variable,1),1)),2)), ...
                                    find(prod(single(variable <= repmat(rangesel{i}{2},size(variable,1),1)),2)))];  %#ok<AGROW>
        end
    end

    if isempty(inds)
        disp_once('WARNING: This data set contains no trials for one of your target classes: please check whether your target marker naming is correct, and ensure that your data has enough target events in each of its required subsets (e.g., in a (nested) cross-validation).'); end
    signal = exp_eval(set_selepos(signal,inds(:)'));
end

exp_endfun;

repo: REST


text:
function pass = test_minres(pref)
% Test preconditioned minres.

% Tolerance:
if ( nargin == 0 )
    pref = cheboppref;
end
tol = 1e2*pref.bvpTol;

%% Example 1: (-u_xx=f, bc=0, sum(f)==0)
a = @(x) 1+0*x;
c = @(x) -0*x;
L = @(x,u) -diff(a(x).*diff(u)) + c(x).*u;

% Chebop solve:
N = chebop( L );
N.bc = 0;
f = chebfun(@(x) 1-3*x.^2);
u = N \ f;

v = minres(N, f);

% Errors:
pass(1) = ( norm( u - v ) < tol );

%% Example 2: (-(a(x)*u_x)_x+c(x)*u=f, bc=0, sum(f)==0)
a = @(x) 2+cos(pi*x);
c = @(x) -10*x;
L = @(x,u) -diff(a(x).*diff(u)) + c(x).*u;

% Chebop solve:
N = chebop( L );
N.bc = 0;
f = chebfun(@(x) 1-3*x.^2);
u = N \ f;

v = minres(N, f);

% Errors:
pass(2) = ( norm( u - v ) < tol );

%% Example 3: (-(a(x)*u_x)_x + c(x)*u=f, bc=0, sum(f)==0)

a = @(x) 2+cos(pi*x);
c = @(x) 1-10*x.^2;
L = @(x,u) -diff(a(x).*diff(u)) + c(x).*u;

% Chebop solve:
N = chebop( L );
N.bc = 0;
f = chebfun(@(x) 1-3*x.^2);
u = N \ f;

v = minres(N, f);

% Errors:
pass(3) = ( norm( u - v ) < tol );

%% Example 4: (-(a(x)*u_x)_x + c(x)*u=f, bc=0, mean(f)~=0)
a = @(x) 2+cos(pi*x);
c = @(x) 1+10*x.^2;
L = @(x,u) -diff(a(x).*diff(u)) + c(x).*u;

% Chebop solve:
N = chebop( L );
N.bc = 0;
f = chebfun(@(x) 1-2*x.^2);
u = N \ f;

% Chebfun-ready pcg:
v = minres(N, f);

pass(4) = ( norm(u - v) < tol );

%% Example 5: (-(a(x)*u_x)_x + c(x)*u=f, bc~=0, mean(f)~=0)
a = @(x) 2+cos(pi*x);
c = @(x) 1-100*x.^2;
L = @(x,u) -diff(a(x).*diff(u)) + c(x).*u;

% Chebop solve:
N = chebop( L );
N.lbc = 1;
N.rbc = -1;
f = chebfun(@(x) 1-2*x.^2);
u = N \ f;

% Chebfun-ready pcg:
v = minres(N, f, [], 40);

pass(5) = ( norm(u - v) < tol );

if ( all(pass) == 1 )
    pass = 1;
end

end


text:
function [name, cmds, errs, msgs] = gitGetBranch(repo, quiet)
name = '';
cmds = {};

if ~exist('repo','var') || isempty(repo)
    repo = [pwd, '/'];
end
if ~exist('quiet','var') || isempty(quiet)
    quiet = 1;
end

currdir = pwd;

repoFull = filesepStandard_startup(repo,'full');

ii = 1;
cmds{ii,1} = sprintf('cd %s', repoFull); ii = ii+1;
cmds{ii,1} = sprintf('%sgit branch',setTerminal()); ii = ii+1; kk = ii-1;

[errs, msgs] = exeShellCmds(cmds, false, quiet);

if all(errs==0)
    branches = str2cell_startup(msgs{kk});
    for jj = 1:length(branches)
        if branches{jj}(1)=='*'
            break;
        end
    end
    name = extractBranchName(branches{jj});
end

cd(currdir);

% -----------------------------------------
function b = extractBranchName(b)
b = removeGarbage(b);
k = find(b<43);
b(k) = ''; %#ok<FNDSB>

% -----------------------------------------
function b = removeGarbage(b)

% Remove garbage strings from branch name. Matlab for MAC
% creates these issues because of peculiar shell environemnt
if ismac()
    k = [];
    knownGarbage = {
        '[m';
        '[32m';
        };
    for kk = 1:length(knownGarbage)
        j = strfind(b, knownGarbage{kk});
        for jj = 1:length(j)
            k = [k, j(jj):j(jj)+length(knownGarbage{kk})-1]; %#ok<AGROW>
        end
    end
    b(k) = '';
end

author: BUNPC


text:
function d=match_distance(XI,XJ)
  % Implementation of the match distance to use with pdist
  % (cf. "The Earth Movers' Distance as a Metric for Image Retrieval",
  %      Y. Rubner, C. Tomasi, L.J. Guibas, 2000)
  %
  % @author: B. Schauerte
  % @date:   2009
  % @url:    http://cvhci.anthropomatik.kit.edu/~bschauer/

  % Copyright 2009 B. Schauerte. All rights reserved.
  %
  % Redistribution and use in source and binary forms, with or without
  % modification, are permitted provided that the following conditions are
  % met:
  %
  %    1. Redistributions of source code must retain the above copyright
  %       notice, this list of conditions and the following disclaimer.
  %
  %    2. Redistributions in binary form must reproduce the above copyright
  %       notice, this list of conditions and the following disclaimer in
  %       the documentation and/or other materials provided with the
  %       distribution.
  %
  % THIS SOFTWARE IS PROVIDED BY B. SCHAUERTE ''AS IS'' AND ANY EXPRESS OR
  % IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  % WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  % DISCLAIMED. IN NO EVENT SHALL B. SCHAUERTE OR CONTRIBUTORS BE LIABLE
  % FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  % CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  % SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  % BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  % WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  % OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  % ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  %
  % The views and conclusions contained in the software and documentation
  % are those of the authors and should not be interpreted as representing
  % official policies, either expressed or implied, of B. Schauerte.

  m=size(XJ,1); % number of samples of p
  p=size(XI,2); % dimension of samples

  assert(p == size(XJ,2)); % equal dimensions
  assert(size(XI,1) == 1); % pdist requires XI to be a single sample

  d=zeros(m,1); % initialize output array

  cxi=cumsum(XI,2); % cumulative histograms
  cxj=cumsum(XJ,2); % cumulative histograms

  for i=1:m
    for j=1:p
      d(i,1) = d(i,1) + abs(cxi(1,j) - cxj(i,j));
    end
  end

author: opencobra

repo: cobratoolbox


text:
%JLAB_THANKS  Sources of support for developing this software.
%
%   This software was developed with the support of the Air Force Office
%   of Scientific Reseach contract #F49620-94-1-0043, the Office of Naval
%   Research (ONR) Physical Oceanography program, a National Defense
%   Science and Engineering Graduate (NDSEG) fellowship from the
%   Department of Defense (DOD), the National Oceanic and Atmospheric
%   Agency (NOAA) Atlantic Climate Change Program (ACCP), the National
%   Aeronautics and Space Administration (NASA) contracts #1221119 and
%   #NNH14CL78C, a Chateaubriand Fellowship from the French government, a
%   fellowship from the Conseil Scientifique of the Universite Pierre et
%   Marie Curie, NASA Goddard Space Flight Center contract #NNG04HZ12C, and
%   by awards #0526297, #0751697, #0849371, #1031002, #1235310, #1459347,
%   and #1658564 from the Physical Oceanography program of the National
%   Science Foundation (NSF).
%   _________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2007--2020 J.M. Lilly --- type 'help jlab_license' for details

author: jonathanlilly

repo: jLab

save_path: github-repos/MATLAB/jonathanlilly-jLab