text:
%   AUTHORSHIP
%   Primary Developer: Stephen Meehan <swmeehan@stanford.edu>
%   Math Lead & Secondary Developer:  Connor Meehan <connor.gw.meehan@gmail.com>
%   Bioinformatics Lead:  Wayne Moore <wmoore@stanford.edu>
%   Provided by the Herzenberg Lab at Stanford University
%   License: BSD 3 clause
%

% this wrapper around MatLab internal map is meant for
% polymorphic function signature compatability with other
% classdef and JAVA class in CytoGenie AutoGate
classdef Map < handle

    properties(Constant)
        PROP_ID='nextId';
    end

    properties
        propertyFile;
    end

    properties(SetAccess=private)
        map;
    end

    methods(Static)
        function SetOnOffBoolean(props, prop, value)
            if strcmp('on', value)
                props.set(prop, 'true');
            else
                props.set(prop, 'false');
            end
        end

        function SetBoolean(props, prop, value)
            if value
                props.set(prop, 'true');
            else
                props.set(prop, 'false');
            end
        end

        function this=Global(closeIfTrueOrMap)
            persistent singleton;
            if nargin>0 && islogical(closeIfTrueOrMap) && closeIfTrueOrMap
                clear singleton;
                singleton=[];
                disp('Resetting global Map');
                this=[];
            else
                if nargin==1
                    try
                        priorMap=closeIfTrueOrMap;
                        %test method compatibility
                        priorMap.size
                        prop='IsBasicMap';
                        if ~priorMap.has(prop)
                            priorMap.set(prop, 'false')
                            priorMap.get(prop, 'true')
                            priorMap.remove(prop);
                        else
                            priorMap.get(prop, 'true')
                        end
                        singleton=priorMap;
                        this=singleton;
                        return;
                    catch ex
                        ex.getReport
                    end
                end
                if isempty(singleton)
                    singleton=Map;
                    singleton.highDef=Gui.hasPcHighDefinitionAProblem(2000, 2500, false);
                    Map.SetHighDef(singleton, singleton.highDef);
                end
                this=singleton;
            end
        end

        function path=Path
            path=Map.Global.contentFolder;
        end

        function nums=GetNumbers(props, name)
            nums=props.get(name, []);
            if ~isempty(nums)
                nums=str2num(nums);
            else
                nums=[];
            end
        end

        function SetStruct(this, id, structure)
            names=fieldnames(structure)';
            N=length(names);
            for i=1:N
                name=names{i};
                value=getfield(structure, name);
                this.set([id '.' name], value);
            end
        end
    end

    methods
        function this=Map(keysOrFileName, values)
            if nargin<2
                values={};
                if nargin<1
                    keysOrFileName=[];
                end
            end
            if ~isempty(values)
                this.map=containers.Map(keysOrFileName, values);
            elseif ~isempty(keysOrFileName) && ischar(keysOrFileName)
                this.propertyFile=keysOrFileName;
                this.load;
            else
                this.map=containers.Map;
            end
        end

        function cnt=size(this)
            cnt=this.map.length;
        end

        function reset(this)
            this.clear;
        end

        function clear(this)
            remove(this.map, this.map.keys);
        end

        function priorValue=remove(this, name)
            priorValue=this.get(name);
            remove(this.map, name);
        end

        function value=getIdentified(this, id, name)
            value=this.get([id '.' name]);
        end

        function set(this, name, value)
            this.map(name)=value;
        end

        function prior=put(this, name, value)
            prior=this.get(name);
            this.map(name)=value;
        end

        %for value char compatibility with outside map classes
        function setBoolean(this, name, isTrue)
            if isTrue
                isTrue='true';
            else
                isTrue='false';
            end
            this.map(name)=isTrue;
        end

        % for value char compatibility with outside map classes
        function setNumeric(this, name, num)
            this.map(name)=num2str(num);
        end

        function isTrue=is(this, name, defaultIsTrue)
            if this.map.isKey(name)
                value=this.map(name);
                if ischar(value)
                    value=strcmpi('yes', value) || strcmpi('true', value);
                end
                isTrue=value;
            else
                if nargin<3
                    isTrue=false;
                else
                    isTrue=defaultIsTrue;
                end
            end
        end

        function value=get(this, name, defaultValue)
            if this.map.isKey(name)
                value=this.map(name);
            else
                if nargin<3
                    value=[];
                else
                    value=defaultValue;
                end
            end
        end

        function value=getNumeric(this, property, defaultValue)
            value=this.get(property);
            if isempty(value)
                if nargin>2
                    value=defaultValue;
                else
                    value=0;
                end
            else
                if isa(value,'char')
                    value=str2double(value);
                    if isnan(value)
                        if nargin>2
                            value=defaultValue;
                        else
                            value=0;
                        end
                    end
                elseif ~isnumeric(value) || any(isnan(value))
                    if nargin>2
                        value=defaultValue;
                    else
                        value=0;
                    end
                end
            end
        end

        function ok=has(this, name)
            ok=this.map.isKey(name);
        end

        function ok=containsKey(this, name)
            ok=this.map.isKey(name);
        end

        function save(this, propertyFile)
            if nargin>1
                this.propertyFile=propertyFile;
            end
            if ~isempty(this.propertyFile)
                basicMap=this;
                save(this.propertyFile, 'basicMap');
            end
        end

        function load(this, propertyFile)
            if nargin>1
                this.propertyFile=propertyFile;
            end
            if ~isempty(this.propertyFile) && exist(this.propertyFile, 'file')
                load(this.propertyFile, 'basicMap');
                this.map=basicMap.map;
            end
        end

        function k=keys(this)
            k=this.map.keys;
        end

        function this=addAll(this, that, keys)
            if nargin<3
                it=that.map.keySet.iterator;
                while(it.hasNext)
                    name=it.next;
                    this.set(name, that.props{that.map.get(name)});
                end
            else
                N=length(keys);
                for i=1:N
                    if that.has(keys{i})
                        this.set(keys{i}, that.get(keys{i}));
                    end
                end
            end
        end

        function idx=indexOf(this, name, value)
            idx=-1;
            N=this.countIfMultipleElse0(name);
            if N==0 && this.has(name)
                v=this.get(name);
                if strcmp(v, value)
                    idx=1;
                end
            else
                for i=1:N
                    v=this.get([name '.' num2str(i)]);
                    if strcmp(v, value)
                        idx=i;
                        break;
                    end
                end
            end
        end

        function wasMissing=addIfMissing(this, name, value)
            idx=this.indexOf(name,value);
            if idx<=0
                wasMissing=true;
                this.add(name,value);
            else
                wasMissing=false;
            end
        end

        function wasMissing=putIfMising(this, name, value)
            if ~this.has(name)
                wasMissing=true;
                this.put(name,value);
            else
                wasMissing=false;
            end
        end

        function debug(this)
            k=this.map.keys;
            N=length(k);
            for i=1:N
                name=k{i};
                v=this.get(name);
                if ischar(v)
                    fprintf('%s=%s\n', name, v);
                elseif isnumeric(v)
                    fprintf('%s=%d\n', name, v);
                else
                    ss=class(v);
                    fprintf('%s=[%s object]\n', name,  ss);
                end
            end
        end

        function add(this, name, value)
            name2=this.increment(name);
            this.set(name2, value);
        end

        function setAll(this, name, values)
            this.remove(name);
            N=length(values);
            for i=1:N
                this.add(name,values{i});
            end
        end

        function c=getAll(this, name)
            N=this.countIfMultipleElse0(name);
            if N==0 && this.has(name)
                c{1}=this.get(name);
            else
                c=cell(1,N);
                for i=1:N
                    c{i}=this.get([name '.' num2str(i)]);
                end
            end
        end

        function name2=increment(this, name)
            N=this.countIfMultipleElse0(name)+1;
            if N==1 && this.has(name)
                N=N+1;
                value=this.get(name);
                this.remove(name);
                this.set([name '.1'], value);
            end
            name2=[name '.' num2str(N)];
            this.set([name '.count'], num2str(N));
        end

        function N=countIfMultipleElse0(this, name)
            N=0;
            if ischar(name)
                num=this.get([name '.count']);
                if ~isempty(num)
                    N=str2num(num);
                end
            end
        end

        function id=newId(this)
            id=num2str(this.getNumeric(Map.PROP_ID, 0)+1);
            this.set(Map.PROP_ID, id);
            this.set([id '.createdWhen'], char(datetime));
            this.save;
        end
    end
end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function w=update_w(dvec, n)
% w=update_w(dvevc, n)
% Computes update for w_jk (JxK) in variational approximation (Buntine & Jakulin
% DCA 2006)
% dvec: (J x I) data - each column is one image
% n: (J x K x I )
% J=#pixels
% K=#components
% I=#images.

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

dvec_reshaped = reshape(dvec,j,1,i);
wtmp = squeeze(sum(bsxfun(@times,dvec_reshaped,n),3));
w=bsxfun(@rdivide, wtmp, sum(wtmp,1));

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function [] = saveSimResults()
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%{
This is a simple save routine provided as part of a quadcopter simulation.

    Additional quadcopter modeling and simulation materials available at:
    github.com/dch33/Quad-Sim

Copyright (C) 2014 D. Hartman, K. Landis, S. Moreno, J. Kim, M. Mehrer

License:
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
%}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

yout = evalin('base','yout');
tout = evalin('base','tout');
quadModel = evalin('base','quadModel');
IC = evalin('base','IC');
pathExist = 'exist(''path'',''var'')';
if evalin('base',pathExist)
    path = evalin('base','path');
    data = {'yout', 'tout', 'quadModel', 'IC', 'path'};
else
    data = {'yout', 'tout', 'quadModel', 'IC'};
end
uisave(data,'simResults_1')

repo: Quad-Sim

path: github-repos/MATLAB/dch33-Quad-Sim/Quad-Sim-961bc69d4939c8d0661eeb9820de668994262f65/Quadcopter Dynamic Modeling and Simulation/Simulation Files/Functions/saveSimResults.m


text:
%+========================================================================+
%|                                                                        |
%|            This script uses the GYPSILAB toolbox for Matlab            |
%|                                                                        |
%| COPYRIGHT : Matthieu Aussal (c) 2017-2019.                             |
%| PROPERTY  : Centre de Mathematiques Appliquees, Ecole polytechnique,   |
%| route de Saclay, 91128 Palaiseau, France. All rights reserved.         |
%| LICENCE   : This program is free software, distributed in the hope that|
%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use,    |
%| redistribute and/or modify it under the terms of the GNU General Public|
%| License, as published by the Free Software Foundation (version 3 or    |
%| later,  http://www.gnu.org/licenses). For private use, dual licencing  |
%| is available, please contact us to activate a "pay for remove" option. |
%| CONTACT   : matthieu.aussal@polytechnique.edu                          |
%| WEBSITE   : www.cmap.polytechnique.fr/~aussal/gypsilab                 |
%|                                                                        |
%| Please acknowledge the gypsilab toolbox in programs or publications in |
%| which you use it.                                                      |
%|________________________________________________________________________|
%|   '&`   |                                                              |
%|    #    |   FILE       : nrtFfmBuilderFem.m                            |
%|    #    |   VERSION    : 0.61                                          |
%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |
%|  ( # )  |   CREATION   : 14.03.2019                                    |
%|  / 0 \  |   LAST MODIF : 05.09.2019                                    |
%| ( === ) |   SYNOPSIS   : Non regression test for convolution using     |
%|  `---'  |                arbitrary kenel integral galerkin formulation |
%+========================================================================+

% Cleaning
clear all
close all
clc

% Gypsilab path
run('../../addpathGypsilab.m')

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('~~~~~~~~~~~~~ DEFINITIONS ~~~~~~~~~~~~~')

% Dimensions
Nx = 1e3
Ny = 2e3

% Accuracy
tol = 1e-3

% Meshes
Xmsh = mshSphere(Nx,1);
Ymsh = mshCube(Ny,2*[1 1 1]);
Ymsh = Ymsh.bnd;

% Domain
Xdom = dom(Xmsh,3);
Ydom = dom(Ymsh,3);

% Finite element
Xfem = fem(Xmsh,'P1');
Yfem = fem(Ymsh,'P1');

% Wave number or frequency (Hz)
stp = Xmsh.stp;
k   = 5

% Green kernel
green = '[exp(ikr)/r]'
Gxy   = @(X,Y) femGreenKernel(X,Y,green,k);

% Charges
V = (-1+2*rand(length(Yfem),1)) + (-1+2i*rand(length(Yfem),1));

% Spatial representation of particles
figure
plot(Xmsh,'b')
hold on
plot(Ymsh,'r')
alpha(0.5)
axis equal

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FULL PRODUCT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('~~~~~~~~~~~~~ FULL PRODUCT ~~~~~~~~~~~~~')

% Full Matrix
tic
M = integral(Xdom,Ydom,Xfem,Gxy,Yfem);
toc

% Matrix-vector product
tic
ref = M * V;
toc

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FFM PRODUCT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('~~~~~~~~~~~~~ FFM PRODUCT ~~~~~~~~~~~~~')

% FFM
tic
Mv = integral(Xdom,Ydom,Xfem,green,k,Yfem,tol);
toc

% FFM Matrix-vector product
tic
sol = Mv * V;
toc

% Error
norm(ref-sol)/norm(ref)

disp('~~> Michto gypsilab !')

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
%%*********************************************************************
%% gdcomp: Compute gd = 1/td in Equation (15) of FOT's paper.
%%
%% [gd,info,blk2,At2,C2,b2] = gdcomp(blk,At,C,b,OPTIONS);
%%
%%*********************************************************************

  function [gd,info,blk2,At2,C2,b2] = gdcomp(blk,At,C,b,OPTIONS);

  if (nargin == 4)
     OPTIONS = sqlparameters;
     OPTIONS.vers = 1;
     OPTIONS.printlevel = 3;
  end
  if ~iscell(C); tmp = C; clear C; C{1} = tmp; end
%%
  m = length(b);
  blk2 = blk;
  At2 = cell(size(blk,1),1);
  C2 = cell(size(blk,1),1);
  b2 = [zeros(m,1); 1; 0];
%%
%%
%%
  for p = 1:size(blk,1)
     pblk = blk(p,:);
     n = sum(pblk{2});
     if strcmp(pblk{1},'s')
        C2{p,1} = sparse(n,n);
     else
        C2{p,1} = zeros(n,1);
     end
  end
%%
%% New multipliers in dual problem: tt, theta.
%% [v; tt; theta].
%%
   ss = 0; cc = 0; aa = zeros(1,m);
   exist_ublk = 0;
   for p = 1:size(blk,1)
      pblk = blk(p,:);
      n = sum(pblk{2});
      if strcmp(pblk{1},'s')
         At2{p} = [At{p}, svec(pblk,speye(n,n),1), -svec(pblk,C{p},1)];
         ss = ss + n;
         cc = cc + trace(C{p});
         aa = aa + svec(pblk,speye(n),1)'*At{p};
      elseif strcmp(pblk{1},'q')
         eq = zeros(n,1);
         idx1 = 1+[0,cumsum(pblk{2})];
         idx1 = idx1(1:length(idx1)-1);
         eq(idx1) = ones(length(idx1),1);
         At2{p} = [At{p}, 2*sparse(eq), -sparse(C{p})];
         ss = ss + 2*length(pblk{2});
         cc = cc + sum(C{p}(idx1));
         aa = aa + eq'*At{p};
      elseif strcmp(pblk{1},'l')
         el = ones(n,1);
         At2{p} = [At{p}, sparse(el), -sparse(C{p})];
         ss = ss + n;
         cc = cc + el'*C{p};
         aa = aa + el'*At{p};
      elseif strcmp(pblk{1},'u')
         At2{p} = [At{p}, sparse(n,1), -sparse(C{p})];
         exist_ublk = 1;
      end
   end
%%
%% 3 additional inequality constraints in dual problem.
%%
   alp = max(1,sqrt(sum(abs(aa))));
   numblk = size(blk,1);
   blk2{numblk+1,1} = 'l'; blk2{numblk+1,2} = 3;
   C2{numblk+1,1}  = [1; alp; 0];
   At2{numblk+1,1} = [-aa,        0,   cc;
		     zeros(1,m),  0,   alp;
		     zeros(1,m), alp, -alp];
%%
%% Solve SDP
%%
   OPTIONS.gaptol = 1e-10;
   [obj,X,y,Z,info] = HSDsqlp(blk2,At2,C2,b2,OPTIONS);
   gd = 1/abs(obj(2));
   err = max([info.gap/(1+mean(abs(obj))), info.pinfeas, info.dinfeas]);
   if (OPTIONS.printlevel)
      fprintf('\n ******** gd = %3.1e, err = %3.1e\n',gd,err);
      if (err > 1e-6);
         fprintf('\n----------------------------------------------------')
         fprintf('\n gd problem is not solved to sufficient accuracy');
         fprintf('\n----------------------------------------------------\n')
      end
   end
%%*********************************************************************

author: yu-jiang

repo: radpbook

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


text:
function p = subsasgn(p,s,r)
%SUBSASGN     Implements subscripted assignment for polynomials
%
%  p(i) = r
%
%For univariate polynomials p, p(i) is the coefficient of x^i, 0<=i<=degree(p).
%  For i>degree(p), p(i):=0. Similarly, p(i:j) is the vector of coefficients
%  [ p(i) p(i+1) ... p(j) ], or, p(:) is the (row) vector of all coefficients
%  of p, the same as vector(p) for univariate polynomials. Especially,
%  p(i) = [] of p(i:j) = [] cancels the i-th or i..j-th coefficient, respectively.
%
%For multivariate polynomials p in k variables x_1..x_k, p(i) is the
%  coefficient of x_1^i, i.e. a polynomial in k-1 variables.
%  Similarly, p(i,[],j) or p(i,:,j) is the coefficient polynomial of
%  x1^i*x3^j. Indices i,j,... must be single indices, no range.
%Note that access to coefficients refers to the current order p.v of
%  variables of p. To change this order, see permvars.
%For example, for a polynomial in three variables p.v={'x','y','z'},
%  p(1,0,3) is the coefficient of x*z^3 (a constant), where p(1,[],3)
%  if the coefficient of x*z^3, a univariate polynomial in y.
%
%Polynomial evaluation is denoted by p{x}, computing the value of p at x.
%  This is the same as polyval(p,x).
%For univariate polynomials, x may be a vector or matrix yielding the vector
%  or matrix of polynomial values evaluated at the corresponding coefficients.
%For multivariate polynomials, x is a vector of values of the variables.
%  For x being a matrix, the result is the (column) vector of p{x(i,:)}.
%
%Moreover, p.mid, p.rad, p.inf, p.sup give access to the midpoint, radius,
%  infimum and supremum of p, respectively.
%
%Finally, p.e, p.c and p.v give access to the arrays of exponents, coefficients
%  and variables of p, such that polynom(p.e,p.c,p.v) is again p. Single variables
%  are accessed by p.v{i}.
%
%In the univariate case,  p == polynom(p.c,p.v)  [ degree is length(p.c)+1 ].
%In the multivariate case,  p == polynom(p.e,p.c,p.v)  [ p.e is (sparse) exponent set ].
%

% written  11/20/97     S.M. Rump
% modified 04/04/04     S.M. Rump  set round to nearest for safety
% modified 04/06/05     S.M. Rump  rounding unchanged
% modified 09/28/08     S.M. Rump  check for rounding to nearest improved
%

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

  while 1
    if ~isa(p,'polynom')
      p = subsasgn(p,s(1),r);
    elseif strcmp(s(1).type,'()')     % index reference p(i)
      if size(p.e,2)==1               % univariate polynomial
        if length(s(1).subs)>1
          error('invalid call: more than one index')
        end
        if isequal(s(1).subs{1},':')
          p.c(:) = typeadj(r,typeof(p.c));
        else
          n1 = length(p.c);
          index = n1-s(1).subs{1};     % index vector, p(0) constant term, etc.
          if ~isreal(index) | ~isequal(index,round(index))
            error('index must be integer')
          end
          if any(index>n1)             % index negative
            error('index out of range')
          end
          if ( length(r)>1 ) & ( length(index)~=length(r) )
            error('length of arguments do not match, invalid assignment')
          end
          if isa(r,'intval') & ~isa(p.c,'intval')
            p.c = intval(p.c);
          end
          m = min(index);
          if isempty(r)
            r = 0;
          end
          if m<=0                      % index greater than degree
            p.c = [zeros(1,-m+1) p.c];
            p.c(index-m+1) = r;
          else
            p.c(index) = r;
          end
        end
        m = min(find(p.c~=0));
        if isempty(m)                  % zero polynomial
          p.c = typeadj(0,typeof(p.c));
        elseif m>1                     % leading coefficients zero
          p.c = p.c(m:length(p.c));    % Matlab bug: ..end does not work for user-defined data types
        end
        p.e = length(p.c)-1;
      else                             % multivariate polynomial
        k = size(p.e,2);               % number of variables
        if length(s(1).subs)>k
          error('too many indices')
        end
        exponents = zeros(1,k);
        for i=1:length(s(1).subs)
          if isempty(s(1).subs{i}) | isequal(s(1).subs{i},':')
            error('Only integer indices allowed in multivariate polynomial assignment')
          end
          exponents(i) = s(1).subs{i};
        end
        I = all( ( p.e == repmat(exponents,size(p.e,1),1) ) , 2 );
        if any(I)                     % coefficient does occur
          if r==0
            p.e(I,:) = [];
            p.c(I) = [];
          else
            p.c(I) = r;
          end
        else                          % coefficient does not occur
          if r~=0
            p.e = [p.e ; exponents];
            if isa(r,'intval')
              p.c = intval(p.c);
            end
            p.c = [p.c ; r];
          end
        end
        p = normalize(p);
      end
    elseif strcmp(s(1).type,'.')      % polynomial access to .v
      if strcmp(s(1).subs,'v')
        if ischar(p.v)                % univariate p
          if ~ischar(r)
            error('variable of univariate polynomial must be string')
          else
            p.v = r;
          end
        else                          % multivariate p
          if ( length(s)==2 ) & ( s(2).type=='{}' )
            if s(2).subs{1}>length(p.v)
              error('index of variable too large')
            end
            if ~ischar(r)
              error('variable name must be string')
            end
            I = find(strcmp(p.v,r));
            if ~isempty(I) & ( I~=s(2).subs{1} )
              error('duplicate variable name not allowed')
            end
            p.v{s(2).subs{1}} = r;
            if rndold
              setround(rndold)
            end
            return
          elseif ~iscell(r)
            error('variables of multivariate polynomials must be cell array of strings')
          else
            if length(r)~=length(p.v)
              error('number of variables does not match')
            else
              p.v = r;
            end
          end
        end
      else
        error('invalid reference for polynomial')
      end
    else
      error('invalid index reference for polynomial')
    end
    if length(s)==1
      if rndold
        setround(rndold)
      end
      return
    end
    error('invalid call of polynom/subsasgn')
  end

repo: OpenMAS


text:
% [INPUT]
% eq = A vector of floats [0,Inf) of length k representing the market value of equity.
% db = A float or a vector of floats [0,Inf) of length k representing the default barrier.
% r = A float or a vector of floats (-Inf,Inf) of length k representing the annualized risk-free interest rate.
% t = A float or a vector of floats (0,Inf) of length k representing the time to maturity of default barrier.
% op = A string representing the option pricing model used by the Systemic CCA framework (optional, default='BSM'):
%   - 'BSM' for Black-Scholes-Merton;
%   - 'GC' for Gram-Charlier.
%
% [OUTPUT]
% va = A column vector of floats of length k representing the value of assets.
% vap = Output argument representing the distributional parameters of assets whose type depends on the chosen option pricing model:
%   - for Black-Scholes-Merton, a float [0,Inf) representing the annualized volatility of assets;
%   - for Gram-Charlier, a row vector of floats (-Inf,Inf) of length 3 whose values represent respectively the annualized volatility, skewness and excess kurtosis of assets.

function [va,vap] = kmv_structural(varargin)

    persistent ip;

    if (isempty(ip))
        ip = inputParser();
        ip.addRequired('eq',@(x)validateattributes(x,{'double'},{'real' 'finite' 'nonnegative' 'vector' 'nonempty'}));
        ip.addRequired('db',@(x)validateattributes(x,{'double'},{'real' 'finite' 'nonnegative' 'vector' 'nonempty'}));
        ip.addRequired('r',@(x)validateattributes(x,{'double'},{'real' 'finite' 'vector' 'nonempty'}));
        ip.addRequired('t',@(x)validateattributes(x,{'double'},{'real' 'finite' '>' 0 'vector' 'nonempty'}));
        ip.addRequired('op',@(x)any(validatestring(x,{'BSM' 'GC'})));
    end

    ip.parse(varargin{:});

    ipr = ip.Results;
    [eq,db,r,t] = validate_input(ipr.eq,ipr.db,ipr.r,ipr.t);
    op = ipr.op;

    nargoutchk(1,2);

    [va,vap] = kmv_structural_internal(eq,db,r,t,op);

end

function [va,vap] = kmv_structural_internal(eq,db,r,t,op)

    df = exp(-r .* t);

    k = numel(r);
    sk = sqrt(k);

    va = eq + (db .* df);
    va_r = diff(log(va));
    va_s = sqrt(252) * std(va_r);

    sst = va_s .* sqrt(t);
    d1 = (log(va ./ db) + ((r + (0.5 * va_s^2)) .* t)) ./ sst;
    d2 = d1 - sst;
    n1 = normcdf(d1);
    n2 = normcdf(d2);

    va_old = va;
    va = eq + ((va .* (1 - n1)) + (db .* df .* n2));

    count = 0;
    error = norm(va - va_old) / sk;

    while ((count < 10000) && (error > 1e-8))
        sst = va_s .* sqrt(t);
        d1 = (log(va ./ db) + ((r + (0.5 * va_s^2)) .* t)) ./ sst;
        d2 = d1 - sst;
        n1 = normcdf(d1);
        n2 = normcdf(d2);

        va_old = va;
        va = eq + ((va .* (1 - n1)) + (db .* df .* n2));
        va_r = diff(log(va));
        va_s = sqrt(252) * std(va_r);

        count = count + 1;
        error = norm(va - va_old) / sk;
    end

    if (strcmp(op,'BSM'))
        vap = va_s;
    else
        va_g = skewness(va_r,0) / sqrt(252);
        va_k = (kurtosis(va_r,0) - 3) / 252;

        vap = [va_s va_g va_k];
    end

end

function [eq,db,r,t] = validate_input(eq,db,r,t)

    eq = eq(:);
    eq_len = numel(eq);

    if (eq_len < 5)
        error('The value of ''eq'' is invalid. Expected input to be a vector containing at least 5 elements.');
    end

    data = {db(:) r(:) t(:)};

    l = unique(cellfun(@numel,data));
    l_scalar = (l == 1);

    if (any(l_scalar))
        if (any(l(~l_scalar) ~= eq_len))
            error(['The number of elements of ''db'', ''r'' and ''t'' must be either 1 or equal to ' num2str(eq_len) '.']);
        end
    else
        if (any(l ~= eq_len))
            error(['The number of elements of ''db'', ''r'' and ''t'' must be either 1 or equal to ' num2str(eq_len) '.']);
        end
    end

    for i = 1:numel(data)
        data_i = data{i};

        if (numel(data_i) == 1)
            data{i} = repmat(data_i,eq_len,1);
        end
    end

    [db,r,t] = deal(data{:});

end

author: TommasoBelluzzo

repo: SystemicRisk


text:
function print_png(outfile)
%PRINT_PNG stores a figure as png file
%
%   Usage: print_png(outfile)
%
%   Input parameters:
%       outfile     - file name to store the figure
%
%   See also: plot_sound_field, print_png

%*****************************************************************************
% The MIT License (MIT)                                                      *
%                                                                            *
% Copyright (c) 2010-2019 SFS Toolbox Developers                             *
%                                                                            *
% Permission is hereby granted,  free of charge,  to any person  obtaining a *
% copy of this software and associated documentation files (the "Software"), *
% to deal in the Software without  restriction, including without limitation *
% the rights  to use, copy, modify, merge,  publish, distribute, sublicense, *
% and/or  sell copies of  the Software,  and to permit  persons to whom  the *
% Software is furnished to do so, subject to the following conditions:       *
%                                                                            *
% The above copyright notice and this permission notice shall be included in *
% all copies or substantial portions of the Software.                        *
%                                                                            *
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
% IMPLIED, INCLUDING BUT  NOT LIMITED TO THE  WARRANTIES OF MERCHANTABILITY, *
% FITNESS  FOR A PARTICULAR  PURPOSE AND  NONINFRINGEMENT. IN NO EVENT SHALL *
% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
% LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT, TORT  OR OTHERWISE, ARISING *
% FROM,  OUT OF  OR IN  CONNECTION  WITH THE  SOFTWARE OR  THE USE  OR OTHER *
% DEALINGS IN THE SOFTWARE.                                                  *
%                                                                            *
% The SFS Toolbox  allows to simulate and  investigate sound field synthesis *
% methods like wave field synthesis or higher order ambisonics.              *
%                                                                            *
% https://sfs.readthedocs.io                            sfstoolbox@gmail.com *
%*****************************************************************************

%% ===== Checking of input parameter =====================================
nargmin = 1;
nargmax = 1;
narginchk(nargmin,nargmax);

%% ===== Main ============================================================
% Font type
set_font_type('Arial');
pause(0.2);
print('-r150','-opengl','-dpng',outfile);
pause(0.2);
close;

author: sfstoolbox

repo: sfs-matlab


text:
% MAIN.m  --  Lesson 2 -- Simple Drawing
%
% This script performs a simulation of the cart as it passively moves from
% some initial state.
%
% In the lesson I've moved the state plotting commands to their own
% function, and introduced some basic drawing concepts using plot
%

clc; clear;

%%%% Initial State
z0 = [
    0.0;   %horizontal position
    (pi/180)*120;  %pendulum angle (wrt gravity)
    0.0;   %horizontal velocity
    0.0];  %pendulum angular rate

%%%% Physical Parameters
p.m1 = 1.0;  % (kg) Cart mass
p.m2 = 0.3;  % (kg) pole mass
p.g = 9.81;  % (m/s^2) gravity
p.l = 0.5;   % (m) pendulum (pole) length

%%%% Time vector
t = linspace(0,2,250);  %Simulation time stamps

%%%% Function Handle
dynFun = @(t,z)( cartPoleDynamics(z, p) );

%%%% Simulate the system!
options = odeset(...
    'RelTol',1e-8, ...
    'AbsTol',1e-8);
[~, z] = ode45(dynFun, t, z0, options);   %  <-- This is the key line!
z = z';

%%%% Plots:
figure(1); clf;
plotPendulumCart(t,z);  %Moved plotting to its own function

%%%% Drawing:

% Convert states to cartesian positions:
pos = cartPolePosition(z,p);

% Unpack the positions:
x1 = pos(1,:);
y1 = pos(2,:);
x2 = pos(3,:);
y2 = pos(4,:);

% Compute the extents of the drawing, keeping everything in view
padding = 0.2*p.l;  %Free space around edges
xLow = min(min(x1,x2)) - padding;
xUpp = max(max(x1,x2)) + padding;
yLow = min(min(y1,y2)) - padding;
yUpp = max(max(y1,y2)) + padding;
extents = [xLow,xUpp,yLow,yUpp];

% Select an index corresponding to the time step to draw:
idx = 6;  %Draw the initial state for now

% Create and clear a figure:
figure(2); clf;
hold on;  %   <-- Important!

title('Cart-Pole System')

% Draw the rail that the cart-pole travels on
plot([xLow, xUpp],[0,0],'k-','LineWidth',2);

% Draw the cart:
plot(x1(idx), y1(idx), 'bs','MarkerSize',30,'LineWidth',5);

% Draw the pole:
plot([x1(idx),x2(idx)], [y1(idx), y2(idx)], 'r-','LineWidth',2);

% Draw the bob of the pendulum:
plot(x2(idx), y2(idx), 'ro','MarkerSize',22,'LineWidth',4);

% Format the axis so things look right:
axis(extents); axis equal; axis off;

author: MatthewPeterKelly

repo: dscTutorials


text:
function [ x, w ] = jacobi_ss_compute ( n, alpha, beta )

%*****************************************************************************80
%
%% JACOBI_SS_COMPUTE computes the abscissa and weights for Gauss-Jacobi quadrature.
%
%  Discussion:
%
%    The integral:
%
%      Integral ( -1 <= X <= 1 ) (1-X)**ALPHA * (1+X)**BETA * F(X) dX
%
%    The quadrature rule:
%
%      Sum ( 1 <= I <= N ) W(I) * F ( X(I) )
%
%    Thanks to Xu Xiang of Fudan University for pointing out that
%    an earlier implementation of this routine was incorrect!
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 October 2011
%
%  Author:
%
%    Original FORTRAN77 version by Arthur Stroud, Don Secrest.
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Arthur Stroud, Don Secrest,
%    Gaussian Quadrature Formulas,
%    Prentice Hall, 1966,
%    LC: QA299.4G3S7.
%
%  Parameters:
%
%    Input, integer N, the order.
%
%    Input, real ALPHA, BETA, the exponents of (1-X) and
%    (1+X) in the quadrature rule.  For simple Gauss-Legendre quadrature,
%    set ALPHA = BETA = 0.0.  -1.0 < ALPHA and -1.0 < BETA are required.
%
%    Output, real X(N), the abscissas.
%
%    Output, real W(N), the weights.
%

%
%  Check ALPHA and BETA.
%
  if ( alpha <= -1.0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'JACOBI_SS_COMPUTE - Fatal error!\n' );
    fprintf ( 1, '  -1.0 < ALPHA is required.\n' );
    error ( 'JACOBI_SS_COMPUTE - Fatal error!' );
  end

  if ( beta <= -1.0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'JACOBI_SS_COMPUTE - Fatal error!\n' );
    fprintf ( 1, '  -1.0 < BETA is required.\n' );
    error ( 'JACOBI_SS_COMPUTE - Fatal error!' );
  end

  x = zeros ( n, 1 );
  w = zeros ( n, 1 );
  b = zeros ( n, 1 );
  c = zeros ( n, 1 );
%
%  Set the recursion coefficients.
%
  for i = 1 : n

    if ( alpha + beta == 0.0 || beta - alpha == 0.0 )

      b(i) = 0.0;

    else

      b(i) = ( alpha + beta ) * ( beta - alpha ) / ...
            ( ( alpha + beta + 2 * i ) ...
            * ( alpha + beta + 2 * i - 2 ) );

    end

    if ( i == 1 )

      c(i) = 0.0;

    else

      c(i) = 4.0 * ( i - 1 ) * ( alpha + i - 1 ) * ( beta + i - 1 ) ...
        * ( alpha + beta + i - 1 ) / ( ( alpha + beta + 2 * i - 1 ) ...
        * ( alpha + beta + 2 * i - 2 )^2 * ( alpha + beta + 2 * i - 3 ) );

    end

  end

  delta = exp ( gammaln ( alpha        + 1.0 ) ...
              + gammaln (         beta + 1.0 ) ...
              - gammaln ( alpha + beta + 2.0 ) );

  cc = delta * 2.0^( alpha + beta + 1.0 ) * prod ( c(2:n) );

  for i = 1 : n

    if ( i == 1 )

      an = alpha / n;
      bn = beta / n;

      r1 = ( 1.0 + alpha ) * ( 2.78 / ( 4.0 + n * n ) ...
        + 0.768 * an / n );

      r2 = 1.0 + 1.48 * an + 0.96 * bn + 0.452 * an^2 + 0.83 * an * bn;

      xval = ( r2 - r1 ) / r2;

    elseif ( i == 2 )

      r1 = ( 4.1 + alpha ) / ...
        ( ( 1.0 + alpha ) * ( 1.0 + 0.156 * alpha ) );

      r2 = 1.0 + 0.06 * ( n - 8.0 ) * ( 1.0 + 0.12 * alpha ) / n;

      r3 = 1.0 + 0.012 * beta * ...
        ( 1.0 + 0.25 * abs ( alpha ) ) / n;

      xval = xval - r1 * r2 * r3 * ( 1.0 - xval );

    elseif ( i == 3 )

      r1 = ( 1.67 + 0.28 * alpha ) / ( 1.0 + 0.37 * alpha );

      r2 = 1.0 + 0.22 * ( n - 8.0 ) / n;

      r3 = 1.0 + 8.0 * beta / ( ( 6.28 + beta ) * n * n );

      xval = xval - r1 * r2 * r3 * ( x(1) - xval );

    elseif ( i < n - 1 )

      xval = 3.0 * x(i-1) - 3.0 * x(i-2) + x(i-3);

    elseif ( i == n - 1 )

      r1 = ( 1.0 + 0.235 * beta ) / ( 0.766 + 0.119 * beta );

      r2 = 1.0 / ( 1.0 + 0.639 * ( n - 4.0 ) ...
        / ( 1.0 + 0.71 * ( n - 4.0 ) ) );

      r3 = 1.0 / ( 1.0 + 20.0 * alpha / ( ( 7.5 + alpha ) * n * n ) );

      xval = xval + r1 * r2 * r3 * ( xval - x(i-2) );

    elseif ( i == n )

      r1 = ( 1.0 + 0.37 * beta ) / ( 1.67 + 0.28 * beta );

      r2 = 1.0 / ( 1.0 + 0.22 * ( n - 8.0 ) / n );

      r3 = 1.0 / ( 1.0 + 8.0 * alpha / ( ( 6.28 + alpha ) * n * n ) );

      xval = xval + r1 * r2 * r3 * ( xval - x(i-2) );

    end

    [ xval, dp2, p1 ] = jacobi_ss_root ( xval, n, alpha, beta, b, c );

    x(i) = xval;
    w(i) = cc / ( dp2 * p1 );

  end
%
%  Reverse the order of the values.
%
  x = r8vec_reverse ( n, x );
  w = r8vec_reverse ( n, w );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
% Zhou, Zongwei, et al. "Fine-tuning convolutional neural networks for biomedical image analysis: actively and incrementally."
% IEEE conference on computer vision and pattern recognition, Hawaii. 2017.

% Author: [Zongwei Zhou](http://www.zongweiz.com)
% Email: zongweiz@asu.edu
% Last modified: Jan.26.2017

%% Table 1. examples of seven different patterns
% Relationships among seven prediction patterns and six AIFT methods in active candidate selection. We assume that
% a candidate has 11 patches, and their probabilities predicted by the current CNN are listed in Column 2. AIFT Entropyα,
% Diversityα, and (Entropy+Diversity)α operate on the top or bottom α percent of the candidate’s patches based on the majority
% prediction as described in Sec. 3.3. In this illustration, we choose α to be 1/4, meaning that the selection criterion (Eq. 3) is
% computed based on 3 patches within each candidate. The first choice of each method is highlighted in yellow and the second
% choice is in light yellow.

function Alg_Analysis()

close all; clear; clc;

% A, B, C, D, E, F represents outputs from CNN after Softmax Layer belong to one candidate.
A = [0.4 0.4 0.4 0.5 0.5 0.5 0.5 0.5 0.5 0.6 0.6];
B = [0.0 0.1 0.2 0.3 0.4 0.4 0.6 0.7 0.8 1.0 1.0];
C = [0.0 0.0 0.0 0.1 0.1 0.9 0.9 1.0 1.0 1.0 1.0];
D = [1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.9 0.9 0.9 0.9];
E = [0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.1 0.1 0.1 0.1];
F  = [0.0 0.0 0.1 0.1 0.1 0.1 0.2 0.2 0.3 0.9 1.0];
G  = [0.0 0.1 0.7 0.8 0.8 0.9 0.9 0.9 0.9 1.0 1.0];

%% Produce values in Table 1 by row pattern A
disp('Table 1. pattern A');
disp(['Entropy_A = ', num2str(roundn(compute_matrix(A, 1, 0, 1), -2))]);
disp(['Entropy^1/4_A = ', num2str(roundn(compute_matrix(A, 1, 0, 0.25), -2))]);
disp(['Diversity_A = ', num2str(roundn(compute_matrix(A, 0, 1, 1), -2))]);
disp(['Diversity^1/4_A = ', num2str(roundn(compute_matrix(A, 0, 1, 0.25), -2))]);
disp(['(Entropy+Diversity)_A = ', num2str(roundn(compute_matrix(A, 1, 1, 1), -2))]);
disp(['(Entropy+Diversity)^1/4_A = ', num2str(roundn(compute_matrix(A, 1, 1, 0.25), -2))]);
disp(' ');

%% Produce values in Table 1 by row pattern B
disp('Table 1. pattern B');
disp(['Entropy_B = ', num2str(roundn(compute_matrix(B, 1, 0, 1), -2))]);
disp(['Entropy^1/4_B = ', num2str(roundn(compute_matrix(B, 1, 0, 0.25), -2))]);
disp(['Diversity_B = ', num2str(roundn(compute_matrix(B, 0, 1, 1), -2))]);
disp(['Diversity^1/4_B = ', num2str(roundn(compute_matrix(B, 0, 1, 0.25), -2))]);
disp(['(Entropy+Diversity)_B = ', num2str(roundn(compute_matrix(B, 1, 1, 1), -2))]);
disp(['(Entropy+Diversity)^1/4_B = ', num2str(roundn(compute_matrix(B, 1, 1, 0.25), -2))]);
disp(' ');

%% Produce values in Table 1 by row pattern C
disp('Table 1. pattern C');
disp(['Entropy_C = ', num2str(roundn(compute_matrix(C, 1, 0, 1), -2))]);
disp(['Entropy^1/4_C = ', num2str(roundn(compute_matrix(C, 1, 0, 0.25), -2))]);
disp(['Diversity_C = ', num2str(roundn(compute_matrix(C, 0, 1, 1), -2))]);
disp(['Diversity^1/4_C = ', num2str(roundn(compute_matrix(C, 0, 1, 0.25), -2))]);
disp(['(Entropy+Diversity)_C = ', num2str(roundn(compute_matrix(C, 1, 1, 1), -2))]);
disp(['(Entropy+Diversity)^1/4_C = ', num2str(roundn(compute_matrix(C, 1, 1, 0.25), -2))]);
disp(' ');

%% Produce values in Table 1 by row pattern D
disp('Table 1. pattern D');
disp(['Entropy_D = ', num2str(roundn(compute_matrix(D, 1, 0, 1), -2))]);
disp(['Entropy^1/4_D = ', num2str(roundn(compute_matrix(D, 1, 0, 0.25), -2))]);
disp(['Diversity_D = ', num2str(roundn(compute_matrix(D, 0, 1, 1), -2))]);
disp(['Diversity^1/4_D = ', num2str(roundn(compute_matrix(D, 0, 1, 0.25), -2))]);
disp(['(Entropy+Diversity)_D = ', num2str(roundn(compute_matrix(D, 1, 1, 1), -2))]);
disp(['(Entropy+Diversity)^1/4_D = ', num2str(roundn(compute_matrix(D, 1, 1, 0.25), -2))]);
disp(' ');

%% Produce values in Table 1 by row pattern E
disp('Table 1. pattern E');
disp(['Entropy_E = ', num2str(roundn(compute_matrix(E, 1, 0, 1), -2))]);
disp(['Entropy^1/4_E = ', num2str(roundn(compute_matrix(E, 1, 0, 0.25), -2))]);
disp(['Diversity_E = ', num2str(roundn(compute_matrix(E, 0, 1, 1), -2))]);
disp(['Diversity^1/4_E = ', num2str(roundn(compute_matrix(E, 0, 1, 0.25), -2))]);
disp(['(Entropy+Diversity)_E = ', num2str(roundn(compute_matrix(E, 1, 1, 1), -2))]);
disp(['(Entropy+Diversity)^1/4_E = ', num2str(roundn(compute_matrix(E, 1, 1, 0.25), -2))]);
disp(' ');

%% Produce values in Table 1 by row pattern F
disp('Table 1. pattern F');
disp(['Entropy_F = ', num2str(roundn(compute_matrix(F, 1, 0, 1), -2))]);
disp(['Entropy^1/4_F = ', num2str(roundn(compute_matrix(F, 1, 0, 0.25), -2))]);
disp(['Diversity_F = ', num2str(roundn(compute_matrix(F, 0, 1, 1), -2))]);
disp(['Diversity^1/4_F = ', num2str(roundn(compute_matrix(F, 0, 1, 0.25), -2))]);
disp(['(Entropy+Diversity)_F = ', num2str(roundn(compute_matrix(F, 1, 1, 1), -2))]);
disp(['(Entropy+Diversity)^1/4_F = ', num2str(roundn(compute_matrix(F, 1, 1, 0.25), -2))]);
disp(' ');

%% Produce values in Table 1 by row pattern G
disp('Table 1. pattern G');
disp(['Entropy_G = ', num2str(roundn(compute_matrix(G, 1, 0, 1), -2))]);
disp(['Entropy^1/4_G = ', num2str(roundn(compute_matrix(G, 1, 0, 0.25), -2))]);
disp(['Diversity_G = ', num2str(roundn(compute_matrix(G, 0, 1, 1), -2))]);
disp(['Diversity^1/4_G = ', num2str(roundn(compute_matrix(G, 0, 1, 0.25), -2))]);
disp(['(Entropy+Diversity)_G = ', num2str(roundn(compute_matrix(G, 1, 1, 1), -2))]);
disp(['(Entropy+Diversity)^1/4_G = ', num2str(roundn(compute_matrix(G, 1, 1, 0.25), -2))]);
disp(' ');

% %% Visualize the diversity equation
% x = 0:0.01:1;
% y = 0:0.01:1;
% [x,y] = meshgrid(x,y);
% div = (x-y).*log(x./(y+eps))+(y-x).*log((1-x)./(1-y+eps));
% mesh(x,y,div)

end

%% Compute matrix R (Eq. 3 in the paper)
function [S] = compute_matrix(p, lamda_1, lamda_2, alpha)

% lamda_1 and lamda_2 are trade-offs between entropy and diversity
% lamda_1: turn on/off entropy (1 or 0)
% lamda_2: turn on/off diversity (1 or 0)

% Handling noisy labels via majority selection (see Sec 3.3)
top = round(length(p) * alpha);
p = Majority(p,top);

% Initialize the R matrix
R = zeros(length(p));
for i = 1:length(p)
    for j = 1:i
        if i == j % entropy computed for diagonal of R
            R(i,i) = - lamda_1 * (p(i)*log(p(i)+eps)+(1-p(i))*log(1-p(i)+eps));
        else % diversity computed for rest of R
            R(i,j) = lamda_2 * ((p(i)-p(j)) * log((p(i)+eps)/(p(j)+eps)) + ...
                     (1-p(i)-1+p(j)) * log((1-p(i)+eps)/(1-p(j)+eps)));
            R(j,i) = R(i,j);
        end
    end
end

% Compute active selecting value from matrix R for this candidate
% by numerical sum of R (see Alg 1 line 11)
S = sum(R(:));

end

%% Sec 3.3. Handling noisy labels via majority selection
% eq. 4, calculate the mean and sort based on dominate predictions.
function [p] = Majority(p,top)

m = mean(p);
if m > 0.5
    p = sort(p,'descend');
else
    p = sort(p,'ascend');
end
p = p(1:top);

end

author: MrGiovanni

repo: Active-Learning


text:
problemToSolve = 'test2d_triangle';
origin = 'P1';
variable = 'd_u';
projectDestination = 'P1D';


text:
classdef RollAngleTermCondOptimizationVariable < AbstractOptimizationVariable
    %RollAngleTermCondOptimizationVariable Summary of this class goes here
    %   Detailed explanation goes here

    properties
        varObj(1,1) RollTermCondition = RollTermCondition(0);

        lb(1,1) double = 0;
        ub(1,1) double = 0;

        useTf(1,1) = false;
    end

    methods
        function obj = RollAngleTermCondOptimizationVariable(varObj)
            obj.varObj = varObj;
            obj.varObj.optVar = obj;

            obj.id = rand();
        end

        function x = getXsForVariable(obj)
            x = [];

            if(obj.useTf)
                x = obj.varObj.targetRollAngle;
            end
        end

        function [lb, ub] = getBndsForVariable(obj)
            lb = obj.lb(obj.useTf);
            ub = obj.ub(obj.useTf);
        end

        function [lb, ub] = getAllBndsForVariable(obj)
            lb = obj.lb;
            ub = obj.ub;
        end

        function setBndsForVariable(obj, lb, ub)
            obj.lb = lb;
            obj.ub = ub;
        end

        function useTf = getUseTfForVariable(obj)
            useTf = obj.useTf;
        end

        function setUseTfForVariable(obj, useTf)
            obj.useTf = useTf;
        end

        function updateObjWithVarValue(obj, x)
            obj.varObj.targetRollAngle = x;
        end

        function nameStrs = getStrNamesOfVars(obj, evtNum, varLocType)
            nameStrs = {sprintf('Event %i Roll Angle Termination Condition', evtNum)};
        end

        function varsStoredInRad = getVarsStoredInRad(obj)
            varsStoredInRad = true;
        end
    end
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function res = units(this, varargin)
% Method for setting/getting all units, over channels
% FORMAT res = units(this, ind)
% _______________________________________________________________________
% Copyright (C) 2008-2012 Wellcome Trust Centre for Neuroimaging

% Stefan Kiebel
% $Id: units.m 5933 2014-03-28 13:22:28Z vladimir $

if this.montage.Mind == 0
    res = getset(this, 'channels', 'units', varargin{:});
else
    if nargin == 3
        this.montage.M(this.montage.Mind) = getset(this.montage.M(this.montage.Mind), 'channels', 'units', varargin{:});
        res = this;
    else
        res = getset(this.montage.M(this.montage.Mind), 'channels', 'units', varargin{:});
    end
end

author: spm


text:
function value = i4_bit_lo1 ( n )

%*****************************************************************************80
%
%% I4_BIT_LO1 returns the position of the low 1 bit base 2 in an integer.
%
%  Example:
%
%       N    Binary    Lo 1
%    ----    --------  ----
%       0           0     0
%       1           1     1
%       2          10     2
%       3          11     1
%       4         100     3
%       5         101     1
%       6         110     2
%       7         111     1
%       8        1000     4
%       9        1001     1
%      10        1010     2
%      11        1011     1
%      12        1100     3
%      13        1101     1
%      14        1110     2
%      15        1111     1
%      16       10000     5
%      17       10001     1
%    1023  1111111111     1
%    1024 10000000000    11
%    1025 10000000001     1
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 November 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the integer to be measured.
%    N should be nonnegative.
%
%    Output, integer I4_BIT_LO1, the position of the low 1 bit.
%
  bit = 0;
  i = n;

  while ( 1 )

    bit = bit + 1;
    i2 = floor ( i / 2 );

    if ( i ~= 2 * i2 )
      break
    end

    i = i2;

  end

  value = bit;

  return
end


text:
function view = initHiddenFlat(subdir)
%
%  hiddenFlat = initHiddenFlat([subdir])
%
% subdir: string specifying the flat subdirectory
%
% ras, 2004: made it
% ras, 04/05, set name to 'hidden'
% ras, 05/05, added curScan field
disp('Initializing HIDDEN Flat view')
% Set viewType
view.name='hidden';
view.viewType='Flat';
% Prompt user for flat subdirectory
if ~exist('subdir','var')
    subdir = getFlatSubdir;
end
view.subdir = subdir;
% Initialize slots for co, amp, and ph
view.co = [];
view.amp = [];
view.ph = [];
view.map = [];
view.mapName = '';
view.mapUnits = '';
% Initialize slots for tSeries
view.tSeries = [];
view.tSeriesScan = NaN;
view.tSeriesSlice = NaN;
% Initialize ROIs
view.ROIs = [];
view.selectedROI = 0;
% Initialize curDataType
view.curDataType = 1;
% Initialize curScan
view.curScan = 1;
% Compute/load coords
view = getFlatLevelCoords(view);
return;

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function J = jacobian(f, g, h)
%JACOBIAN   Jacobian determinant of three CHEBFUN3 objects.
%   J = JACOBIAN(F,G,H) returns the determinant of the Jacobian matrix.
%
%   Note we return the determinant of the Jacobian matrix and not the
%   Jacobian matrix itself.
%
% See also CHEBFUN3V/JACOBIAN.

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

% Empty check:
if ( isempty(f) || isempty(g) || isempty(h))
    J = [];
    return
end

% Call CHEBFUN3V/JACOBIAN():
J = jacobian(chebfun3v({f, g, h}));

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


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

% Last Modified by GUIDE v2.5 11-Oct-2011 22:48:12

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

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

% --- Executes just before MDOF_vibration_calculator3 is made visible.
function MDOF_vibration_calculator3_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 MDOF_vibration_calculator3 (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);
global CC
CC = 0;
initial_function(hObject, eventdata, handles)
% UIWAIT makes MDOF_vibration_calculator3 wait for user response (see UIRESUME)
% uiwait(handles.figure1);

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

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

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

AcquiringData(hObject, eventdata, handles);
Calculating_Modal_Equation(hObject, eventdata, handles)
[z,wn,f0,wdr,x0,v0] = Definding_Modal_Equa_values(hObject, eventdata, handles);
Displaying_Modal_Equation(z,wn,f0,wdr,x0,v0,hObject, eventdata, handles);
Calculation_XDisplacement(hObject, eventdata, handles);
% Displaying_XDisplacement(hObject, eventdata, handles)
Plotting_XT(hObject, eventdata, handles)
Plotting_RT(hObject, eventdata, handles)

function Animation_2mass(hObject, eventdata, handles)
global XT t CC

axes(handles.axes1);    cla(handles.axes1);
set(handles.pushbutton3, 'string','Stop');
    if CC == 0
        CC = 1;
    else
        CC = 0;
    end
posx=[0.5 -0.5 -0.5 0.5];
posy=[0.5 0.5 -0.5 -0.5];
h1=line(0,0);

line([-5 10],[-0.5 -0.5],'color','k','linewidth',2);%base line
line([0 0],[-0.5 5],'color','k','linewidth',2); %a wall on left
block1=patch(posx,posy,'y');
block2=patch(posx,posy,'g');

axes(handles.axes1);
axis([0 10 -1 1]);
Ratio = 1/max(max(abs(XT)));
xini = [3; 6];
for i = 1 : length(t)
            if ishandle(h1) == 0 || CC  == 0
                set(handles.pushbutton3, 'string','Play');
                cla(handles.axes1);
                break
            else
                Movx1 = xini(1) + Ratio * XT(1,i);
                Movx2 = xini(2) + Ratio * XT(2,i);
                set(h1,'xdata',[0 Movx1-0.5 Movx2-0.5],'ydata',[0 0 0]);
                set(block1,'xdata', posx + Movx1, 'ydata', posy);
                set(block2,'xdata', posx + Movx2, 'ydata', posy);

               pause(0.015);
            end
end
CC = 0;
set(handles.pushbutton3, 'string','Play');

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

function Plotting_RT(hObject, eventdata, handles)
global t RT
plot(handles.axes2,t, RT);legend(handles.axes2,'r_1(t)','r_2(t)');
xlabel(handles.axes2,'Time, t'); ylabel(handles.axes2,'Displacement')

function Plotting_XT(hObject, eventdata, handles)
global t XT
plot(handles.axes3,t, XT);legend(handles.axes3,'x_1(t)','x_2(t)');
xlabel(handles.axes3,'Time, t'); ylabel(handles.axes3,'Displacement')

% function Displaying_XDisplacement(hObject, eventdata, handles)
% global S func
%
% switch func
%     case 1
%             R1 = get(handles.text10,'string');
%             R2 = get(handles.text11,'string');
%             R1a = str2num(R1(11:15)); R1b = R1(16:35);
%             R2a = str2num(R2(11:15)); R2b = R2(16:35);
%
%             X11 = S(1,1)*R1a;       X12 = S(1,2)*R2a;
%             X21 = S(2,1)*R1a;       X22 = S(2,2)*R2a;
%
%             set(handles.text14, 'string',['']);
%     case 2
%         set(handles.text14,'string','  Sorry ');
%         set(handles.text15,'string','  Sorry ');
%     case 3
%         set(handles.text14,'string','  Sorry ');
%         set(handles.text15,'string','  Sorry ');
% end

% set(handles.text14,'string','')
% set(handles.text15,'string','')

function Calculation_XDisplacement(hObject, eventdata, handles)
global RT S XT
XT = S*RT;

function Displaying_Modal_Equation(z,wn,f0,wdr,x0,v0, hObject, eventdata, handles)
global M t func RT S
zz = z*0.5./wn; wwn = wn; wwdr = wdr; xx0 = x0; vv0 = v0; ff0 = f0;
RT = zeros(length(M),length(t));

for i = 1 : length(M)
    z = zz(i);    wn = wwn(i);     wdr = wwdr(i);
    x0 = xx0(i);     v0 = vv0(i);     f0 = ff0(i);
%     z,wn,wdr,x0,v0,f0

    switch func
        case 1      % func 1 : F0 = 0
                    if z >= 1
                        warndlg('This is not underdamp system because ...the damping ratio is larger than 1. Please insert the value correctly.');
                        %XT = 0*t;
                    else
                        wd = wn*sqrt(1-z^2);
                        X     = f0/sqrt((wn^2 - wdr^2)^2 + (2*z*wn*wdr)^2);
                        Theta = atan(2*z*wn*wdr/(wn^2 - wdr^2));
                        Phi = atan((wd*(x0 - X*cos(Theta)))/(v0 + (x0 - X*cos(Theta))*z*wn - wdr*X*sin(Theta)));
                        A     = (x0 - X*cos(Theta))/sin(Phi);
                        RT(i,:) = A*exp(-z*wn*t).*sin(wd*t + Phi) + X*cos(wdr*t - Theta);
                        if i == 1
                            if z == 0
                                set(handles.text10, 'string',['  r1(t) = ',sprintf('%4.3f',A),...
                            ' sin(',sprintf('%4.3f',wd),...
                            't + ',sprintf('%4.3f',Phi),')']);
                            else
                            set(handles.text10, 'string',['  r1(t) = ',sprintf('%4.3f',A),...
                            'exp(',sprintf('%4.3f',-z*wn),'t) sin(',sprintf('%4.3f',wd),...
                            't + ',sprintf('%4.3f',Phi),')']);
                            end
                        else
                            if z == 0
                                set(handles.text11, 'string',['  r2(t) = ',sprintf('%4.3f',A),...
                            ' sin(',sprintf('%4.3f',wd),...
                            't + ',sprintf('%4.3f',Phi),')']);
                            else
                            set(handles.text11, 'string',['  r2(t) = ',sprintf('%4.3f',A),...
                            'exp(',sprintf('%4.3f',-z*wn),'t) sin(',sprintf('%4.3f',wd),...
                            't + ',sprintf('%4.3f',Phi),')']);
                            end
                        end
                    end
        case 2      % func 1 : F0 cos wt
                    wd = wn*sqrt(1-z^2);

                    X     = f0/sqrt((wn^2 - wdr^2)^2 + (2*z*wn*wdr)^2);
                    Theta = atan(2*z*wn*wdr/(wn^2 - wdr^2));
                    Phi = atan((wd*(x0 - X*cos(Theta)))/(v0 + (x0 - X*cos(Theta))*z*wn - wdr*X*sin(Theta)));
                    A     = (x0 - X*cos(Theta))/sin(Phi);
                    RT(i,:) = A*exp(-z*wn*t).*sin(wd*t + Phi) + X*cos(wdr*t - Theta);
                    if i ==1
                        if z == 0
                            set(handles.text10, 'string',['  r1(t) = ',sprintf('%4.3f',A),...
                            ' sin(', sprintf('%4.3f',wd),'t + ',...
                            sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',X),'cos(',sprintf('%4.3f',wdr),...
                            't - ',sprintf('%4.3f',Theta),')']);
                        else
                            set(handles.text10, 'string',['  r1(t) = ',sprintf('%4.3f',S(1,1)*A),'exp(',...
                            sprintf('%4.3f',-z*wn),'t) sin(', sprintf('%4.3f',wd),'t + ',...
                            sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',X),'cos(',sprintf('%4.3f',wdr),...
                            't - ',sprintf('%4.3f',Theta),')']);
                         end
                    else
                        if z == 0
                             set(handles.text11, 'string',['  r2(t) = ',sprintf('%4.3f',A),...
                            ' sin(', sprintf('%4.3f',wd),'t + ',...
                            sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',X),'cos(',sprintf('%4.3f',wdr),...
                            't - ',sprintf('%4.3f',Theta),')']);
                        else
                            set(handles.text11, 'string',['  r2(t) = ',sprintf('%4.3f',A),'exp(',...
                            sprintf('%4.3f',-z*wn),'t) sin(', sprintf('%4.3f',wd),'t + ',...
                            sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',X),'cos(',sprintf('%4.3f',wdr),...
                            't - ',sprintf('%4.3f',Theta),')']);
                        end
                    end

        case 3      % func 1 : F0 sin wt
                    wd    = wn*sqrt(1-z^2);
                    T     = f0/sqrt((wn^2 - wdr^2)^2 + (2*z*wn*wdr)^2);
                    X     = f0/((wn^2 - wdr^2)^2 + (2*z*wn*wdr)^2);
                    Theta = atan(2*z*wn*wdr/(wn^2 - wdr^2));
                    Phi   = atan((wd*(x0 + X*cos(Theta)))/(v0 + (x0 + X*cos(Theta))*z*wn + wdr*X*sin(Theta)));
                    A     = (x0 + X*cos(Theta))/sin(Phi);
                    RT(i,:)    = A*exp(-z*wn*t).*sin(wd*t + Phi) + T*sin(wdr*t + Theta);
                    if i == 1
                        if z == 0
                            set(handles.text10, 'string',['  r1(t) = ',sprintf('%4.3f',A),...
                            ' sin(', sprintf('%4.3f',wd),'t + ',...
                            sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',T),'sin(',sprintf('%4.3f',wdr),...
                            't + ',sprintf('%4.3f',Theta),')']);
                        else
                         set(handles.text10, 'string',['  r1(t) = ',sprintf('%4.3f',A),'exp(',...
                            sprintf('%4.3f',-z*wn),'t) sin(', sprintf('%4.3f',wd),'t + ',...
                            sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',T),'sin(',sprintf('%4.3f',wdr),...
                            't + ',sprintf('%4.3f',Theta),')']);
                        end
                    else
                        if z == 0
                            set(handles.text11, 'string',['  r2(t) = ',sprintf('%4.3f',A),' sin(', sprintf('%4.3f',wd),'t + ',...
                            sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',T),'sin(',sprintf('%4.3f',wdr),...
                            't + ',sprintf('%4.3f',Theta),')']);
                        else
                        set(handles.text11, 'string',['  r2(t) = ',sprintf('%4.3f',A),'exp(',...
                            sprintf('%4.3f',-z*wn),'t) sin(', sprintf('%4.3f',wd),'t + ',...
                            sprintf('%4.3f',Phi),') + ',sprintf('%4.3f',T),'sin(',sprintf('%4.3f',wdr),...
                            't + ',sprintf('%4.3f',Theta),')']);
                        end
                    end
    end
end

function [z,wn,f0,wdr,x0,v0] = Definding_Modal_Equa_values(hObject, eventdata, handles)

global M B F0 w wn
global  PCMP PKMP  S Sinv

x0 = str2num(get(handles.edit9,'string'));
v0 = str2num(get(handles.edit10,'string'));

% x0, v0,
% Intial value of modal equation
r0 = Sinv*x0;       x0 = r0;
rdot0 = Sinv*v0;    v0 = rdot0;
zz = diag(PCMP);

% Define each of modal equation value

for i = 1 : length(M)
    z(i) = zz(i);
    wn(i) = sqrtm(PKMP(i,i));
    FF = S'*B.*F0;
    f0(i) = FF(i,2);
    wdr(i) = w;
end
z = z'; f0 = f0'; wdr = wdr';
%  r0, rdot0, f0, F0,z,wn,wdr

function Calculating_Modal_Equation(hObject, eventdata, handles)

global M C K
global CM PCMP KM PKMP U S Sinv wn

Minvsquare = inv(chol(M));
KM = Minvsquare*K*Minvsquare;
CM = Minvsquare*C*Minvsquare;
U = chol(M);
[P,lam] = eig(U'\K/U);
[w,k]   = sort(sqrt(diag(lam)));
P = P(:,k);
    for i = 1:length(M)
      if P(1,i) < 0
         P(:,i) = -P(:,i);
      end
    end
PKMP = P'*KM*P;
PCMP = P'*CM*P;
S = U\P;    Sinv = inv(S);  wn = w;
% S,Sinv,U,PKMP,PCMP, wn

function AcquiringData(hObject, eventdata, handles)

global M C K B F0 w t x0 v0

M = str2num(get(handles.edit1,'string'));
C = str2num(get(handles.edit2,'string'));
K = str2num(get(handles.edit3,'string'));
B = str2num(get(handles.edit4,'string'));
F0 = str2num(get(handles.edit5,'string'));
w  = str2num(get(handles.edit6,'string'));
t0 = str2num(get(handles.edit7,'string'));
tf = str2num(get(handles.edit8,'string'));
x0 = str2num(get(handles.edit9,'string'));
v0 = str2num(get(handles.edit10,'string'));

t  = t0:0.05:tf;
if size(C) ~= size(M)
    warndlg('Please check matrix size of M, C, K')
end

% M, C, K, B, F0, w, t, x0, v0

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

switch get(hObject,'Value')
    case 1
            func = 1;
            set(handles.edit5,'string',0);set(handles.edit5,'enable','off');
            set(handles.edit6,'string',0);set(handles.edit6,'enable','off');
    case 2
            func = 2;
            set(handles.edit5,'enable','on');
            set(handles.edit6,'enable','on');
    case 3
            func = 3;
            set(handles.edit5,'enable','on');
            set(handles.edit6,'enable','on');
end

function initial_function(hObject, eventdata, handles)
global func
        func = 1;
        set(handles.edit5,'string',0);set(handles.edit5,'enable','off');
        set(handles.edit6,'string',0);set(handles.edit6,'enable','off');
        set(handles.popupmenu1,'value',1);
        set(handles.axes1,'visible','off');

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

set(handles.edit1,'string','[3 0 ; 0 1]');
set(handles.edit2,'string','[0 0 ; 0 0]');
set(handles.edit3,'string','[3 -1 ; -1 3]');
set(handles.edit4,'string','[0 0 ; 0 1]');
set(handles.edit5,'string','1');set(handles.edit5,'enable','on');
set(handles.edit6,'string','1');set(handles.edit6,'enable','on');
set(handles.edit9,'string','[1;0]');
set(handles.edit10,'string','[0;0]');
set(handles.popupmenu1,'value',1);
 func = 1;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

author: Sable

repo: mcbench-benchmarks


text:
function isMatchAll = eval_match_parts_gt(endpointsAll, annolist, sc, evlType, factor, nPartsEval)

fprintf('eval_match_parts_gt()\n');

if ischar(annolist)
    annolist = loadannotations(annolist);
end

if (nargin < 5)
    factor = 0.5;
end

if (nargin < 4)
    evlType = 1;
end

if (nargin < 5)
    nPartsEval = 10;
end

if (nPartsEval > 10)
    [~, parts] = util_get_parts_spatial();
else
    [~, parts] = util_get_parts();
end

if (evlType == 2)
    mean_part_length = eval_compute_mean_part_length(annolist,parts);
end

isMatchAll = nan(length(annolist),length(parts));

for imgidx = 1:length(annolist)
    fprintf('.');
    rect = annolist(imgidx).annorect(1);
    points = rect.annopoints.point;
    endpoints = endpointsAll{imgidx};

    if (isempty(endpoints))
        for pidx = 1:length(parts)
            p1 = util_get_annopoint_by_id(points,parts(pidx).xaxis(2));
            p2 = util_get_annopoint_by_id(points,parts(pidx).xaxis(1));
            if (~isempty(p1) && ~isempty(p2))
                isMatchAll(imgidx,pidx) = 0;
            end
        end
    else
        for pidx = 1:length(parts)
            p1 = util_get_annopoint_by_id(points,parts(pidx).xaxis(2));
            p2 = util_get_annopoint_by_id(points,parts(pidx).xaxis(1));

            detBottom = [endpoints(pidx,1) endpoints(pidx,2)];
            detTop    = [endpoints(pidx,3) endpoints(pidx,4)];

            if (~isempty(p1) && ~isempty(p2))
                gtBottom = sc*[p1.x p1.y];
                gtTop    = sc*[p2.x p2.y];

                distBottom = norm(detBottom - gtBottom);
                distTop    = norm(detTop   - gtTop);

                if (evlType == 1) % standard pcp
                    % use part size
                    gtScale = norm(gtBottom - gtTop);
                elseif (evlType == 2) % pcp with fixed thresh
                    % use mean part length
                    gtScale = sc*mean_part_length(pidx);
                end

                bIsGTmatch = is_gt_match_pcp(distBottom, distTop, factor, gtScale);
                isMatchAll(imgidx,pidx) = bIsGTmatch;
            end
        end
    end
    if (~mod(imgidx, 100))
        fprintf(' %d/%d\n',imgidx,length(annolist));
    end
end
fprintf('\ndone\n');

    function res = is_gt_match_pcp(distBottom, distTop, factor, gtLen)
        res = distBottom <= gtLen*factor && distTop <= gtLen*factor;
    end

end

author: eldar

repo: deepcut

save_path: github-repos/MATLAB/eldar-deepcut