text:
function [field, allVarString, indVarName, pdeVarNames, pdeflag, ...
    eigVarNames, allVarNames]  = setupFields(guifile, input, type, allVarString)
%SETUPFIELDS   Convert input from GUI window to format useful for Chebfun.
%
% Calling sequence:
%
%   [FIELD, ALLVARSTRING, INDVARNAME, PDEVARNAMES, PDEFLAG,  EIGVARNAMES, ...
%       ALLVARNAMES] = SETUPFIELDS(GUIFILE, INPUT, TYPE, ALLVARSTRING)
%
% Here, the inputs are:
%
%   GUIFILE:        A CHEBGUI object, describing the problem shown in the GUI.
%   INPUT:          The 'String' property of a particular input field of the GUI.
%   TYPE:           The type of the field (differential equation, boundary
%                   conditions or initial guess/condition).
%   ALLVARSTRING:   A strings, containing the name of all variables that appear
%                   in a problem.
%
% The outputs are:
%   FIELD:          A string that can be converted to anonymous function,
%                   describing the INPUT variable.
%   ALLVARSTRING:   A strings, containing the name of all variables that appear
%                   in a problem.
%   INDVARNAME:     A cell-array of strings that contains the name of the
%                   independent variables that appear in the problem. The first
%                   entry corresponds to the time variable, the second to the
%                   potential time variable.
%   PDEVARNAMES:    A cell array of strings that appear on PDE format in INPUT,
%                   i.e. u_t.
%   PDEFLAG:        A vector, whose kth element is equal to 1 of the kth line of
%                   INPUT is of PDE format, e.g. u_t = u'', 0 otherwise.
%   EIGVARNAMES:    A string that indicates how the eigenvalue parameter appears
%                   in the problem, that is, either l, lam or lambda.
%   ALLVARNAMES:    A cell array of string, containing the name of all variables
%                   that appear in a problem.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% For BCs, we need to check whether varNames contains anything not found in
% varNames of the DE. Should we make the varNames of the DE as parameters? Also
% check for indVarName in deRHS.

% Number of rows in the input.
numOfRows = max(size(input));

% Binary flag for PDE detection. The kth element is going to be equal to 1 of
% the kth row of the input has PDE input in it, e.g. u_t.
pdeflag = zeros(1,numOfRows);

% What variables appear with the PDE subscript _ on them?
pdeVarNames = '';

% A temporary string for the space variable, as we don't know yet whether it is
% going to be r, t or x. This will then get replaced later.
dummys = 'DUMMYSPACE';

if ( numOfRows == 1 )
    % In this case, we only have to deal with a single line of input.
    [anFun, indVarName, allVarNames, pdeVarNames, eigVarNames, commaSeparated] = ...
        setupLine(guifile, input{1}, type);

    % Check whether we have too many variables involved in a PDE.
    if ( ~isempty(pdeVarNames) ) % Not a PDE (or we can't do this type yet!)
        pdeflag = true;

        % Are we actually working in PDE mode?
        assert(strcmpi(guifile.type, 'PDE'), ...
            'CHEBFUN:CHEBGUI:setupField:incorrectPDEmode', ...
            ['Problem specified appears to be a PDE. Please ensure you''re' ...
            'working in the correct mode in Chebgui.'])

        % Check whether we have a match of variable names, i.e. we want u
        % and u_t, not u and v_t:
        if ( (length(allVarNames) > 1) || (length(pdeVarNames) > 1) )
            error('CHEBFUN:CHEBGUI:setupFields:numberOfVariables', ...
                'Too many variables.');
        end

        % Find where the PDE variable appears:
        underScoreLocation = strfind(pdeVarNames{1},'_');
        if ( ~strcmp(allVarNames{1}, pdeVarNames{1}(1:underScoreLocation-1)) )
            error('CHEBFUN:CHEBGUI:setupFields:variableNames', ...
                'Inconsistent variable names.');
        end
    end

    % Only need to convert the cell to a string for DE -- information has been
    % passed for BCs
    if ( strcmp(type, 'DE') )
        allVarString = allVarNames{1};
    end

    % Create the string which will become the anonymous function. Put x (or t)
    % as the first argument of the anonymous function if we have a BVP or EIG.

    % If we are working with an eigenvalue problem, the differential equation
    % will have important information on both sides of the = sign if we are
    % solving a generalized problem. In this case, we want to keep the input in
    % two separate strings in a cell-array.
    if ( strcmp(guifile.type, 'eig') && iscell(anFun) )
        field1 = ['@(', dummys, ',', allVarString, ') ', anFun{1}];
        field2 = ['@(', dummys, ',', allVarString, ') ', anFun{2}];
        field = {field1 ; field2};
    elseif ( ~strcmp(guifile.type, 'pde') && strcmp(type, 'DE') )
        field = ['@(', dummys, ',', allVarString, ') ', anFun];

    % Otherwise, add variables in front of what will be anonymous functions.
    % This is not needed for 'dirichlet', 'neumann', etc... This can only happen
    % in BCs, and in that case, allVarNames will be empty
    elseif ( ~isempty(allVarNames) )
        if ( commaSeparated )
            anFun = ['[', anFun, ']'];
        end

        if ( strcmp(type, 'BCnew') )
            field = ['@(', dummys, ',', allVarString, ') ', anFun];
        else
            field = ['@(', allVarString, ') ', anFun, ''];
        end
    else
        field = anFun;
    end

else % Have a system, go through each row
    % Keep track of every variable encountered in the problem
    allVarNames = {};
    allPdeVarNames = {};
    indVarName = [];
    anFun = cell(1, numOfRows);
    % Loop through the rows
    for k = 1:numOfRows
        [anFun{k}, indVarNameTemp, varNames, pdeVarNames, eigVarNames, dummy] = ...
            setupLine(guifile, input{k}, type);
        if ( strcmp(anFun{k}([1 end]), '[]') )
            anFun{k}([1 end]) = [];
        end

        % Update what variables appear in the problem.
        allVarNames = [allVarNames ; varNames];

        % Only allow one time derivative in each line
        if ( length(pdeVarNames) > 1 )
            error('CHEBFUN:CHEBGUI:setupFields:tooManyTimeDerivatives', ...
                'Only one time derivative per line allowed')
        end

        if ( isempty(pdeVarNames) )
            % Indicate that no PDE variable was found in this line.
            pdeVarNames = '|';
        else
            % Indicate that this line was of PDE format.
            pdeflag(k) = 1;
        end

        if ( isempty(indVarName) )
            indVarName = indVarNameTemp;
        elseif ( ~myStringCompare(indVarName{1}, indVarNameTemp{1}) || ...
                ~myStringCompare(indVarName{2}, indVarNameTemp{2}) )
            error('CHEBFUN:CHEBGUI:setupFields:differentIndepVars', ...
                'Different names for independent variables detected')
        end

        % Update what variables appear on PDE format.
        allPdeVarNames = [allPdeVarNames ; pdeVarNames];
    end

    % Remove duplicate variable names
    allVarNames = unique(allVarNames);

    % Construct the handle part. For the DE field, we need to collect all
    % the variable names in one string. If we are working with BCs, we have
    % already passed that string in (as the parameter allVarString).
    if ( strcmp(type, 'DE') )
        allVarString = allVarNames{1};
        for varCounter = 2:length(allVarNames)
            allVarString = [allVarString, ',', allVarNames{varCounter}];
        end
    end

    indx = (1:numOfRows)';
    % For PDEs we need to reorder so that the order of the time derivatives
    % matches the order of the input arguments.
    if ( any(pdeflag) )
        for k = 1:numel(allPdeVarNames)
            if ( ~pdeflag(k) )
                continue % Not a PDE variable, do nothing
            end

            vark = allPdeVarNames{k};
            if ( strcmp(vark, '|') )
                continue  % Skip dummy pdevarname
            end

            % Get the kth pdevarname
            vark = vark(1:find(vark == '_', 1, 'first')-1);

            % Find which varname this matches
            idx3 = find(strcmp(vark,allVarNames));

            % Update the index list
            indx(find(indx == idx3)) = indx(k);
            indx(k) = idx3;
        end

        [dummy, indx] = sort(indx);     % Invert the index
        pdeflag = pdeflag(indx);        % Update the pdeflags
        allPdeVarNames(strcmp(allPdeVarNames, '|')) = []; % Delete the junk
        pdeVarNames = allPdeVarNames;
    end

    % Did we have PDE variables but are not actually working in PDE mode?
    assert( ~( any(pdeflag) && ~strcmpi(guifile.type, 'PDE')), ...
        'CHEBFUN:CHEBGUI:setupField:incorrectPDEmode', ...
        ['Problem specified appears to be a PDE. Please ensure that you''re' ...
        ' working in the correct mode in Chebgui.'])

    % If we are solving a BVP or EIG, we now need x as the first argument as
    % well. However, we don't want that variable in allVarString as we use that
    % information when setting up BCs. Create the string that goes at the start
    % of the final string.
    if ( (~strcmp(guifile.type, 'pde') && strcmp(type, 'DE')) || ...
            strcmp(type, 'BCnew') )
        fieldStart = ['@(', dummys, ',', allVarString, ') '];
    else
        fieldStart = ['@(', allVarString, ') '];
    end

    % Construct the function. Need to treat eig. problems separately as there we
    % can have nontrivial LHS and RHS at the same time.
    allAnFun = [];
    if ( strcmp(guifile.type, 'eig') && iscell(anFun{1}) )
        allAnFun1 = [];
        allAnFun2 = [];
        for k = 1:numOfRows
            allAnFun1 = [allAnFun1, anFun{indx(k)}{1}, ';'];
            allAnFun2 = [allAnFun2, anFun{indx(k)}{2}, ';'];
        end

        % Remove the last comma
        allAnFun1(end) = [];
        allAnFun2(end) = [];

        % Set up LHS and RHS fields
        field1 = [fieldStart, '[', allAnFun1, ']'];
        field2 = [fieldStart, '[', allAnFun2, ']'];
        field = {field1 ; field2};
    else
        % Concatenate each anonymous functions vertically.
        for k = 1:numOfRows
            allAnFun = [allAnFun, anFun{indx(k)},  '; '];
        end
        allAnFun(end-1:end) = []; % Remove the last semicolon and space.

        % Wrap the concatenated field with []-s.
        field = [fieldStart, '[', allAnFun, ']'];
    end

end

end

function [field, indVarName, varNames, pdeVarNames, eigVarNames, commaSeparated] ...
    = setupLine(guifile, input, type)
%SETUPLINE      Convert an individual input line to format useful for Chebfun.
%
% Calling sequence:
%
%   [FIELD, INDVARNAME, VARNAMES, PDEVARNAMES, EIGVARNAMES, COMMASEPARATED] =
%       SETUPLINE(GUIFILE, INPUT, TYPE)
%
% Here, the inputs are:
%
%   GUIFILE:        A CHEBGUI object, describing the problem shown in the GUI.
%   INPUT:          A single line of the 'String' property of a particular
%                   input field of the GUI.
%   TYPE:           The type of the field (differential equation, boundary
%                   conditions or initial guess/condition).
%
% The outputs are:
%   FIELD:          A string that can be converted to anonymous function,
%                   describing the INPUT variable.
%   INDVARNAME:     A cell-array of strings that contains the name of the
%                   independent variables that appear in the problem. The first
%                   entry corresponds to the time variable, the second to the
%                   potential time variable.
%   VARNAMES:       A cell array of string, containing the name of all variables
%                   that appear in the line INPUT.
%   PDEVARNAMES:    A cell array of strings that appear on PDE format in the
%                   line INPUT, i.e. u_t.
%   EIGVARNAMES:    A string that indicates how the eigenvalue parameter appears
%                   in the problem, that is, either l, lam or lambda.
%   COMMASEPARATED: Equal to 1 if the line INPUT is comma separated, for
%                   example, "u=1, v=2+x".

% Do we need to convert a BC to an anonymous function?
convertBCtoAnon = 0;

% Usually, input lines are not comma separated.
commaSeparated = 0;

if ( ~isempty(strfind(input, '@')) ) % User supplied anon. function
    % Look at the part of the string that starts after the @(x,u,...) part.
    firstRPloc = strfind(input, ')');
    trimmedInput = input(firstRPloc+1:end);

    % Inspect the string, which will give us the name of the independent
    % variable (which we assume to be either r, x or t).
    [field, indVarName, varNames, pdeVarNames, eigVarNames, commaSeparated] = ...
        stringParser.str2anon(trimmedInput, guifile.type, type);

    return

elseif ( any(strcmp(type,{'BC','BCnew'})) )  % More types of syntax for BCs
    bcNum = str2num(input);

    % Check whether we have a number (OK), allowed strings (OK) or whether
    % we will have to convert the string to anon. function (i.e. the input
    % is on the form u' +1 = 0).
    if ( ~isempty(bcNum) )
        field = input;
        indVarName = []; % Don't need to worry about lin. func. in this case
        varNames = [];
        pdeVarNames = [];
        eigVarNames = [];
    elseif ( strcmpi(input, 'dirichlet') || strcmpi(input, 'neumann') || ...
            strcmpi(input, 'periodic') )
        % Add extra 's to allow evaluation of the string
        field = ['''', input, ''''];
        indVarName = []; % Don't need to worry about lin. func. in this case
        varNames = [];
        pdeVarNames = [];
        eigVarNames = [];
    else
        convertBCtoAnon = 1;
        guifile.type = 'bvp'; % Convert to 'BVP' type for BCs.
    end
end

if ( any(strcmp(type, {'DE', 'INIT', 'INITSCALAR'})) || convertBCtoAnon )
    % Convert to anonymous function string
    [field, indVarName, varNames, pdeVarNames, eigVarNames, commaSeparated] = ...
        stringParser.str2anon(input, guifile.type, type);
end

end

function res =  myStringCompare(str1, str2)
% Modified strcmp, if we compare with an empty string, give a match
if ( isempty(str1) || isempty(str2) )
    res = 1;
else
    res = strcmp(str1, str2);
end

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function [xi,w]=secondOrderTriangleCubPoints()
%%SECONDORDERTRIANGLECUBPOINTS Obtain second-order cubature points for
%   integration over a triangle in 2D. The points and weights are for the
%   triangle with vertices (1,0), (0,1), (0,0), but can be transformed to
%   any triangle using transformSimplexTriPoints.
%
%INPUTS: None
%
%OUTPUTS: xi A 2XnumCubPoints set of points for the standard triangle.
%          w A 1XnumCubPoints set of cubature weights. This sums to the
%            volume of the triangle (1/2).
%
%This function implements the points given in [1] (3 points).
%
%EXAMPLE:
%Given the vertices of the simplex, we compare a second-order moment
%computed using these cubature points to one computed using
%monomialIntSimplex. The results are the same within typical finite
%precision limits.
% [xi,w]=secondOrderTriangleCubPoints();
% alpha=[1;1];
% theMoment=findMomentFromSamp(alpha,xi,w)
% intVal=monomialIntSimplex(alpha)
%
%REFERENCES:
%[1] F. D. Witherden and P. E. Vincent, "On the identification of symmetric
%    quadrature rules for finite element methods," Computer and Mathematics
%    with Applications, vol. 69, no. 10, pp. 1232-1241, May 2015.
%
%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

M=[-0.66666666666666666666666666666666666667,   0.33333333333333333333333333333333333333,   0.66666666666666666666666666666666666667;
    0.33333333333333333333333333333333333333,  -0.66666666666666666666666666666666666667,   0.66666666666666666666666666666666666667;
   -0.66666666666666666666666666666666666667,  -0.66666666666666666666666666666666666667,   0.66666666666666666666666666666666666667];

w=M(:,3);
xi=M(:,1:2)';
%Transform the points to the standard triangle.
v1=[-1,-1, 1;
    -1, 1,-1];
v2=[1,0,0;
    0,1,0];
[A,d]=affineTransBetweenTriangles(v1,v2);
xi=bsxfun(@plus,A*xi,d);
w=w/4;
end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
function h_ax = plotSphFunctionTriangle(F, dirs, realComplex, h_ax)
%PLOTSPHFUNCTIONTRIANGLE Plots a spherical function on unstructured grid
%
%   F:  vector of K function values on the sampling points
%   dirs:   [azimuth1 inclination1; ...; azimuthK inclinationK] angles in
%           rads for each evaluation point, where inclination is the polar
%           angle from zenith: inclination = pi/2-elevation
%   realComplex: {'real','complex'} if the function is real then it is
%                plotted with one surface for its positive part and one for
%                its negative part. If it is complex, the magnitude
%                function is plotted, with its phase mapped on the colormap
%   h_ax: optional argument to define an axis handle for the plot,
%         otherwise the new axis handle is returned
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   Archontis Politis, 20/02/2015
%   archontis.politis@aalto.fi
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin==3
    figure
    h_ax = axes;
elseif nargin==2
    figure
    h_ax = axes;
    realComplex = 'complex';
else
    axes(h_ax);
end

% triangulate sampling points
aziIncl2aziElev = @(dirs) [dirs(:,1) pi/2-dirs(:,2)];
dirs = aziIncl2aziElev(dirs);
[triangulated.vertices(:,1), triangulated.vertices(:,2), triangulated.vertices(:,3)] = ...
    sph2cart(dirs(:,1), dirs(:,2), 1);
triangulated.vertices = abs(F)*ones(1,3) .* triangulated.vertices;
triangulated.faces = sphDelaunay(dirs);

% construct real positive and negative colormap if real function
CData = zeros(length(F),3);
if isequal(realComplex, 'real')
    pos_idx = find(F>=0);
    neg_idx = find(F<0);
    for i=1:length(pos_idx)
        CData(pos_idx(i),:) = [0 0 255];
    end
    for i=1:length(neg_idx)
        CData(neg_idx(i),:) = [255 0 0];
    end
elseif isequal(realComplex, 'complex')
    CData = angle(F);
end

% plot 3d axes
maxF = max(max(abs(F)));
line([0 1.5*maxF],[0 0],[0 0],'color',[1 0 0])
line([0 0],[0 1.5*maxF],[0 0],'color',[0 1 0])
line([0 0],[0 0],[0 1.5*maxF],'color',[0 0 1])

% plot function
hold on
triangulated.Facecolor = 'interp';
triangulated.Edgecolor = 'k';
triangulated.FaceVertexCData = CData;
patch(triangulated)
xlabel('x')
ylabel('y')
zlabel('z')
light('Position',[0 0 1],'Style','infinite');
light('Position',[-1 -1 -1],'Style','infinite');
light('Position',[0 0 -1],'Style','infinite');
material shiny
axis equal
grid

end

author: polarch

repo: Spherical-Harmonic-Transform


text:
%% Copyright (C) 2014-2019 Colin B. Macdonald
%%
%% This file is part of OctSymPy.
%%
%% OctSymPy 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 software is distributed in the hope that it will be useful,
%% but WITHOUT ANY WARRANTY; without even the implied warranty
%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
%% the GNU General Public License for more details.
%%
%% You should have received a copy of the GNU General Public
%% License along with this software; see the file COPYING.
%% If not, see <http://www.gnu.org/licenses/>.

%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @defmethod  @@sym function_handle (@var{f})
%% @defmethodx @@sym function_handle (@var{f1}, @dots{}, @var{fn})
%% @defmethodx @@sym function_handle (@dots{}, @var{param}, @var{value})
%% @defmethodx @@sym function_handle (@dots{}, 'vars', [@var{x} @dots{} @var{z}])
%% @defmethodx @@sym function_handle (@dots{}, 'file', @var{filename})
%% @defmethodx @@sym function_handle (@dots{}, 'outputs', [@var{o1} @dots{} @var{on}])
%% Convert symbolic expression into a standard function.
%%
%% This can make anonymous functions from symbolic expressions:
%% @example
%% @group
%% syms x y
%% f = x^2 + sin(y)
%%   @result{} f = (sym)
%%        2
%%       x  + sin(y)
%% h = function_handle(f)
%%   @result{} h = @@(x, y) x .^ 2 + sin (y)
%% h(2, pi/2)
%%   @result{} ans =  5
%% @end group
%% @end example
%%
%% Multiple arguments correspond to multiple outputs of the
%% function.  For example, the final @code{x} in this example
%% specifies the third output (rather than the input):
%% @example
%% @group
%% h = function_handle(x^2, 5*x, x);
%% [a, b, c] = h(2)
%%   @result{} a = 4
%%   @result{} b = 10
%%   @result{} c = 2
%% @end group
%% @end example
%%
%% The order and number of inputs can be specified:
%% @example
%% @group
%% syms x y z
%% h = function_handle(f, 'vars', [z y x])
%%   @result{} h = @@(z, y, x) x .^ 2 + sin (y)
%% @end group
%% @end example
%%
%% For compatibility with the Symbolic Math Toolbox in Matlab, we
%% provide a synonym: @pxref{@@sym/matlabFunction}
%%
%% OctSymPy can also generate an @code{.m} file from a symbolic
%% expression by passing the keyword @code{file} with a string
%% argument for @var{filename}.  A handle to the function in the
%% file will be returned.
%% Passing an empty @var{filename} creates an anonymous function:
%% @example
%% @group
%% h = function_handle(f, 'file', '')
%%   @result{} h = @@(x, y) x .^ 2 + sin (y)
%% @end group
%% @end example
%%
%% FIXME: naming outputs with @var{PARAM} as @code{outputs}
%% not implemented.
%%
%% FIXME: does not ``optimize'' code, for example, using common
%% subexpression elimination.
%%
%% @seealso{@@sym/ccode, @@sym/fortran, @@sym/latex, @@sym/matlabFunction}
%% @end defmethod

function f = function_handle(varargin)

  % We use the private/codegen function only for its input parsing
  [flg, meh] = codegen(varargin{:}, 'lang', 'octave');
  assert(flg == -1);
  [Nin, inputs, inputstr, Nout, param] = deal(meh{:});

  %% Outputs
  if (param.codegen) && (~isempty(param.fname))
    cmd = { '(expr,fcnname,filename,showhdr,in_vars) = _ins' ...
            'from sympy.utilities.codegen import codegen' ...
            'try:' ...
           ['    out = codegen((fcnname,expr), "' param.lang ...
            '", filename, header=showhdr' ...
            ', argument_sequence=in_vars)'] ...
            'except ValueError as e:' ...
            '    return (False, str(e))' ...
            'return (True, out)' };

    [fcnpath, fcnname, fcnext] = fileparts(param.fname);
    [worked, out] = pycall_sympy__ (cmd, varargin(1:Nout), fcnname, fcnname, param.show_header, inputs);

    if (~worked)
      if (strcmp(out, 'Language ''octave'' is not supported.'))
        error('function_handle: your SymPy has no octave codegen');
      else
        out
        error('function_handle: Some other error from SymPy code gen?  file a bug!');
      end
    end
    M.name = out{1}{1};
    M.code = out{1}{2};

    assert (strcmp (M.name, [fcnname '.m']), 'sanity check failed: names should match');

    file_to_write = fullfile(fcnpath, [fcnname '.m']);
    [fid,msg] = fopen(file_to_write, 'w');
    assert(fid > -1, msg)
    fprintf(fid, '%s', M.code);
    fclose(fid);
    fprintf('Wrote file %s.\n', file_to_write);

    % FIXME: Check upstream to rehash the files correctly once created
    % Due to an upstream bug in octave on windows, we have to wait for the file to be loaded.
    % See https://savannah.gnu.org/bugs/?31080 for more information...\n
    if (exist('OCTAVE_VERSION', 'builtin') && ispc())
      fprintf('Workaround savannah.gnu.org/bugs/?31080: waiting for %s... ', fcnname);
      fflush(stdout);
      while (exist(fcnname) == 0)
        rehash()
        pause(1)
      end
      fprintf('Found!\n');
    end

    f = str2func(fcnname);

  else % output function handle

    exprstrs = {};
    for i=1:Nout
      expr = varargin{i};
      cmd = { '(f,) = _ins' ...
              'try:' ...
              '    a, b, s = octave_code(f, human=False)' ...
              'except NameError as e:' ...
              '    return (False, str(e))' ...
              'if len(b) != 0:' ...
              '    return (False, s)' ...
              'if len(a) != 0:' ...
              '    return (False, "expected symbols-to-declare to be empty")' ...
              'return (True, s)' };
      [worked, codestr] = pycall_sympy__ (cmd, expr);
      if (~worked)
        error('function_handle: python codegen failed: %s', codestr)
      end
      exprstr{i} = codestr;
    end

    if (Nout == 1)
      f = eval(sprintf('@(%s) %s', inputstr, exprstr{1}));
    else
      str = [ sprintf('@(%s) deal(', inputstr) ...
              sprintf('%s,', exprstr{:})];
      str = [str(1:end-1) ')'];
      f = eval(str);
    end
  end

  % Note: this fails in Matlab SMT too:
  %h = function_handle({x,y,z},'vars',{x y z})
  % (could fix by moving it outside @sym)
end

%!shared x,y,z
%! syms x y z

%!test
%! % basic test
%! h = function_handle(2*x);
%! assert(isa(h, 'function_handle'))
%! assert(h(3)==6)

%!test
%! % autodetect inputs
%! h = function_handle(2*x*y, x+y);
%! [t1, t2] = h(3,5);
%! assert(t1 == 30 && t2 == 8)

%!test
%! % specified inputs
%! h = function_handle(2*x*y, 'vars', [x y]);
%! assert(h(3,5)==30)
%! h = function_handle(2*x*y, x+y, 'vars', [x y]);
%! [t1, t2] = h(3,5);
%! assert(t1 == 30 && t2 == 8)

%!test
%! % cell arrays for vars list
%! h = function_handle(2*x*y, x+y, 'vars', {x y});
%! [t1, t2] = h(3,5);
%! assert(t1 == 30 && t2 == 8)
%! h = function_handle(2*x*y, x+y, 'vars', {'x' 'y'});
%! [t1, t2] = h(3,5);
%! assert(t1 == 30 && t2 == 8)

%!test
%! % cell arrays specfies order, overriding symvar order
%! h = function_handle(x*y, 12/y, 'vars', {y x});
%! [t1, t2] = h(3, 6);
%! assert(t1 == 18 && t2 == 4)
%! h = function_handle(x*y, 12/y, 'vars', [y x]);
%! [t1, t2] = h(3, 6);
%! assert(t1 == 18 && t2 == 4)

%!test
%! % cell arrays specfies order, overriding symvar order
%! h = function_handle(x*y, 12/y, 'vars', {y x});
%! [t1, t2] = h(3, 6);
%! assert(t1 == 18 && t2 == 4)
%! h = function_handle(x*y, 12/y, 'vars', [y x]);
%! [t1, t2] = h(3, 6);
%! assert(t1 == 18 && t2 == 4)

%!test
%! % Functions with different names in Sympy.
%! f = abs(x);  % becomes Abs(x)
%! h = function_handle(f);
%! assert(h(-10) == 10)
%! f = ceil(x);
%! h = function_handle(f);
%! assert(h(10.1) == 11)

%!test
%! % 'file' with empty filename returns handle
%! h = function_handle(2*x*y, 'file', '');
%! assert(isa(h, 'function_handle'))
%! assert(h(3,5)==30)
%! h = function_handle(2*x*y, 'vars', {x y}, 'file', '');
%! assert(isa(h, 'function_handle'))
%! assert(h(3,5)==30)

%!test
%! % output to disk
%! fprintf('\n')
%! if (exist ('OCTAVE_VERSION', 'builtin'))
%!   temp_file = tempname('', 'oct_');
%! else
%!   temp_file = tempname();
%! end
%! % allow loading function from temp_file
%! [temp_path, ans, ans] = fileparts(temp_file);
%! addpath(temp_path);
%! f = function_handle(2*x*y, 2^x, 'vars', {x y z}, 'file', temp_file);
%! assert( isa(f, 'function_handle'))
%! addpath(temp_path);  % Matlab 2014a needs this?
%! [a,b] = f(10,20,30);
%! assert (isnumeric (a) && isnumeric (b))
%! assert (a == 400)
%! assert (b == 1024)
%! if (exist ('OCTAVE_VERSION', 'builtin'))
%!   assert (unlink([temp_file '.m']) == 0)
%! else
%!   delete ([temp_file '.m'])
%! end
%! % remove temp_path from load path
%! rmpath(temp_path);

%!test
%! % output to disk: also works with .m specified
%! if (exist ('OCTAVE_VERSION', 'builtin'))
%!   temp_file = [tempname('', 'oct_') '.m'];
%! else
%!   temp_file = [tempname() '.m'];
%! end
%! % allow loading function from temp_file
%! [temp_path, ans, ans] = fileparts(temp_file);
%! addpath(temp_path);
%! f = function_handle(2*x*y, 2^x, 'vars', {x y z}, 'file', temp_file);
%! assert( isa(f, 'function_handle'))
%! addpath(temp_path);  % Matlab 2014a needs this?
%! [a,b] = f(10,20,30);
%! assert (isnumeric (a) && isnumeric (b))
%! assert (a == 400)
%! assert (b == 1024)
%! if (exist ('OCTAVE_VERSION', 'builtin'))
%!   assert (unlink(temp_file) == 0)
%! else
%!   delete (temp_file)
%! end
%! % remove temp_path from load path
%! rmpath(temp_path);

%!test
%! % non-scalar outputs
%! H = [x y z];
%! M = [x y; z 16];
%! V = [x;y;z];
%! h = function_handle(H, M, V);
%! [t1,t2,t3] = h(1,2,3);
%! assert(isequal(t1, [1 2 3]))
%! assert(isequal(t2, [1 2; 3 16]))
%! assert(isequal(t3, [1;2;3]))

%!test
%! % non-scalar outputs in .m files
%! H = [x y z];
%! M = [x y; z 16];
%! V = [x;y;z];
%! if (exist ('OCTAVE_VERSION', 'builtin'))
%!   temp_file = tempname('', 'oct_');
%! else
%!   temp_file = tempname();
%! end
%! % allow loading function from temp_file
%! [temp_path, ans, ans] = fileparts(temp_file);
%! addpath(temp_path);
%! h = function_handle(H, M, V, 'vars', {x y z}, 'file', temp_file);
%! assert( isa(h, 'function_handle'))
%! addpath(temp_path);  % Matlab 2014a needs this?
%! [t1,t2,t3] = h(1,2,3);
%! assert(isequal(t1, [1 2 3]))
%! assert(isequal(t2, [1 2; 3 16]))
%! assert(isequal(t3, [1;2;3]))
%! if (exist ('OCTAVE_VERSION', 'builtin'))
%!   assert (unlink([temp_file '.m']) == 0)
%! else
%!   delete ([temp_file '.m'])
%! end
%! % remove temp_path from load path
%! rmpath(temp_path);

%!test
%! % order of outputs is lexiographic
%! syms a A x y
%! f = y + 10*a + 100*x + 1000*A;
%! h = function_handle(f);
%! assert (h(1, 2, 3, 4) == 1000 + 20 + 300 + 4)

%!test
%! % https://github.com/cbm755/octsympy/issues/854
%! f = function_handle (x + 1i*sqrt (sym(3)));
%! assert (f (1), complex (1, sqrt (3)), -eps)

repo: octsympy


text:
function jac = p00_jac ( test, neqn, t, y )

%*****************************************************************************80
%
%% P00_JAC evaluates the jacobian for any problem.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer TEST, the problem number.
%
%    Input, integer NEQN, the number of equations.
%
%    Input, real T, Y(NEQN), the arguments of the jacobian.
%
%    Output, real JAC(NEQN,NEQN), the jacobian matrix.
%
  if ( test == 1 )
    jac = p01_jac ( neqn, t, y );
  elseif ( test == 2 )
    jac = p02_jac ( neqn, t, y );
  elseif ( test == 3 )
    jac = p03_jac ( neqn, t, y );
  elseif ( test == 4 )
    jac = p04_jac ( neqn, t, y );
  elseif ( test == 5 )
    jac = p05_jac ( neqn, t, y );
  elseif ( test == 6 )
    jac = p06_jac ( neqn, t, y );
  elseif ( test == 7 )
    jac = p07_jac ( neqn, t, y );
  elseif ( test == 8 )
    jac = p08_jac ( neqn, t, y );
  elseif ( test == 9 )
    jac = p09_jac ( neqn, t, y );
  elseif ( test == 10 )
    jac = p10_jac ( neqn, t, y );
  elseif ( test == 11 )
    jac = p11_jac ( neqn, t, y );
  elseif ( test == 12 )
    jac = p12_jac ( neqn, t, y );
  elseif ( test == 13 )
    jac = p13_jac ( neqn, t, y );
  elseif ( test == 14 )
    jac = p14_jac ( neqn, t, y );
  elseif ( test == 15 )
    jac = p15_jac ( neqn, t, y );
  elseif ( test == 16 )
    jac = p16_jac ( neqn, t, y );
  elseif ( test == 17 )
    jac = p17_jac ( neqn, t, y );
  elseif ( test == 18 )
    jac = p18_jac ( neqn, t, y );
  elseif ( test == 19 )
    jac = p19_jac ( neqn, t, y );
  elseif ( test == 20 )
    jac = p20_jac ( neqn, t, y );
  elseif ( test == 21 )
    jac = p21_jac ( neqn, t, y );
  elseif ( test == 22 )
    jac = p22_jac ( neqn, t, y );
  elseif ( test == 23 )
    jac = p23_jac ( neqn, t, y );
  elseif ( test == 24 )
    jac = p24_jac ( neqn, t, y );
  elseif ( test == 25 )
    jac = p25_jac ( neqn, t, y );
  elseif ( test == 26 )
    jac = p26_jac ( neqn, t, y );
  elseif ( test == 27 )
    jac = p27_jac ( neqn, t, y );
  elseif ( test == 28 )
    jac = p28_jac ( neqn, t, y );
  elseif ( test == 29 )
    jac = p29_jac ( neqn, t, y );
  elseif ( test == 30 )
    jac = p30_jac ( neqn, t, y );
  elseif ( test == 31 )
    jac = p31_jac ( neqn, t, y );
  elseif ( test == 32 )
    jac = p32_jac ( neqn, t, y );
  elseif ( test == 33 )
    jac = p33_jac ( neqn, t, y );
  elseif ( test == 34 )
    jac = p34_jac ( neqn, t, y );
  elseif ( test == 35 )
    jac = p35_jac ( neqn, t, y );
  elseif ( test == 36 )
    jac = p36_jac ( neqn, t, y );
  elseif ( test == 37 )
    jac = p37_jac ( neqn, t, y );
  elseif ( test == 38 )
    jac = p38_jac ( neqn, t, y );
  elseif ( test == 39 )
    jac = p39_jac ( neqn, t, y );
  elseif ( test == 40 )
    jac = p40_jac ( neqn, t, y );
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'P00_JAC - Fatal error!\n' );
    fprintf ( 1, '  Unrecognized problem number = %d\n', test );
    error ( 'P00_JAC - Fatal error!' );
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
clear;
%Note that I add original val to train
%and then redefine the train/test split.
%5000 val, 5000 test  https://cs.stanford.edu/people/karpathy/cvpr2015.pdf.
txt = fileread('./annotations/captions_val2014.json');
json = jsondecode(txt);  %jsondecode is not available on 2015b. I use Matlab2016b.

file_path_val = {json.images.file_name};
img_id_val = [json.images.id];

caption_val = {json.annotations.caption};
caption_img_id_val = [json.annotations.image_id];

%train
txt = fileread('./annotations/captions_train2014.json');
json = jsondecode(txt);  %jsondecode is not available on 2015b. I use Matlab2016b.

file_path = {json.images.file_name};
img_id = [json.images.id];

caption = {json.annotations.caption};
caption_img_id = [json.annotations.image_id];

% change full path
data = cat(2,...
    cellfun(@(x) sprintf('/home/zzd/Image-Text-Embedding/dataset/MSCOCO-prepare/image_256/train2014/%sjpg',x(1:end-3)), file_path,'UniformOutput',false),...
    cellfun(@(x) sprintf('/home/zzd/Image-Text-Embedding/dataset/MSCOCO-prepare/image_256/val2014/%sjpg',x(1:end-3)), file_path_val,'UniformOutput',false));
img_label = cat(2,img_id,img_id_val);
caption = cat(2,caption,caption_val);
caption_label = cat(2,caption_img_id,caption_img_id_val);

% final 5000 images as test
rng(1);
num = numel(data);
set = ones(1,num);
val_test_id = randperm(num,10000);
set(1,val_test_id) = 2; %val+test
test_id = val_test_id(randperm(10000,5000));
set(1,test_id) = 3; %test

%assign image label
new_label = zeros(1,numel(img_label));
new_label(set==1) = 1:sum(set==1);
train_img_label = img_label;
train_img_label(set~=1) = 0;
%assign text label
for i=1:numel(caption_label)
    now = caption_label(i);
    index = find(train_img_label==now);
    if(isempty(index))
        caption_label(i) = 0;
    else
        caption_label(i) = new_label(index);%update
    end
end

% dataset
imdb.images.set = set;
imdb.images.data = data;
imdb.images.label = new_label;
imdb.images.label2 = caption_label;
%resize_image; % resize image to 256, return mean.
imdb.rgbMean = [119.8557, 113.9346, 103.9336];
save('url_data.mat','imdb');  % only train data

caption_train = caption(caption_label~=0);
caption_dic = caption_train;

save('caption_train.mat','caption_dic');

save('caption.mat','caption');

caption_label = cat(2,caption_img_id,caption_img_id_val);
img_label = cat(2,img_id,img_id_val);

test_img_label = img_label(set==3);
%assign text label
parfor i=1:numel(caption_label)
    now = caption_label(i);
    index = find(test_img_label==now);
    if(isempty(index))
        caption_label(i) = 0;
    end
end
test_id = [];
test_id.txt_id = caption_label; % test left
test_label = img_label;
test_label(set~=3) = 0;
test_id.img_id = test_label;

save('test_id.mat','test_id');

author: layumi

repo: Image-Text-Embedding


text:
function x = cheby_diff1_null_right ( m, n )

%*****************************************************************************80
%
%% CHEBY_DIFF1_NULL_RIGHT returns a right null vector of the CHEBY_DIFF1 matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 March 2015
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the order of A.
%
%    Output, real X(N,1), the null vector.
%
  x = zeros ( n, 1 );

  if ( mod ( n, 2 ) == 1 )
    x(1:n,1) = 1.0;
  end

  return
end


text:
function userfuncdir = FindUserFuncDir(obj)
global cfg

cfg = InitConfig(cfg);

userfuncdir = {};
dirnameApp = getAppDir();

rootdirRegsitry = [dirnameApp, 'FuncRegistry/UserFunctions/'];
if ~ispathvalid(rootdirRegsitry)
    rootdirRegsitry = filesepStandard([dirnameApp, '../FuncRegistry/UserFunctions/']);
    if ~ispathvalid(rootdirRegsitry)
    	return;
	end
end
userfuncdir{1} = rootdirRegsitry;
dirs = dir([userfuncdir{1}, '*']);
for ii = 1:length(dirs)
    if ~dirs(ii).isdir
        continue
    elseif strcmp(dirs(ii).name, '..') || strcmp(dirs(ii).name, '.')
        continue
    elseif strcmp(dirs(ii).name, 'Archive')
        obj.config = struct('InclArchivedFunctions','');
        obj.config.InclArchivedFunctions = cfg.GetValue('Include Archived User Functions');
        if strcmp(obj.config.InclArchivedFunctions, 'Yes')
            userfuncdir{end+1} = fullpath([userfuncdir{1}, 'Archive/']); %#ok<*AGROW>
        end
    elseif strcmp(dirs(ii).name, 'Sim')
        obj.config = struct('InclArchivedFunctions','');
        obj.config.InclArchivedFunctions = cfg.GetValue('Include Archived User Functions');
        if strcmp(obj.config.InclArchivedFunctions, 'Yes')
            userfuncdir{end+1} = fullpath([userfuncdir{1}, 'Sim/']); %#ok<*AGROW>
        end
    else
        userfuncdir{end+1} = filesepStandard(fullpath([userfuncdir{1}, dirs(ii).name]));
    end
end

author: BUNPC


text:
%% ORB (Oriented FAST and Rotated BRIEF)
%
% In this demo, we will see the basics of ORB.
%
% Sources:
%
% * <https://docs.opencv.org/3.2.0/d1/d89/tutorial_py_orb.html>
%

%% Theory
%
% As an OpenCV enthusiast, the most important thing about the ORB is that it
% came from "OpenCV Labs". This algorithm was brought up by Ethan Rublee,
% Vincent Rabaud, Kurt Konolige and Gary R. Bradski in their paper
% *ORB: An efficient alternative to SIFT or SURF* in 2011. As the title says,
% it is a good alternative to SIFT and SURF in computation cost, matching
% performance and mainly the patents. Yes, SIFT and SURF are patented and you
% are supposed to pay them for its use. But ORB is not!
%
% ORB is basically a fusion of FAST keypoint detector and BRIEF descriptor
% with many modifications to enhance the performance. First it use FAST to
% find keypoints, then apply Harris corner measure to find top N points among
% them. It also use pyramid to produce multiscale-features. But one problem
% is that, FAST doesn't compute the orientation. So what about rotation
% invariance? Authors came up with following modification.
%
% It computes the intensity weighted centroid of the patch with located corner
% at center. The direction of the vector from this corner point to centroid
% gives the orientation. To improve the rotation invariance, moments are
% computed with x and y which should be in a circular region of radius $r$,
% where $r$ is the size of the patch.
%
% Now for descriptors, ORB use BRIEF descriptors. But we have already seen
% that BRIEF performs poorly with rotation. So what ORB does is to "steer"
% BRIEF according to the orientation of keypoints. For any feature set of
% $n$ binary tests at location $(x_i, y_i)$, define a $2 \times n$ matrix,
% $S$ which contains the coordinates of these pixels. Then using the
% orientation of patch, $\theta$, its rotation matrix is found and rotates
% the $S$ to get steered (rotated) version $S_\theta$.
%
% ORB discretize the angle to increments of $2 \pi /30$ (12 degrees), and
% construct a lookup table of precomputed BRIEF patterns. As long as the
% keypoint orientation $\theta$ is consistent across views, the correct set of
% points $S_\theta$ will be used to compute its descriptor.
%
% BRIEF has an important property that each bit feature has a large variance
% and a mean near 0.5. But once it is oriented along keypoint direction, it
% loses this property and become more distributed. High variance makes a
% feature more discriminative, since it responds differentially to inputs.
% Another desirable property is to have the tests uncorrelated, since then
% each test will contribute to the result. To resolve all these, ORB runs a
% greedy search among all possible binary tests to find the ones that have
% both high variance and means close to 0.5, as well as being uncorrelated.
% The result is called *rBRIEF*.
%
% For descriptor matching, multi-probe LSH which improves on the traditional
% LSH, is used. The paper says ORB is much faster than SURF and SIFT and ORB
% descriptor works better than SURF. ORB is a good choice in low-power devices
% for panorama stitching etc.
%

%% ORB in OpenCV
%
% As usual, we have to create an ORB object with the function |cv.ORB|, or
% using feature2d common interface. It has a number of optional parameters.
% Most useful ones are |MaxFeatures| which denotes maximum number of features
% to be retained (by default 500), |ScoreType| which denotes whether Harris
% score or FAST score to rank the features (by default, Harris score) etc.
% Another parameter, |WTA_K| decides number of points that produce each
% element of the oriented BRIEF descriptor. By default it is two, i.e selects
% two points at a time. In that case, for matching, |Hamming| distance is
% used. If |WTA_K| is 3 or 4, which takes 3 or 4 points to produce BRIEF
% descriptor, then matching distance is defined by |Hamming2|.
%

%%
% load source image
img = cv.imread(fullfile(mexopencv.root(),'test','butterfly.jpg'), ...
    'Grayscale',true);

%%
% detect keypoints
orb = cv.ORB();
keypoints = orb.detect(img);
whos keypoints

%%
% compute the descriptors
descriptors = orb.compute(img, keypoints);
whos descriptors

%%
% draw keypoints (only location, not size and orientation)
out = cv.drawKeypoints(img, keypoints, 'Color',[255 0 0]);
imshow(out), title('ORB')

%% Additional Resources
%
% * Ethan Rublee, Vincent Rabaud, Kurt Konolige, Gary R. Bradski.
%   "ORB: An efficient alternative to SIFT or SURF". ICCV 2011: 2564-2571.
%

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
% LTFAT - Frames
%
%  Peter L. Søndergaard, 2012 - 2018.
%
%  Creation of a frame object
%    FRAME             - Construct a new frame
%    FRAMEPAIR         - Construct a pair of frames
%    FRAMEDUAL         - The canonical dual frame
%    FRAMETIGHT        - The canonical tight frame
%    FRAMEACCEL        - Precompute arrays for faster application
%
%  Linear operators
%    FRANA             - Frame analysis
%    FRSYN             - Frame synthesis
%    FRSYNMATRIX       - Frame synthesis operator matrix
%    FRGRAMIAN	       - Frame Gramian operator
%    FRAMEOPERATOR     - Frame operator
%    FRAMEDIAG         - Diagonal of frame operator
%    FRANAITER         - Iterative perfect reconstruction analysis
%    FRSYNITER         - Iterative perfect reconstruction synthesis
%
%  Visualization
%    PLOTFRAME         - Plot frame coefficients
%    FRAMEGRAM         - Plot energy of signal in frame space
%
%  Information about a frame
%    FRAMEBOUNDS       - Frame bounds
%    FRAMERED          - Redundancy of frame
%    FRAMELENGTH       - Length of frame to expand signal
%    FRAMELENGTHCOEF   - Length of frame given a set of coefficients
%    FRAMECLENGTH      - Number of coefficients given input signal length
%    FRAMEVECTORNORMS  - Norms of the frame vectors
%
%  Coefficients conversions
%    FRAMECOEF2NATIVE  - Convert to native transform format
%    FRAMENATIVE2COEF  - Convert native to column format
%    FRAMECOEF2TF      - Convert to time-frequency plane layout
%    FRAMETF2COEF      - Convert TF-plane layout to native
%    FRAMECOEF2TFPLOT  - Convert to time-frequency plane layout for plotting
%
%  Non-linear analysis and synthesis
%    FRANABP           - Basis pursuit using the SALSA algorithm.
%    FRANAMP           - Orthogonal matching pursuit
%    FRANALASSO        - LASSO thresholding using Landweber iterations.
%    FRANAGROUPLASSO   - Group LASSO thresholding.
%    FRSYNABS          - Frame synthesis from magnitude of coefficients
%
%  For help, bug reports, suggestions etc. please visit
%  http://github.com/ltfat/ltfat/issues

author: ltfat

repo: ltfat

save_path: github-repos/MATLAB/ltfat-ltfat


text:
function clear_except(varargin)

% The following function clears the command workspace except the
% variables specified by the user.

error(nargchk(1,inf,nargin)); % Checks for zero input arguments

s = evalin('caller','who'); % Get contents of command workspace

cnt = 0; % Count that keeps track of no. of inputs
for ii = 1:1:nargin
    for jj = 1:1:length(s)
        if strcmp(varargin{ii},s{jj}) % Compare command workspace contents with the user specified variables.
            cnt = cnt + 1;
            index(cnt) = jj;
        end
    end
end

if cnt < nargin
        error('MATLAB:clear_except:Unidentified', ... % If any of the input arguments not present in workspace generate an error.
        'One of the variables not present in the workspace');
end

e = length(s)-cnt; % This variable ensures if somebody by mistake calls this function with
                   % all variables of workspace as input arguments then the variables should
                   % not be cleared.

t ={};
for k = 1:1:nargin % Create the cell array of the variables that need to be cleared.
    for ii = 1:1:index(k)-1;
        t(ii) = {[s{ii} ' ']};
    end
    for ii = index(k)+1:1:length(s)
        t(ii) = {[s{ii} ' ']};
    end
    s = t;
    clear t;
end
if e == 0 % If e is zero, it implies that all the variables present in the workspace
          % have been given as input arguments to the function and hence
          % all of them needs to be preserved.
    return;
else
    evalin('caller',['clear ',s{:}]); % Clear the variables that are not in the input argument list.
end

author: Sable

repo: mcbench-benchmarks


text:
classdef nme_load_acc < mp.nme_load_ac & mp.form_acc

%   MATPOWER
%   Copyright (c) 2019-2020, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

%     properties
%     end     %% properties

%     methods
%     end     %% methods
end         %% classdef

author: MATPOWER

repo: matpower

save_path: github-repos/MATLAB/MATPOWER-matpower


text:
function yp = p13_fun ( neqn, t, y )

%*****************************************************************************80
%
%% P13_FUN evaluates the function for problem P13.
%
%  Discussion:
%
%    10 equations.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Wayne Enright, John Pryce,
%    Algorithm 648,
%    ACM Transactions on Mathematical Software,
%    Volume 13, Number 1, pages 28-34.
%
%  Parameters:
%
%    Input, integer NEQN, the number of equations.
%
%    Input, real T, Y(NEQN), the arguments of the derivative
%    function.
%
%    Output, real YP(NEQN), the value of the derivative function.
%
  yp = zeros ( neqn, 1 );

  yp(1)        =             - 2.0 * y(1) + y(2);
  yp(2:neqn-1) = y(1:neqn-2) - 2.0 * y(2:neqn-1) + y(3:neqn);
  yp(neqn)     = y(neqn-1)   - 2.0 * y(neqn);

  return
end


text:
function sd=sdobs(obsr,obsb,f)

global glc

if f<=glc.NFREQ
    pi=obsr.L(f);
else
    pi=obsr.P(f-glc.NFREQ);
end

if f<=glc.NFREQ
    pj=obsb.L(f);
else
    pj=obsb.P(f-glc.NFREQ);
end

if pi==0||pj==0
    sd=0;
else
    sd=pi-pj;
end

return

repo: GINav


text:
function varargout = clipPoints3d(points, shape, varargin)
%CLIPPOINTS3D Clip a set of points by a box or other 3d shapes.
%
%   CLIP = clipPoints3d(POINTS, BOX);
%   Returns the set of points which are located inside of the box BOX.
%
%   [CLIP, IND] = clipPoints3d(POINTS, BOX);
%   Also returns the indices of clipped points.
%
%   ... = clipPoints3d(..., 'shape', 'sphere') Specify the shape.
%   Default is 'box'. But it is also possible to use 'sphere' or 'plane'.
%
%   ... = clipPoints3d(..., 'inside', false) returns the set of
%   points outside the shape instead of inside.
%
%   See also
%   points3d, boxes3d, spheres
%

% ------
% Author: David Legland, oqilipo
% E-mail: david.legland@inra.fr
% Created: 2008-10-13, using Matlab 7.4.0.287 (R2007a)
% Copyright 2008-2022 INRA - BIA Nantes - MIAJ Jouy-en-Josas

parser = inputParser;
validStrings = {'box', 'sphere', 'plane'};
addParameter(parser, 'shape', 'box', @(x) any(validatestring(x, validStrings)));
addParameter(parser, 'inside', true, @islogical);
parse(parser,varargin{:});

switch parser.Results.shape
    case 'box'
        LI = clipPointsByBox(points, shape);
    case 'plane'
        LI = clipPointsByPlane(points, shape);
    case 'sphere'
        LI = clipPointsBySphere(points, shape);
end

if parser.Results.inside
    % keep points inside the shape
    ind = find(LI);
else
    % keep points outside the shape
    ind = find(~LI);
end
points = points(ind, :);

% process output arguments
varargout{1} = points;
if nargout == 2
    varargout{2} = ind;
end

    function LI = clipPointsByBox(points, box)
        % get bounding box limits
        xmin = box(1);
        xmax = box(2);
        ymin = box(3);
        ymax = box(4);
        zmin = box(5);
        zmax = box(6);

        % compute indices of points inside visible area
        xOk = points(:,1) >= xmin & points(:,1) <= xmax;
        yOk = points(:,2) >= ymin & points(:,2) <= ymax;
        zOk = points(:,3) >= zmin & points(:,3) <= zmax;

        LI = xOk & yOk & zOk;
    end

    function LI = clipPointsByPlane(points, plane)
        % points inside and on the surface of the sphere
        LI = isBelowPlane(points, plane);
    end

    function LI = clipPointsBySphere(points, sphere)
        % points inside and on the surface of the sphere
        LI = distancePoints3d(points, sphere(1:3)) <= sphere(4);
    end

end

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function fx = p25_fun ( n, x )

%*****************************************************************************80
%
%% P25_FUN evaluates the integrand for problem 25.
%
%  Interval:
%
%    0 <= x <= 1.
%
%  Integrand:
%
%    ln ( abs ( x - 0.7 ) )
%
%  Exact Integral:
%
%    0.3 * ln ( 0.3 ) + 0.7 * ln ( 0.7 ) - 1
%
%  Approximate Integral (20 digits):
%
%    -1.6108643020548934630
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 November 2009
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Kendall Atkinson,
%    An Introduction to Numerical Analysis,
%    Prentice Hall, 1984, page 303.
%
%  Parameters:
%
%    Input, integer N, the number of evaluation points.
%
%    Input, real X(N), the evaluation points.
%
%    Output, real FX(N), the integrand values.
%
  fx = log ( abs ( x - 0.7 ) );

  return
end


text:
function [atlas, varargout] = handle_atlas_input(atlas, varargin)

% HANDLE_ATLAS_INPUT handles user input to specify volumetric atlases in some coordinate. It
% does two things: (1) call FT_READ_ATLAS to read the atlas from file, if it is specified as a
% string input, and (2) if the optional second data input argument is provided, and it has a
% coordsys and/or unit field, checks the coordinate systems and units of the atlas and the
% input against each other.
%
% This code was taken from ft_sourceplot to avoid duplication upon adding similar functionality
% to ft_sourceplot_interactive.

if ischar(atlas)
  % initialize the atlas
  [p, f, x] = fileparts(atlas);
  fprintf(['reading ', f, ' atlas coordinates and labels\n']);
  atlas = ft_read_atlas(atlas);
end

if nargin > 1
  data_hasunit = isfield(varargin{1}, 'unit');
  data_hascoordsys = isfield(varargin{1}, 'coordsys');

  % ensure that the atlas is formatted properly
  atlas = ft_checkdata(atlas, 'hasunit', data_hasunit, 'hascoordsys', data_hascoordsys);

  if data_hasunit
    % ensure that the units are consistent, convert if required
    atlas = ft_convert_units(atlas, varargin{1}.unit);

    % all data objects should have the same unit
    for i=2:numel(varargin)
      varargin{i} = ft_convert_units(varargin{i}, varargin{1}.unit);
    end
  end

  if data_hascoordsys
    % ensure that the coordinate systems are consistent, convert if required
    atlas = ft_convert_coordsys(atlas, varargin{1}.coordsys);

    % all data objects should have the same coordsys
    for i=2:numel(varargin)
      varargin{i} = ft_convert_coordsys(varargin{i}, varargin{1}.coordsys);
    end
  end
end

% the unit and coordsys might have changed
varargout = varargin;

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% KNOCK-OUT BARRIER OPTION PRICE COMPARISON (RUN SCRIPT)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Descritpion: Script to Compare Methods For Barrier Options Under Black Scholes Model
%              This script compares accuracy/CPU of the following methods,
%                   Monte Carlo
%                   PROJ
%
% Author:      Justin Kirkby
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[folder, name, ext] = fileparts(which( mfilename('fullpath')));
cd(folder);
addpath('../../PROJ/LEVY/RN_CHF')
addpath('../../PROJ/LEVY/Helper_Functions')

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%  Step 1) CHOOSE CONTRACT/GENERAL PARAMETERS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
S_0    = 100;   %Initial price
W      = 100;   %Strike            %NOTE: no error handling in place for extreme values of W (increase grid if strike falls outside)
r      = 0.05;  %Interest rate
q      = 0.02;  %dividend yield
T      = 1;     %Time (in years)
call   = 1;     %For call use 1 (else, its a put)
down   = 1;     %down-out or up-out (down=1 => down-and-out)
H      = 90;    %barrier (Knock-Out)
M      = 52;    %number of discrete monitoring points
rebate = 0;     % rebate paid immediately upon passing the barrier (knocking-out)

sigma = 0.15;  % volatility of diffusion

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
model = 1; params = {}; params.sigmaBSM = sigma;
modelInput = getModelInput(model, T/M, r, q, params);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%  Reference Price (Using PROJ)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
addpath('../../PROJ/LEVY/Barrier_Options')
L1_ref = 20; N_ref = 2^17;
alpha_ref = getTruncationAlpha(T, L1_ref, modelInput, model);
price_ref = PROJ_Barrier(N_ref, alpha_ref, call, down, S_0, W, H, M, r, q, modelInput.rnCHF, T, rebate);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%  PROJ Method
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
N = 2^12;    % grid roughly centered on [c1 - alph, c1 + alph]
L1 = 10;
alpha = getTruncationAlpha(T, L1, modelInput, model);

tic
price_PROJ = PROJ_Barrier(N, alpha, call, down, S_0, W, H, M, r, q, modelInput.rnCHF, T, rebate);
time_PROJ = toc;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%  Monte Carlo Pricer (Exact Sim, Multi-Step)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NOTE: Variance reduction techniques should be used in practice
addpath('../../Monte_Carlo/')
addpath('../../Monte_Carlo/Barrier')
N_sim = 5*10^5;  % number of paths
mult = 3;   % multiplier for simulation (see below) to reduce bias

tic
M_mult = M*mult;  %time partitioning to reduce bias
Spath = Simulate_Jump_Diffusion_func( N_sim, M_mult + 1, T, S_0, r, q, sigma);

[price_MC, stdErr] = Price_MC_Barrier_Strikes_func(Spath, call, down, H, W, M, mult, rebate, r, T);

price_MC_L = price_MC - 2*stdErr; price_MC_U = price_MC + 2*stdErr;
time_MC = toc;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% COMPARE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('\n---------------------------------------------\n')
fprintf('Method      |    Price    |    Err   |  CPU \n')
fprintf('---------------------------------------------\n')
fprintf('Reference   | %.8f  |          |       \n', price_ref)
fprintf('---------------------------------------------\n')
fprintf('PROJ        | %.8f  | %.2e | %.4f \n', price_PROJ, abs(price_ref-price_PROJ), time_PROJ)
fprintf('---------------------------------------------\n')
fprintf('MC-Exact    |[%.3f,%.3f]| %.2e | %.4f \n', price_MC_L, price_MC_U, abs(price_ref-price_MC), time_MC)
fprintf('---------------------------------------------\n')


text:
function nMS=grMinAbsVerSet(E,d)
% Function nMS=grMinAbsVerSet(E,d) solve the minimal absorbant set problem
%   for the graph vertexes.
% Input parameters:
%   E(m,2) - the edges of graph;
%     1st and 2nd elements of each row is numbers of vertexes;
%     m - number of edges.
%   d(n) (optional) - the weights of vertexes,
%     n - number of vertexes.
%     If we have only 1st parameter E, then all d=1.
% Output parameter:
%   nMS - the list of the numbers of vertexes included
%     in the minimal (weighted) absorbant set of vertexes.
% Uses the reduction to integer LP-problem.
% Required the Optimization Toolbox v.3.0.1 or over.
% Author: Sergiy Iglin
% e-mail: siglin@yandex.ru
% personal page: http://iglin.exponenta.ru

% ============= Input data validation ==================
if nargin<1,
  error('There are no input data!')
end
[m,n,E] = grValidation(E); % E data validation
if nargin<2, % we may only 1st parameter
  d=ones(n,1); % all weights =1
else
  d=d(:); % reshape to vector-column
  if length(d)<n, % the poor length
    error('The length of the vector d is poor!')
  else
    d=d(1:n); % First n numbers
  end
end

% ============= Parameters of integer LP problem ==========
A=eye(n);
A((E(:,2)-1)*n+E(:,1))=1; % adjacency matrix + main diagonal
A=double(A+A'>0); % symmetrical
options=optimset('bintprog'); % the default options
options.Display='off'; % we change the output

% ============= We solve the MILP problem ==========
xmin=bintprog(d,-A,-ones(n,1),[],[],[],options);
nMS=find(round(xmin)); % the answer - numbers of vertexes
return

author: HuangCongQing


text:
function moc_display ( a, b, n, f )

%*****************************************************************************80
%
%% MOC_DISPLAY plots data related to the modulus of continuity of a function.
%
%  Discussion:
%
%    Three graphs will be shown:
%    1) A plot of F(X) from A to B.
%    2) A plot of the function MC1(X) for 0 <= T <= B-A, where
%       MC1(T) = max | F(X+DX) - F(X) |, for DX = T, X and X+DX in [A,B].
%    3) A plot of the function MC(X) for 0 <= T <= B-A, where
%       MC(T) = max | F(X+DX) - F(X) |, for DX <= T, X and X+DX in [A,B].
%
%    The functions MC1 and MC are estimated by evaluating F(X) at N
%    equally spaced points in [A,B].
%
%    MC(T) is known as the "modulus of continuity" for F(X);
%    MC1(T) has no special name.
%
%    The exact function MC(T) should be a monotone increasing function.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 October 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real A, B, the left and right endpoints of the interval.
%
%    Input, integer N, the number of equally spaced sample points used to
%    estimate MC1(T) and MC(T).
%
%    Input, function F(x), a handle to the function whose modulus of
%    continuity function is to be estimated and plotted.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'MOC_DISPLAY:\n' );
  fprintf ( 1, '  Estimate and plot the Modulus of Continuity function\n' );
  fprintf ( 1, '  over an interval [A,B], using N sample points, and a\n' );
  fprintf ( 1, '  user-specified function F(X).\n' );

  if ( nargin < 1 )
    a = 0.0;
  end

  if ( nargin < 2 )
    b = a + 1.0;
  end

  if ( nargin < 3 )
    n = 501;
  end
%
%  Compute discrete data for given N.
%
  x = linspace ( a, b, n );
  dx = linspace ( 0, b - a, n );
  fx = f ( x );

  mc1 = zeros ( n, 1 );
  for i = 0 : n - 1
    mc1(i+1) = max ( abs ( fx(1+i:n) - fx(1:n-i) ) );
  end

  mc = zeros ( n, 1 );
  for i = 1 : n - 1
    mc(i+1) = max ( mc(i), mc1(i+1) );
  end
%
%  Display the plots.
%
  subplot ( 3, 1, 1 )
  n_fine = 1000;
  x_fine = linspace ( a, b, n_fine );
  fx_fine = f ( x_fine );
  plot ( x_fine, fx_fine, 'LineWidth', 2 )
  grid on
  title ( 'F(X)' );

  subplot ( 3, 1, 2 )
  plot ( dx, mc1, 'LineWidth', 2 );
  grid on
  title ( sprintf ( 'MC1(DX): max |F(X+DX)-F(X)|, N = %d', n ) )

  subplot ( 3, 1, 3 )
  plot ( dx, mc, 'LineWidth', 2 );
  grid on
  title ( sprintf ( 'MC(T): max |F(X+DX)-F(X)| for DX <= T, N = %d', n ) )

  return
end


text:
function [xx, BestMetric] = SoftVitDec(G, y, ZeroTail);

%
% SoftVitDec			This function performs Viterbi Decoding for Soft Decision Inputs
%
% 						Inputs: G = [g1; g2; ...; gN] - matrix of generation polynomials
%                                    y - encoded sequence
%                                    ZeroTail - 1/0 - defines if contains zero tail
%
% 						Outputs: xx - recovered encoded bits
%                                       BestMetric - final best metric
%
%           Rule =  MAXIMAL METRIC WINS (Likelihood function)
%

L = size(G, 1);     % --- num of output chips
K= size(G, 2);      % --- length of generation polinom
N = 2^(K-1);         % --- number of states
T = length(y)/L;                % --- maximum trellis depth

%------- Output Generation Matrix Definition (contains all possible state transactions)-------------
OutMtrx = zeros(N, 2*L);
for s = 1:N
    in0 = ones(L, 1)*[0, (dec2bin((s-1), (K-1))-'0')];
    in1 = ones(L, 1)*[1, (dec2bin((s-1), (K-1))-'0')];

    out0 = mod(sum((G.*in0)'), 2);
    out1 = mod(sum((G.*in1)'), 2);

    OutMtrx(s, :) = [out0, out1];
end
OutMtrx = sign(OutMtrx-1/2);

%---------------------------------------------------------------------------------------------
%------------------------------------ Trellis SECTION ----------------------------------
%---------------------------------------------------------------------------------------------
%------- Path Mertrix Initialization -------------
PathMet = [100; zeros((N-1), 1)];       % Initial State = 100 (better initial conditions)
PathMetTemp = PathMet(:,1);

Trellis = zeros(N, T);
Trellis(:,1) = [0 : (N-1)]';

%------------------------ MAIN Trellis Calculation Loop ---------------------------
y = reshape(y, L, length(y)/L);
for t = 1:T

    yy = y(:, t);
    for s = 0:N/2-1
        [B0 ind0] = max(  PathMet(1+[2*s, 2*s+1]) + [OutMtrx(1+2*s, 0+[1:L]) * yy; OutMtrx(1+(2*s+1), 0+[1:L])*yy] );
        [B1 ind1] = max(  PathMet(1+[2*s, 2*s+1]) + [OutMtrx(1+2*s, L+[1:L]) * yy; OutMtrx(1+(2*s+1), L+[1:L]) * yy] );

        PathMetTemp(1+[s, s+N/2]) =  [B0; B1];
        Trellis(1+[s, s+N/2], t+1) = [2*s+(ind0-1); 2*s + (ind1-1)];
    end
   PathMet = PathMetTemp;

end

%---------------------------------------------------------------------------------------------
%---------------------------------- Trace Back Section -----------------------------
%---------------------------------------------------------------------------------------------
%------- Find Best Path Mertric -------------
xx = zeros(T, 1);
if (ZeroTail)
    BestInd = 1;
else
    [Mycop, BestInd]  = max(PathMet);
end

BestMetric = PathMet(BestInd);
xx(T) = floor((BestInd-1)/(N/2));

%------------------------ MAIN Trace Back Loop ---------------------------
NextState = Trellis(BestInd, (T+1));
for t=T:-1:2
    xx(t-1) = floor(NextState/(N/2));
    NextState = Trellis( (NextState+1), t);
end

if (ZeroTail)
    xx = xx(1:end-K+1);
end


text:
function fullBconv()
    global config mem;
    current_layer = config.misc.current_layer;
    mem.grads{current_layer+1} = mem.deltas{current_layer+1} * mem.activations{current_layer}';
    mem.grads{current_layer+1+config.layer_num} = sum(mem.deltas{current_layer+1}, 2);
end

author: jimmy-ren


text:
% *** This function is part of ERPLAB Toolbox ***
% Author: Javier Lopez-Calderon
% Center for Mind and Brain
% University of California, Davis,
% Davis, CA
% 2009

binArray       = plotset.pfrequ.binArray;
plotallbin     = plotset.pfrequ.plotallbin;
chanArray      = plotset.pfrequ.chanArray;
plotallch      = plotset.pfrequ.plotallch;
chanArray_MGFP = plotset.pfrequ.chanArray_MGFP;
blcorr         = plotset.pfrequ.blcorr;
xxscale        = plotset.pfrequ.xscale;
yyscale        = plotset.pfrequ.yscale;
linewidth      = plotset.pfrequ.linewidth;
isiy           = plotset.pfrequ.isiy;
fschan         = plotset.pfrequ.fschan;
fslege         = plotset.pfrequ.fslege;
fsaxtick       = plotset.pfrequ.fsaxtick;
pstyle         = plotset.pfrequ.pstyle;
errorstd       = plotset.pfrequ.errorstd;
stdalpha       = plotset.pfrequ.stdalpha;
isMGFP         = plotset.pfrequ.isMGFP;
%
% if plotallch
%         newnch = numel(chanArray);
%         if isMGFP
%                 newnch = newnch + 1;
%         end
%         dsqr   = round(sqrt(newnch));
%         sqrdif = dsqr^2 - newnch;
%         if sqrdif<0
%                 pbox(1) = dsqr + 1;
%         else
%                 pbox(1) = dsqr;
%         end
%         pbox(2) = dsqr;
% else
        pbox   = plotset.pfrequ.pbox;
% end
counterwin     = plotset.pfrequ.counterwin;
holdch         = plotset.pfrequ.holdch;
yauto          = plotset.pfrequ.yauto;
yautoticks     = plotset.pfrequ.yautoticks;
xautoticks     = plotset.pfrequ.xautoticks;
binleg         = plotset.pfrequ.binleg;
chanleg        = plotset.pfrequ.chanleg;

ismaxim        = plotset.pfrequ.ismaxim;
%istopo         = plotset.pfrequ.istopo;
axsize         = plotset.pfrequ.axsize;
minorticks     = plotset.pfrequ.minorticks;
linespeci      = plotset.pfrequ.linespec;
legepos        = plotset.pfrequ.legepos;
posgui         = plotset.pfrequ.posgui;
posminigui     = plotset.pfrequ.posminigui;
posfig         = plotset.pfrequ.posfig;
ibckground     = plotset.pfrequ.ibckground;

author: ucdavis

repo: erplab

save_path: github-repos/MATLAB/ucdavis-erplab


text:
%FILLPOLY  Fills the area bounded by one or more polygons
%
%     img = cv.fillPoly(img, pts)
%     [...] = cv.fillPoly(..., 'OptionName', optionValue, ...)
%
% ## Input
% * __img__ Image.
% * __pts__ Array of polygons where each polygon is represented as an array
%   of points. A cell array of cell arrays of 2-element vectors, in the form:
%   `{{[x,y], [x,y], ...}, ...}`, or a cell array of Nx2 matrices.
%
% ## Output
% * __img__ Output image, same size and type as input `img`.
%
% ## Options
% * __Color__ 3-element floating-point vector specifying polygon color.
%   default zeros
% * __LineType__ Type of the polygon boundaries. One of:
%   * __4__ 4-connected line
%   * __8__ 8-connected line (default)
%   * __AA__ anti-aliased line
% * __Shift__ Number of fractional bits in the vertex coordinates. default 0
% * __Offset__ Optional offset of all points of the contours. default `[0,0]`
%
% The function cv.fillPoly fills an area bounded by several polygonal
% contours. The function can fill complex areas, for example, areas with
% holes, contours with self-intersections (some of thier parts), and so forth.
%
% See also: cv.line, cv.fillConvexPoly, roipoly, poly2mask
%


text:
function [batches, batch_padding] = rcnn_extract_regions(im, boxes, rcnn_model)
% [batches, batch_padding] = rcnn_extract_regions(im, boxes, rcnn_model)
%   Extract image regions and preprocess them for use in Caffe.
%   Output is a cell array of batches.
%   Each batch is a 4-D tensor formatted for input into Caffe:
%     - BGR channel order
%     - single precision
%     - mean subtracted
%     - dimensions from fastest to slowest: width, height, channel, batch_index
%
%   im is an image in RGB order as returned by imread
%   boxes are in [x1 y1 x2 y2] format with one box per row

% AUTORIGHTS
% ---------------------------------------------------------
% Copyright (c) 2014, Ross Girshick
%
% This file is part of the R-CNN code and is available
% under the terms of the Simplified BSD License provided in
% LICENSE. Please retain this notice and LICENSE if you use
% this file (or any portion of it) in your project.
% ---------------------------------------------------------

% convert image to BGR and single
im = single(im(:,:,[3 2 1]));
num_boxes = size(boxes, 1);
batch_size = rcnn_model.cnn.batch_size;
num_batches = ceil(num_boxes / batch_size);
batch_padding = batch_size - mod(num_boxes, batch_size);
if batch_padding == batch_size
  batch_padding = 0;
end

crop_mode = rcnn_model.detectors.crop_mode;
image_mean = rcnn_model.cnn.image_mean;
crop_size = size(image_mean,1);
crop_padding = rcnn_model.detectors.crop_padding;

batches = cell(num_batches, 1);
%for batch = 1:num_batches
parfor batch = 1:num_batches
  batch_start = (batch-1)*batch_size+1;
  batch_end = min(num_boxes, batch_start+batch_size-1);

  ims = zeros(crop_size, crop_size, 3, batch_size, 'single');
  for j = batch_start:batch_end
    bbox = boxes(j,:);
    crop = rcnn_im_crop(im, bbox, crop_mode, crop_size, ...
        crop_padding, image_mean);
    % swap dims 1 and 2 to make width the fastest dimension (for caffe)
    ims(:,:,:,j-batch_start+1) = permute(crop, [2 1 3]);
  end

  batches{batch} = ims;
end

author: rbgirshick

repo: rcnn

save_path: github-repos/MATLAB/rbgirshick-rcnn


text:
function nonlin_param_mod_brain(ons, modulator, image_names, SETUP, varargin)
% Nonlinear fits with a parametric modulator on a set of brain images
%
% :Usage:
% ::
%
%     nonlin_param_mod_brain(X, image_names, SETUP, [SETUPional inputs])
%
% :Inputs:
%
%   **ons:**
%        onsets for each condition; one cell per
%        condition, one col. vector per series of onsets
%
%   **modulator:**
%        modulator values for each condition; same
%        format as above
%
%   **image_names:**
%        outcome variable; Images (volume names) for each subject, in
%        string matrix (list of image names); 3-D for now!
%
% :SETUP.(fields):
%
%   **.mask:**
%        name of mask image
%
%   **.preprocX:**
%        flag for whether to HP filter X data
%
%   **.preprocY:**
%        flag for whether to HP filter Y data
%
%   **'nopreproc':**
%        Turn off preproc
%
%   **.TR:**
%        repetition time of volume (image) acquisition
%
%   **.HPlength:**
%        high-pass filter length, in s
%
%   **.scans_per_session:**
%        vector of # volumes in each run, e.g., [128 128 128 128 128]
%
%   **.dummyscans:**
%        indices of images in each run that will be modeled
%        with separate dummy variables
%
%   **.startslice:**
%        starting slice number (to resume analysis)
%
% SETUPional inputs:
% Any of the SETUPions in mediation.m
%
% Also: 'nopreproc' to skip preprocessing (i.e., for trial-level inputs)
%
% ..
%    Tor Wager, May 2008
% ..

    % ..
    %    Set up preprocessing
    %    To skip, enter 'nopreproc' as var. arg.
    % ..

    [preprochandle, SETUP] = filter_setup(SETUP, varargin{:});

    % SETUPional: preproc Y?  Should do mostly only if not brain
    % Should not do if using trial-level estimates

    N = size(image_names, 1);  % number of subjects; one cell per subject

    % do high-pass filter preprocessing on X, if specified
    if SETUP.preprocX, for i = 1:N, X{i} = preprochandle(X{i}); end, end

    if ~SETUP.preprocY
        preprochandle = [];

    else
        tmp = cell(1, N);
        for i = 1:N, tmp{i} = preprochandle; end
        preprochandle = tmp;
    end

    tr = SETUP.TR;

    % ---------------------------------------------------------------------
    % Set up mask
    % ---------------------------------------------------------------------
    SETUP.mask_unresampled = SETUP.mask;
    disp('Writing resampled mask.img in current directory.');

    scn_map_image(SETUP.mask, image_names(1, :), 'write', 'mask.img');
    SETUP.mask = fullfile(pwd, 'mask.img');

    % ---------------------------------------------------------------------
    % Set up analysis
    % ---------------------------------------------------------------------

    % THIS stuff is the same for each voxel
    % --------------------------------------
    modulator_centered = modulator - nanmean(modulator);
    xvals = (1:N)';

    % This runs the whole thing given a data vector (y)
    fhandle = @(y) nonlin_param_modulator(y, ons, modulator_centered, tr, xvals);

    SETUP.names = {'amplitude_mean.img' 'amplitude_by_modulator.img' 'duration_mean.img' 'duration_by_modulator.img' ...
    'intercept.img' 'auc_mean_trial.img' ...
    'auc_by_modulator.img' 'variance.img' };

    SETUP.preprochandle = preprochandle;
    SETUP.fhandle = fhandle;

    SETUP.data.descrip = 'Data after any preprocessing specified (for X and Y)';
    SETUP.data.ons = ons;
    SETUP.data.modulator = modulator;
    SETUP.data.modulator_centered = modulator_centered;
    SETUP.data.image_names = image_names;
    save nonlin_param_mod_SETUP SETUP

    % ---------------------------------------------------------------------
    % Run preprocessing and analysis
    % ---------------------------------------------------------------------
    if ~isfield(SETUP, 'startslice') || isempty(SETUP.startslice), SETUP.startslice = 1; end

    [a, b, c, d, e, f, g, h] = image_eval_function(image_names, fhandle, 'mask', SETUP.mask, 'preprochandle', preprochandle, 'outnames', SETUP.names, 'start', SETUP.startslice);

end    % End Main Function

% Set up preprocessing
function [preprochandle, SETUP] = filter_setup(SETUP, varargin)

    preprochandle = [];
    wh_elim = [];
    hpflag = 1;  % only does it if requested, though

    for i = 1:length(varargin)
        if ischar(varargin{i})
            switch varargin{i}
                % reserved keywords
                case 'custompreproc'
                    preprochandle = varargin{i + 1};  % e.g., 'custompreproc', @(data) scale(data) for z=scores;

                    hpflag = 0;
                    SETUP.TR = NaN;
                    SETUP.HPlength = [];
                    SETUP.dummyscans = [];
                    wh_elim = i;

                case {'nopreproc'}
                    hpflag = 0;
                    SETUP.preprocY = 0; SETUP.preprocX = 0;
                    if ~isfield(SETUP, 'TR') || isempty(SETUP.TR), SETUP.TR = NaN; end
                    SETUP.HPlength = [];
                    SETUP.dummyscans = [];
                    wh_elim = i;

                    % We need to allow mediation SETUPions here, so eliminate this from list and do not error check here.
                    %otherwise, warning(['Unknown input string SETUPion:' varargin{i}]);
            end
        end
    end

    varargin(wh_elim) = [];

    N = fieldnames(SETUP);
    for i = 1:length(N)
        if ~isfield(SETUP, N{i}) || isempty(SETUP.(N{i}))
            switch N{i}
                case {'TR', 'mask', 'scans_per_session', 'preprocY'}
                    error(['Enter SETUP.' N{i}]);

                case 'HPlength'
                    SETUP.(N{i}) = [];

                case 'dummyscans'
                    SETUP.(N{i}) = 1:2;

                otherwise
                    disp('Warning! Unrecognized field in SETUPions structure SETUP.');
            end
        end
    end

    SETUP.preproc_any = SETUP.preprocX || SETUP.preprocY

    if ~isfield(SETUP, 'TR') || isempty(SETUP.TR) || isnan(SETUP.TR)
        error('SETUP.TR must be entered.');
    end

    if SETUP.preproc_any && hpflag

        error('THIS CODE IS NOT SET UP TO PREPROCESS YET.');

        [tmp, I, S] = hpfilter(X(:,1), SETUP.TR, SETUP.HPlength, SETUP.scans_per_session, SETUP.dummyscans); % creates intercept and smoothing matrices

        preprochandle = @(Y) hpfilter(Y,  [], S, SETUP.scans_per_session, I);  % function handle with embedded fixed inputs

    end

end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function result = emap(func, x)
%An alias for cellfun, which applies function func to all elements
%of cell array x, but with UniformOutput set to false
if nargin<2
  error('Not enough arguments to cellfunc2\n');
end
result = cellfun(func, x, 'UniformOutput', false);

author: quantombone

repo: exemplarsvm


text:
function [L,Lc,Lli] = fromFramePlucker(C,Li)

% FROMFRAMEPLUCKER  Transform plucker line from a given frame.
%   L = FROMFRAMEPLUCKER(C,Li) expresses in global frame the line Li
%   originally expressed in frame C=(t,q).
%
%   The formula for transformation is
%
%       L = [ R        [t]_x*R ]
%           [ zeros(3)       R ] * Li
%
%   where
%       R    = q2R(q)
%      [t]_x = hat(t).
%
%   [L,Lc,Lli] = FROMFRAMEPLUCKER(...) returns the Jacobians wrt C
%   and Li.
%
%   See also TOFRAMEPLUCKER, TXP, HAT, CROSS, Q2R.

%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.

ai = Li(1:3);
bi = Li(4:6);

t = C.t;
q = C.q;

if nargout == 1

    R = C.R;

    b = R*bi;
    a = R*ai + hat(t)*b;

    L = [a;b];

else

    [b,Bq,Bbi]      = Rp(q,bi);
    [txb,TXBt,TXBb] = crossJ(t,b);
    [Ra,RAq,RAai]   = Rp(q,ai);

    a   = Ra + txb;

    At  = TXBt;
    Aq  = RAq + TXBb*Bq;
    Aai = RAai;
    Abi = TXBb*Bbi;

    L   = [a;b];

    Lc  = [At Aq;zeros(3) Bq];
    Lli = [Aai Abi;zeros(3) Bbi];

end

return

%% test jacobians

syms a b c d x y z real
syms L1 L2 L3 L4 L5 L6 real

q   = [a;b;c;d];
t   = [x;y;z];
C.x = [t;q];
C   = updateFrame(C);
Li  = [L1;L2;L3;L4;L5;L6];

[L,Lc,Lli] = fromFramePlucker(C,Li);

simplify(Lc  - jacobian(L,C.x))
simplify(Lli - jacobian(L,Li))

%% test inv. transform
Li2 = toFramePlucker(C,L);

EL = simplify(Li - Li2);

simplify(subs(EL,d,sqrt(1-a^2-b^2-c^2)))

% ========== 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 linpack_d_test11 ( )

%*****************************************************************************80
%
%% TEST11 tests DGEFA and DGESL.
%
%  Discussion:
%
%    In this example, we solve a relatively large linear system.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 June 2009
%
%  Author:
%
%    John Burkardt
%
  n = 100;
  lda = n;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST11\n' );
  fprintf ( 1, '  For a general matrix,\n' );
  fprintf ( 1, '  DGEFA computes the LU factors;\n' );
  fprintf ( 1, '  DGESL solves a factored linear system;\n' );
  fprintf ( 1, '  The matrix size is N = %d\n', n );
%
%  Assign values to the matrix A and the right hand side B.
%
%  The problem is just an enlarged version of the
%  problem for N = 5, which is:
%
%  Matrix A is ( n -1 -1 -1 -1)    Right hand side B is  (1)
%              (-1  n -1 -1 -1)                          (1)
%              (-1 -1  n -1 -1)                          (1)
%              (-1 -1 -1  n -1)                          (1)
%              (-1 -1 -1 -1  n)                          (1)
%
%  Solution is   (1)
%                (1)
%                (1)
%                (1)
%                (1)
%
  b(1:n) = 1.0;

  a(1:n,1:n) = -1.0;
  for i = 1 : n
    a(i,i) = n;
  end
%
%  Factor the matrix.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Factor the matrix\n' );

  [ a, ipvt, info ] = dgefa ( a, lda, n );

  if ( info ~= 0 )
    fprintf ( 1, '  DGEFA returned an error flag INFO = %d\n', info );
    return
  end
%
%  Solve the linear system.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Solve the linear system.\n' );

  job = 0;
  b = dgesl ( a, lda, n, ipvt, b, job );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  The first and last five entries of the solution:\n' );
  fprintf ( 1, '  (All of them should be 1.)\n' );
  fprintf ( 1, '\n' );
  for i = 1 : n
    if ( i <= 5 | n-5 < i )
      fprintf ( 1, '  %6d  %14f\n', i, b(i) );
    end
    if ( i == 5 )
      fprintf ( 1, '  ......  ..............\n' );
    end
  end

  return
end


text:
function Y = log(X)
    %  Symbolic matrix element-wise natural logarithm.

    % Convert inputs to SymExpression
    % X = SymExpression(X);

    % construct the operation string
    sstr = ['Log[' X.s ']'];

    % create a new object with the evaluated string
    Y = SymExpression(sstr);
end

author: ayonga

repo: frost-dev

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


text:
function x = line_adj_null_left ( m, n )

%*****************************************************************************80
%
%% LINE_ADJ_NULL_LEFT returns a left null vector of the LINE_ADJ matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 March 2015
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the order of the matrix.
%
%    Output, real X(M), a null vector
%
  if ( mod ( m, 2 ) == 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'LINE_ADJ_NULL_LEFT - Fatal error!\n' );
    fprintf ( 1, '  For M even, there is no null vector.\n' );
    error ( 'LINE_ADJ_NULL_LEFT - Fatal error!' );
  end

  x = zeros ( m, 1 );

  x(1:4:m,1) =  1.0;
  x(3:4:m,1) = -1.0;

  return
end

author: johannesgerer


text:
function [x,state] = struct_triu(z,task)
%STRUCT_TRIU Upper triangular matrix.
%   [x,state] = struct_triu(z) generates x as a lower triangular matrix by
%   using the vector z to fill the matrix column by column. For a matrix x
%   of order n, the vector z should have length n*(n+1)/2. The structure
%   state stores information which is reused in computing the right and
%   left Jacobian-vector products.
%
%   struct_triu(z,task) computes the right or left Jacobian-vector
%   product of this transformation, depending on the structure task. Use
%   the structure state and add the field 'r' of the same shape as z or the
%   field 'l' of the same shape as x to obtain the structure task for
%   computing the right and left Jacobian-vector products
%
%      (dF(:)/dz(:).')*task.r(:) and
%      (dF(:)/dz(:).')'*task.l(:) + conj((dF(:)/dconj(z(:)).')'*task.l(:)),
%
%   respectively. Here, F(z) represents this transormation, (:) signifies
%   vectorization and the derivative w.r.t. z (conj(z)) is a partial
%   derivative which treats conj(z) (z) as constant. The output has the
%   same shape as x or z for the right and left Jacobian-vector products,
%   respectively.
%
%   See also struct_band, struct_diag, struct_tridiag, struct_tril.

%   Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)
%            Marc Van Barel (Marc.VanBarel@cs.kuleuven.be)
%            Lieven De Lathauwer (Lieven.DeLathauwer@kuleuven-kulak.be)
%
%   References:
%   [1] L. Sorber, M. Van Barel, L. De Lathauwer, "Structured data fusion,"
%       ESAT-SISTA Internal Report 13-177, KU Leuven, 2013.

if nargin < 2, task = []; end
n = 0.5*(-1+sqrt(1+8*length(z)));
[x,state] = struct_band(z,task,[n n],[0 n-1]);

end

author: andrewssobral

repo: lrslibrary


text:
function [model, cost_curve] = badacostWithTreesTrain( X0, X1, L1, varargin )
%--------------------------------------------------------------------------
% function [model, cost_curve] = badacostWithTreesTrain( X0, X1, L1, varargin)
%
% This function performs Multiclass Bosting ADApted for Costs (badacost)
% algorithm with trees as weak learner.
%
% INPUTS
%  X0         - [N0xF] negative feature vectors
%  X1         - [N1xF] positive feature vectors
%  L1         - [N1x1] positive subclasses labels  (in [1, H] where H is the #subclasses)
%  pBoost     - additional params (struct or name/value pairs)
%   .nWeak      - [128] number of trees to learn
%   .shrinkage  - [0.1] learning rate (multiplicative factor for weak learner weights).
%   .resampling - [0.1] sampling proportion of data for weak learner training.
%   .Cost       - [onesH+1,H+1)-eye(H+1))] C(i, j) is the cost of classifing in j whereas the
%                 real label is i.
%   .stopAtNegWeight [1] Stop iterating badacost when a Weak Learner gets a negative weight
%   .maxDepth   - [] Max depth levels of the decision trees.
%   .quantized  - [0]
%   .use_rus    - [0] Use Random Under Sampling.
%   .verbose    - [0] if true print status information
%
% OUTPUTS
%  model      - learned boosted tree classifier w the following fields
%   .fids       - [K x nWeak] feature ids for each node
%   .thrs       - [K x nWeak] threshold corresponding to each fid
%   .child      - [K x nWeak] index of child for each node (1-indexed)
%   .hs         - [K x nWeak] log ratio (.5*log(p/(1-p)) at each node
%   .weights    - [K x nWeak] total sample weight at each node
%   .depth      - [K x nWeak] depth of each node
%   .errs       - [1 x nWeak] error for each tree (for debugging)
%   .losses     - [1 x nWeak] loss after every iteration (for debugging)
%   .treeDepth  - depth of all leaf nodes (or 0 if leaf depth varies)
%

%
% Author: Jose M. Buenaposada

x = [X0; X1];

% We make 1 the negative class label and add 1 to the rest of labels
y = [ones(size(X0,1), 1); L1(:) + 1];
num_classes = length(unique(y));

% get additional parameters
Cost = ones(num_classes, num_classes) - diag(ones(num_classes, 1));
dfs={ 'nWeak',128, 'shrinkage', 0.1, 'resampling', 0.5, 'Cost', Cost, 'stopAtNegWeight', 1, ...
      'fracFtrs', 1, 'minDepth', [], 'maxDepth', [], 'quantized', 0, 'variable_depth', 0, ...
      'use_rus', 0, ...
      'verbose', 0};
[nWeak,shrinkage,resampling,Cost,stopAtNegWeight,fracFtrs,minDepth,maxDepth,quantized,variable_depth,use_rus,verbose]=getPrmDflt(varargin,dfs,1);

opt.SET_MINPARENT_TREE_WL = 1;
opt.learning_rate         = shrinkage;
opt.frac_features         = fracFtrs;
opt.num_iterations        = nWeak;
opt.scalar_class_labels   = 1;
opt.stop_with_negative_wl_weight = stopAtNegWeight;
opt.maxDepth              = maxDepth;
opt.minDepth              = minDepth;
opt.USE_QUANTIZED         = quantized;
opt.use_variable_depth    = variable_depth;
opt.USE_RUS_BALANCED_WL   = use_rus; % Use Random Under Sampling Balancing .
opt.verbose               = verbose;
if opt.USE_QUANTIZED
  opt.train_weak_learner    = @train_costs_pdollar_quantized_multiclasstree;
else
  opt.train_weak_learner    = @train_costs_pdollar_multiclasstree;
end
opt.classify_weak_learner = @classify_costs_pdollar_multiclasstree;
if ((resampling >= 1.0) || (resampling < 0))
  opt.USE_SAMPLED_WL        = 0;
  opt.USE_RUS_BALANCED_WL   = 0;
  opt.SAMPLE_PROPORTION_WL  = resampling;
elseif ~opt.USE_RUS_BALANCED_WL
  opt.USE_SAMPLED_WL        = 1;
  opt.SAMPLE_PROPORTION_WL  = resampling;
else
  opt.USE_SAMPLED_WL        = 0;
  opt.SAMPLE_PROPORTION_WL  = resampling;
end

msg='Training BAdaCost: nWeak=%3i shrinkage=%f resampling=%f fracFtrs=%f\n';
if(verbose), fprintf(msg,nWeak,shrinkage,resampling,fracFtrs); start=clock; end

[classfr, cost_curve] = badacostTrain( x', y, Cost, opt );
%figure;
%plot(cost_curve);
%xlabel('#weak learners');
%ylabel('cost');

% Now we adapt the output of the badacost to the P.Dollar toolbox.
% create output model struct
k=0;
nWeak = length(classfr.WEAK_LEARNERS);
for i=1:nWeak
   k=max(k,size(classfr.WEAK_LEARNERS{i}.TREE.fids,1));
end
Z = @(type) zeros(k,nWeak,type);
model=struct( 'fids',Z('uint32'), 'thrs',Z('single'), ...
  'child',Z('uint32'), 'hs',Z('single'), 'weights',Z('single'), ...
  'depth',Z('uint32')); %, 'errs',errs, 'losses',losses );
for i=1:nWeak
  T=classfr.WEAK_LEARNERS{i}.TREE;
  k=size(T.fids,1);
  model.fids(1:k,i)=T.fids;
  model.thrs(1:k,i)=T.thrs;
  model.child(1:k,i)=T.child;
  model.hs(1:k,i)=T.hs;
%  model.weights(1:k,i)=T.weights;
  model.depth(1:k,i)=T.depth;
end
depth = max(model.depth(:));
model.treeDepth = depth * uint32(all(model.depth(~model.child)==depth));
model.num_classes = classfr.num_classes;
model.Cprime      = classfr.Cprime;
model.Y           = classfr.Y;
model.wl_weights  = classfr.WEIGHTS;
model.weak_learner_type = 'trees';

% output info to log
predicted = badacostWithTreesApply(x, model);
error = sum(predicted(:) ~= y(:))/length(predicted);
fp    = sum((predicted(:) ~= 1) & (y == 1))./length(predicted);
fn    = sum((predicted(:) == 1) & (y ~= 1))./length(predicted);
msg='Done training err=%.4f fp=%.4f fn=%.4f (t=%.1fs).\n';
if(verbose)
  fprintf(msg,error,fp,fn,etime(clock,start));
end

end

author: MengyangPu

repo: EDTER

save_path: github-repos/MATLAB/MengyangPu-EDTER


text:
function [ZV,ZV2] = ZV_gen2(Z,cz,ind,ZV21)
    [d n]= size(Z);
    b = size(cz,2);

    XX = Z;
    cxx = XX(:,ind);
    sqX = sum(XX.^2,1);
    Xc = XX'*cxx;
    sqcx = sum(cxx.^2,1);
    ZV2 = ones(n,1)*sqcx - 2*Xc + sqX'*ones(1,b);

    for l = 1:d
        ZV{l} = ones(n,1)*cz(l,:) - Z(l,:)'*ones(1,size(cz,2));
    end;

author: BehnoodRasti


text:
function X=transpose(X)
%TRANSPOSE (overloaded)

if isa(X,'blkvar')
    X = sdpvar(X);
end

n = X.dim(1);
m = X.dim(2);
ind = reshape(reshape(1:n*m,n,m)',n*m,1);
X.basis = X.basis(ind,:);
X.dim(1) = m;
X.dim(2) = n;
% Reset info about conic terms
X.conicinfo = [0 0];
X = transposefactor(X);

author: zarathustr

repo: LibQPEP

save_path: github-repos/MATLAB/zarathustr-LibQPEP