text:
classdef ( Hidden ) Divider < matlab.mixin.SetGet
    %uix.Divider  Draggable divider
    %
    %  d = uix.Divider() creates a divider.
    %
    %  d = uix.Divider(p1,v1,p2,v2,...) creates a divider and sets
    %  specified property p1 to value v1, etc.

    %  Copyright 2009-2016 The MathWorks, Inc.
    %  $Revision: 1601 $ $Date: 2018-05-01 10:22:53 +0100 (Tue, 01 May 2018) $

    properties( Dependent )
        Parent % parent
        Units % units [inches|centimeters|characters|normalized|points|pixels]
        Position % position
        Visible % visible [on|off]
        BackgroundColor % background color [RGB]
        HighlightColor % border highlight color [RGB]
        ShadowColor % border shadow color [RGB]
        Orientation % orientation [vertical|horizontal]
        Markings % markings [pixels]
    end

    properties( Access = private )
        Control % uicontrol
        BackgroundColor_ = get( 0, 'DefaultUicontrolBackgroundColor' ) % backing for BackgroundColor
        HighlightColor_ = [1 1 1] % backing for HighlightColor
        ShadowColor_ = [0.7 0.7 0.7] % backing for ShadowColor
        Orientation_ = 'vertical' % backing for Orientation
        Markings_ = zeros( [0 1] ) % backing for Markings
        SizeChangedListener % listener
    end

    methods

        function obj = Divider( varargin )
            %uix.Divider  Draggable divider
            %
            %  d = uix.Divider() creates a divider.
            %
            %  d = uix.Divider(p1,v1,p2,v2,...) creates a dividerand sets
            %  specified property p1 to value v1, etc.

            % Create control
            control = matlab.ui.control.UIControl( ...
                'Style', 'checkbox', 'Internal', true, ...
                'Enable', 'inactive', 'DeleteFcn', @obj.onDeleted,...
                'Tag', 'uix.Divider' );

            % Store control
            obj.Control = control;

            % Set properties
            try
                uix.set( obj, varargin{:} )
            catch e
                delete( obj )
                e.throwAsCaller()
            end

            % Force update
            obj.update()

            % Create listener
            sizeChangedListener = event.listener( control, 'SizeChanged', ...
                @obj.onSizeChanged );

            % Store listener
            obj.SizeChangedListener = sizeChangedListener;

        end % constructor

        function delete( obj )
            %delete  Destructor

            control = obj.Control;
            if isgraphics( control ) && strcmp( control.BeingDeleted, 'off' )
                delete( control )
            end

        end % destructor

    end % structors

    methods

        function value = get.Parent( obj )

            value = obj.Control.Parent;

        end % get.Parent

        function set.Parent( obj, value )

            obj.Control.Parent = value;

        end % set.Parent

        function value = get.Units( obj )

            value = obj.Control.Units;

        end % get.Units

        function set.Units( obj, value )

            obj.Control.Units = value;

        end % set.Units

        function value = get.Position( obj )

            value = obj.Control.Position;

        end % get.Position

        function set.Position( obj, value )

            obj.Control.Position = value;

        end % set.Position

        function value = get.Visible( obj )

            value = obj.Control.Visible;

        end % get.Visible

        function set.Visible( obj, value )

            obj.Control.Visible = value;

        end % set.Visible

        function value = get.BackgroundColor( obj )

            value = obj.BackgroundColor_;

        end % get.BackgroundColor

        function set.BackgroundColor( obj, value )

            % Check
            assert( isa( value, 'double' ) && ...
                isequal( size( value ), [1 3] ) && ...
                all( value >= 0 ) && all( value <= 1 ), ...
                'uix:InvalidArgument', ...
                'Property ''BackgroundColor'' must be a valid colorspec.' )

            % Set
            obj.BackgroundColor_ = value;

            % Update
            obj.update()

        end % set.BackgroundColor

        function value = get.HighlightColor( obj )

            value = obj.HighlightColor_;

        end % get.HighlightColor

        function set.HighlightColor( obj, value )

            % Check
            assert( isnumeric( value ) && isequal( size( value ), [1 3] ) && ...
                all( isreal( value ) ) && all( value >= 0 ) && all( value <= 1 ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''HighlightColor'' must be an RGB triple.' )

            % Set
            obj.HighlightColor_ = value;

            % Update
            obj.update()

        end % set.HighlightColor

        function value = get.ShadowColor( obj )

            value = obj.ShadowColor_;

        end % get.ShadowColor

        function set.ShadowColor( obj, value )

            % Check
            assert( isnumeric( value ) && isequal( size( value ), [1 3] ) && ...
                all( isreal( value ) ) && all( value >= 0 ) && all( value <= 1 ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''ShadowColor'' must be an RGB triple.' )

            % Set
            obj.ShadowColor_ = value;

            % Update
            obj.update()

        end % set.ShadowColor

        function value = get.Orientation( obj )

            value = obj.Orientation_;

        end % get.Orientation

        function set.Orientation( obj, value )

            % Check
            assert( ischar( value ) && ismember( value, ...
                {'horizontal','vertical'} ) )

            % Set
            obj.Orientation_ = value;

            % Update
            obj.update()

        end % set.Orientation

        function value = get.Markings( obj )

            value = obj.Markings_;

        end % get.Markings

        function set.Markings( obj, value )

            % Check
            assert( isa( value, 'double' ) && ndims( value ) == 2 && ...
                size( value, 2 ) == 1 && all( isreal( value ) ) && ...
                all( ~isinf( value ) ) && all( ~isnan( value ) ) && ...
                all( value > 0 ), 'uix:InvalidPropertyValue', ...
                'Property ''Markings'' must be a vector of positive values.' ) %#ok<ISMAT>

            % Set
            obj.Markings_ = value;

            % Update
            obj.update()

        end % set.Markings

    end % accessors

    methods

        function tf = isMouseOver( obj, eventData )
            %isMouseOver  Test for mouse over
            %
            %  tf = d.isMouseOver(wmd) tests whether the WindowMouseData
            %  wmd is consistent with the mouse pointer being over the
            %  divider d.
            %
            %  This method returns false for dividers that are being
            %  deleted.

            tf = isvalid( obj ); % initialize
            for ii = 1:numel( obj )
                tf(ii) = tf(ii) && obj(ii).Control == eventData.HitObject;
            end

        end % isMouseOver

    end % methods

    methods( Access = private )

        function onDeleted( obj, ~, ~ )
            %onDeleted  Event handler

            % Call destructor
            obj.delete()

        end % onDeleted

        function onSizeChanged( obj, ~, ~ )
            %onSizeChanged  Event handler

            % Update
            obj.update()

        end % onSizeChanged

    end % event handlers

    methods( Access = private )

        function update( obj )
            %update  Update divider
            %
            %  d.update() updates the divider markings.

            % Get properties
            control = obj.Control;
            position = control.Position;
            backgroundColor = obj.BackgroundColor;
            highlightColor = obj.HighlightColor;
            shadowColor = obj.ShadowColor;
            orientation = obj.Orientation;
            markings = obj.Markings;

            % Assemble mask
            mask = zeros( floor( position([4 3]) ) - [1 1] ); % initialize
            switch orientation
                case 'vertical'
                    markings(markings < 4) = [];
                    markings(markings > position(4)-6) = [];
                    for ii = 1:numel( markings )
                        marking = markings(ii);
                        mask(floor( marking ) + [-3 0 3],1:end-1) = 1;
                        mask(floor( marking ) + [-2 1 4],1:end-1) = 2;
                    end
                case 'horizontal'
                    markings(markings < 4) = [];
                    markings(markings > position(3)-6) = [];
                    for ii = 1:numel( markings )
                        marking = markings(ii);
                        mask(2:end,floor( marking ) + [-3 0 3]) = 1;
                        mask(2:end,floor( marking ) + [-2 1 4]) = 2;
                    end
            end

            % Assemble color data
            cData1 = repmat( backgroundColor(1), size( mask ) );
            cData1(mask==1) = highlightColor(1);
            cData1(mask==2) = shadowColor(1);
            cData2 = repmat( backgroundColor(2), size( mask ) );
            cData2(mask==1) = highlightColor(2);
            cData2(mask==2) = shadowColor(2);
            cData3 = repmat( backgroundColor(3), size( mask ) );
            cData3(mask==1) = highlightColor(3);
            cData3(mask==2) = shadowColor(3);
            cData = cat( 3, cData1, cData2, cData3 );

            % Set properties
            control.ForegroundColor = backgroundColor;
            control.BackgroundColor = backgroundColor;
            control.CData = cData;

        end % update

    end % methods

end % classdef

author: goGPS-Project


text:
function vol=smoothbinvol(vol,layer)
%
% vol=smoothbinvol(vol,layer)
%
% perform a memory-limited 3D image smoothing
%
% author: Qianqian Fang <q.fang at neu.edu>
%
% input:
%     vol: a 3D volumetric image to be smoothed
%     layer: number of iterations for the smoothing
%
% output:
%     vol: the volumetric image after smoothing
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

dim=size(vol);
dxy=dim(1)*dim(2);
fulllen=prod(dim);

weight=1./6.;
step=4000;

% in case vol is a logical
vol=double(vol);
offs=[1,-1,dim(1), -dim(1),dxy, -dxy];

for i=1:layer
  % find all non-zero values
  idx=find(vol);
  % get the neighbors of all the non-zero values
  % this may cause wrapping -- TODO
  val=vol(idx);
  for k=1:6
    nextidx=idx+offs(k);
    % find all 1-valued voxels that are located within the domain
	  goodidx=find(nextidx>0 & nextidx<fulllen);
    % for all neighboring voxels, add a fraction from the non-0 voxels
    % problematic when running in parallel (racing)
    len=length(goodidx);
    % control granualarity with step
    if(len>step)
        for j=1:step:len-step
            vol(nextidx(goodidx(j:j+step-1)))=vol(nextidx(goodidx(j:j+step-1)))+weight*val(goodidx(j:j+step-1));
        end
        vol(nextidx(goodidx(j+step:end)))=vol(nextidx(goodidx(j+step:end)))+weight*val(goodidx(j+step:end));
    else
        vol(nextidx(goodidx))=vol(nextidx(goodidx))+weight*val(goodidx);
    end
    % the above line may change the values of the non-zero voxels, recover
    % them
  end
  vol(idx)=val;
end

author: fangq


text:
% Generate a set of covariance matrices according to a Wishart distrib.
% Inputs :
%   N : the size of the matrices
%   I : the number of matrices
%   Df : the degee of freedom
%   Sig : the parameter of the wishart disrib
%
% Outputs :
%   COV : a set of I covariance matrices
%   Sig : the parameter of the wishart disrib
function [COV Sig] = generate_wishart_set(N,I,Df,Sig)

    if nargin<4
        [Q,~] = qr(randn(N));
        Sig = Q'*diag(5*rand(N,1))*Q;
    end

    COV = zeros(N,N,I);
    for i=1:I
        COV(:,:,i) = wishrnd(Sig,Df);
    end

author: alexandrebarachant

repo: covariancetoolbox


text:
function [c] = cov(x, varargin)

% [C] = COV(X, NORMALIZEFLAG, DIM) computes the covariance, across all cells in x along
%        the dimension dim. W
% [C] = COV(X, Y, NORMALIZEFLAG, DIM) computes the covariance between all cells in x and y
%
% X (and Y) should be linear cell-array(s) of matrices for which the size in at
% least one of the dimensions should be the same for all cells

if numel(varargin)==0
  normalizeflag = 0;
  dim           = [];
  flag          = 0;
end

if numel(varargin)>=1 && iscell(varargin{1})
  y        = varargin{1};
  varargin = varargin(2:end);
else
  y = [];
end

if numel(varargin)>=1 && isempty(varargin{1})
  normalizeflag = 0;
  varargin      = varargin(2:end);
elseif numel(varargin)>=1
  normalizeflag = varargin{1};
  varargin      = varargin(2:end);
end

if numel(varargin)>=1
  dim      = varargin{1};
  varargin = varargin(2:end);
end

if numel(varargin>=1)
  flag = varargin{1};
else
  flag = 1;
end

if isempty(dim)
  [scx1, scx2] = size2(x, [], 'cell');
  if     all(scx1==scx1(1)), dim = 2;
  elseif all(scx2==scx2(1)), dim = 1; %let second dimension prevail
  else   error('no dimension to compute covariance for');
  end
end

nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1)
  error('incorrect input for cellcov');
end

nx   = max(nx);
nsmp = cellfun('size', x, dim);
n    = sum(nsmp);
if isempty(y)
  for k = 1:nx
    [tmp1, tmp2] = covc(x{k}, dim);
    if k==1
      C = tmp1;
      M = tmp2;
    else
      C = C + tmp1;
      M = M + tmp2;
    end
  end
  Mx = M;
  My = M;
else
  for k = 1:nx
    [tmp1, tmp2, tmp3] = covc(x{k}, y{k}, dim);
    if k==1
      C  = tmp1;
      Mx = tmp2;
      My = tmp3;
    else
      C  = C  + tmp1;
      Mx = Mx + tmp2;
      My = My + tmp3;
    end
  end
end

if normalizeflag || n==1
  % normalize by n
  n1 = n;
  n2 = n;
else
  % normalize by n-1
  n1 = n;
  n2 = n-1;
end

if flag
  c = (C-(Mx(:)*My(:)')./n1)./n2;
else
  c = C./n2;
end

function [c,mx,my] = covc(x, y, dim)

if nargin==2
  dim = y;
  y   = x;
end

if islogical(x), x = double(x); end
if islogical(y), y = double(y); end

if dim==1
  c  = x'*y;
elseif dim==2
  c = x*y';
end

mx = sum(x,dim);
my = sum(y,dim);

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
% DEMO6 - Gratuitis ncdataset demo showing AUV path

echo('on')
% Starting DEMO6 ----------------------------------------------------------
% Gratuitis demo showing AUV path
%% ---- open datset
nav = ncdataset('http://dods.mbari.org/cgi-bin/nph-nc/data/ssdsdata/ssds/generated/netcdf/files/ssds.shore.mbari.org/auvbi/missionlogs/2009/2009173/2009.173.03/navigation.nc');
y = nav.data('mPos_y');
x = nav.data('mPos_x');
z = nav.data('mDepth');
%% ---- 3d plot of AUV location
plot3(x, y, z, '.')
set(gca, 'ZDir', 'reverse')
axis('equal')
grid('on')
xlabel('meters')
ylabel('meters')
zlabel('meters')
title({'Gratuitis demo showing AUV path',nav.location})
echo('off') % Ending DEMO6 ------------------------------------------------

author: nctoolbox

repo: nctoolbox

save_path: github-repos/MATLAB/nctoolbox-nctoolbox


text:
function SO3VF = approximation(nodes, values, varargin)
%
% Syntax
%   SO3VF = SO3VectorFieldHarmonic.approximation(nodes, values)
%   SO3VF = SO3VectorFieldHarmonic.approximation(nodes, values, 'bandwidth', bw)
%
% Input
%   nodes - @rotation
%   values - @vector3d
%
% Output
%   SO3VF - @SO3VectorFieldHarmonic
%
% Options
%   bandwidth - maximal degree of the Wigner-D functions (default: 128)
%

% TODO: This method uses the very expensive approximation method

SO3F = SO3FunHarmonic.approximation(nodes(:),values.xyz,varargin{:});

SO3VF = SO3VectorFieldHarmonic(SO3F);

end

author: mtex-toolbox

repo: mtex

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


text:
function [favar]=favar_fevdols(gamma_record,It,Bu,n,IRFperiods,FEVDband,favar)

% function [fevd_estimates]=bear.olsfevd(irf_estimates,IRFperiods,gamma,n,endo,datapath)
% computes and displays fevd values for the OLS VAR model
% inputs:  - cell 'irf_estimates': lower bound, point estimates, and upper bound for the IRFs
%          - integer 'IRFperiods': number of periods for IRFs
%          - matrix 'gamma': structural disturbance variance-covariance matrix (defined p 48 of technical guide)
%          - integer 'n': number of endogenous variables in the BVAR model (defined p 7 of technical guide)
%          - cell 'endo': list of endogenous variables of the model
%          - string 'datapath': user-supplied path to excel data spreadsheet
% outputs: - cell 'fevd_estimates': lower bound, point estimates, and upper bound for the FEVD

% preliminary tasks
npltX=favar.npltX;
npltXshck=favar.IRF.npltXshck;

%relevant loadings of restricted information variables
L=favar.L(favar.plotX_index,favar.IRF.plotXshock_index);
% gamma=gamma(:,favar.FEVD.plotXshock_index);
% % scale gamma, irf estimates are already scaled
%         for ii=1:npltX
%             for ll=1:npltXshck
%                 favar_gamma{ii}(:,ll)=L(ii,ll)*gamma(:,ll);
%             end
%         end

% create the first cell
temp=cell(npltX,npltXshck+1);

% start by filling the first column of every Tij matrix in the cell
% loop over rows of temp
for jj=1:npltX
   % loop over columns of temp
   for ii=1:npltXshck
   % square each element
   temp{jj,ii}(:,1)=favar.IRF.favar_irf_estimates{jj,ii}(:,1).^2;
   end
end
% fill all the other entries of the Tij matrices
% loop over rows of temp
for jj=1:npltX
   % loop over columns of temp
   for ii=1:npltXshck
      % loop over remaining columns
      for kk=2:IRFperiods
      % define the column as the square of the corresponding column in orthogonalised_irf_record
      % additioned to the value of the preceeding columns, which creates the cumulation
      temp{jj,ii}(:,kk)=favar.IRF.favar_irf_estimates{jj,ii}(:,kk).^2+temp{jj,ii}(:,kk-1);
      end
   end
end

% multiply each matrix in the cell by the variance of the structural shocks
% to do so, loop over simulations (rows of the Tij matrices)
for kk=1:It-Bu
% recover the covariance matrix of structural shocks gamma for this iteration
gamma=reshape(gamma_record(:,kk),n,n);

gamma=gamma(:,favar.IRF.plotXshock_index);
% scale gamma, irf estimates are already scaled
        for ii=1:npltX
            for ll=1:npltXshck
                favar_gamma{ii}(:,ll)=L(ii,ll)*gamma(:,ll);
            end
        end

% loop over rows of temp
for ii=1:npltX
% loop over columns of temp
   for jj=1:npltXshck
   % multiply column jj of the matrix by the variance of the structural shock
   temp{ii,jj}(1,:)=temp{ii,jj}(1,:)*favar_gamma{ii}(jj,jj);
   end
end
end

% obtain now the values for Ti, the (n+1)th matrix of each row
% loop over rows of temp
for ii=1:npltX
% start the summation over Tij matrices
temp{ii,npltXshck+1}=temp{ii,1};
   % sum over remaining columns
   for jj=2:npltXshck
   temp{ii,npltXshck+1}=temp{ii,npltXshck+1}+temp{ii,jj};
   end
end

% create the output cell fevd_record
favar_fevd_record=cell(npltX,npltXshck);
% fill the cell
% loop over rows of fevd_estimates
for ii=1:npltX
   % loop over columns of fevd_estimates
   for jj=1:npltXshck
   % define the matrix Vfij as the division (pairwise entry) of Tfij by Tfj
   favar_fevd_record{ii,jj}=temp{ii,jj}./temp{ii,npltXshck+1};
   end
end

%% create the FEVD estimates output
% create first the cell that will contain the estimates
favar_fevd_estimates=cell(npltX,npltXshck);

% for each variable and each variable contribution along with each period, compute the median, lower and upper bound from the Gibbs sampler records
% consider variables in turn
for ii=1:npltX
   % consider contributions in turn
   for jj=1:npltXshck
      % consider periods in turn
      for kk=1:IRFperiods
      % compute first the lower bound
      favar_fevd_estimates{ii,jj}(1,kk)=quantile(favar_fevd_record{ii,jj}(:,kk),(1-FEVDband)/2);
      % then compute the median
      favar_fevd_estimates{ii,jj}(2,kk)=quantile(favar_fevd_record{ii,jj}(:,kk),0.5);
      % finally compute the upper bound
      favar_fevd_estimates{ii,jj}(3,kk)=quantile(favar_fevd_record{ii,jj}(:,kk),1-(1-FEVDband)/2);
      end
   end
end

%save output
favar.FEVD.favar_fevd_estimates=favar_fevd_estimates;

% % % % finally, save on excel
% % % if pref.results==1
% % % % create the cell that will be saved on excel
% % % fevd_estimates=fevd_estimates';
% % % fevdcell={};
% % % % build preliminary elements: space between the tables
% % % horzspace=repmat({''},2,3*n);
% % % vertspace=repmat({''},IRFperiods+3,1);
% % % % loop over variables (vertical dimension)
% % % for ii=1:n
% % % tempcell={};
% % %    % loop over shocks (horizontal dimension)
% % %    for jj=1:n
% % %    % create cell of fevd record for variable ii in response to shock jj
% % %    temp=['part of ' endo{ii,1} ' fluctuation due to ' endo{jj,1} ' shocks'];
% % %    fevd_ij=[temp {''};{''} {''};{''} {'median'};num2cell((1:IRFperiods)') num2cell((fevd_estimates{ii,jj})')];
% % %    tempcell=[tempcell fevd_ij vertspace];
% % %    end
% % % fevdcell=[fevdcell;horzspace;tempcell];
% % % end
% % % % trim
% % % fevdcell=fevdcell(3:end,1:end-1);
% % % % write in excel
% % %     xlswrite(fullfile(pref.results_path, [pref.results_sub '.xlsx']),fevdcell,'FEVD','B2');
% % % end

author: european-central-bank

repo: BEAR-toolbox


text:
function z_callBack_virtualTeachPendant_J3_plus()
%% Soft realtime joints control Joint X button callback
% Copyright: Mohammad SAFEEA, 27th-July-2018
global virtual_smartPad_w_joints_command;
disp('Moving J3 in positive direction');
virtual_smartPad_w_joints_command(3)=1;
end

repo: KST-Kuka-Sunrise-Toolbox


text:
function [varargout] = min(varargin)

% MIN compile the missing mex file on the fly

% Copyright (C) 2012, Donders Centre for Cognitive Neuroimaging, Nijmegen, NL
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

% remember the original working directory
pwdir = pwd;

% determine the name and full path of this function
funname = mfilename('fullpath');
mexsrc  = [funname '.c'];
[mexdir, mexname] = fileparts(funname);

try
  % try to compile the mex file on the fly
  warning('trying to compile MEX file from %s', mexsrc);
  cd(mexdir);
  mex(mexsrc);
  cd(pwdir);
  success = true;

catch
  % compilation failed
  disp(lasterr);
  error('could not locate MEX file for %s', mexname);
  cd(pwdir);
  success = false;
end

if success
  % execute the mex file that was just created
  funname   = mfilename;
  funhandle = str2func(funname);
  [varargout{1:nargout}] = funhandle(varargin{:});
end


text:
function g = gpTimeDynamicsLogLikeGradients(model)

% GPTIMEDYNAMICSLOGLIKEGRADIENTS Gradients of the GP dynamics wrt parameters.
% FORMAT
% DESC Computes the gradients with respect to the log likelihood of
% the GP dynamics in a GP-LVM model.
% ARG model : the GP model for which log likelihood is to be
% computed.
% RETURN g : the gradients of the log likelihood with respect to
% the latent points and (optionally) parameters.
%
% SEEALSO : gpLogLikeGradients, gpTimeDynamicsCreate, gpTimeDynamicsLogLikelihood, modelLogLikelihood
%
% COPYRIGHT : Neil D. Lawrence, 2006, 2009

% FGPLVM

if model.k ==0 & ~model.learn & ~model.learnScales
  g = [];
  return
end

g = gpLogLikeGradients(model);

if ~model.learn
  % If we aren't learning model parameters extract only X_u;
  % this is inefficient (but neater in the code) as we have also computed parameters
  if ~model.learnScales
    if isfield(model, 'fixInducing') & model.fixInducing
      g = [];
    else
      g = g(1:model.k*model.q);
    end
  else
    switch model.approx
     case 'ftc'
      g =  [g(end-model.d + 1:end)];
     case {'dtc', 'dtcvar', 'fitc', 'pitc'}
      if isfield(model, 'fixInducing') & model.fixInducing
        g = g(end-model.d:end-1);
      else
        g =  [g(1:model.k*model.q) g(end-model.d:end-1)];
      end
    end
  end
end

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


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
%
function [d, resized]=resizeJavaPrefs(app, J, H)
d=J.getPreferredSize;
if app.toolBarFactor>0
    d=java.awt.Dimension(d.width*.55, d.height*.6);
    J.setPreferredSize(d);
    resized=true;
else
    resized=false;
end
end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function obj_normal_vector_print ( normal_num, normal_vector )

%*****************************************************************************80
%
%% OBJ_NORMAL_VECTOR_PRINT prints the normal vectors.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 September 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NORMAL_NUM, the number of normal vectors.
%
%    Input, real NORMAL_VECTOR(3,NORMAL_NUM), the normal vectors.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Normal Vectors:\n' );
  fprintf ( 1, '\n' );

  for normal = 1 : normal_num

    fprintf ( 1, '  %8d  %14f  %14f  %14f\n', ...
      normal,  normal_vector(1:3,normal) );

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
% This is a sample code from Appendix A.4 of the following book:
%
%    Zhuang Jiao, YangQuan Chen, Igor Podlubny,
%    Distributed-Order Dynamic Systems: Stability, Simulation,
%    Applications and Perspectives (Springer, London, 2012),
%    ISBN ISBN 978-1-4471-2851-9,
%    http://www.springer.com/engineering/control/book/978-1-4471-2851-9
%
% (C) Igor Podlubny, 2011

clear all

% Check if the FEX package 36574 is on your MATLAB path,
% and if not, then suggest downloading the FEX submission #36574
% "Demos for investigating distributed-order linear time-invariant systems"
% by Zhuang Jiao, which contains the Matlab code from Appendices 1-3
% of the same book
Explanation = ['You may be interested in downloading ' ...
'Zhuang Jiao''s FEX submission #36574' sprintf('\n')...
'(Demos for investigating distributed-order linear ' ...
'time-invariant systems)', sprintf('\n')...
'which contains the Matlab code from Appendices 1-3 to the same book.' ];
if ~(exist('stabbound_dods', 'file') == 2)
    P = suggestFEXpackage(36574, Explanation);
end

% Check if the FEX package 22071 is on your MATLAB path,
% and if it is not there, then require the FEX packages
% 31069 ("requireFEXpackage") and 22071 ("Matrix approach
% to discretization of ODEs and PDEs of arbitrary real order"):
if ~(exist('ban', 'file') == 2 && exist('fan', 'file') == 2 && exist('eliminator', 'file') == 2)
    P = requireFEXpackage(31069); % "requireFEXpackage"
    P = requireFEXpackage(22071);  % "Matrix approach..."
end

% (1) Prepare constants and nodes
%     (this is the longest part of the script):
h = 0.01;           % step of discretization
t = 0:h:5;          % discretization nodes
N = length(t) + 1;  % number of nodes
B = 0.1;            % coefficient of the equation
f = '0 + 0*t';      % right-hand-side
M = zeros(N,N);     % pre-allocate matrix M for the system

% (2) Write the discretization matrix:
M = doban('6*alf.*(1-alf)', [0 1], 0.01, N-1, h) + B*eye(N-1,N-1);

% (3) Compute the right-hand side at discretization nodes:
F = eval ([f '-B'], t)';

% (4) Utilize zero initial condition:
M = eliminator(N-1,[1])*M*eliminator(N-1, [1])';
F = eliminator(N-1,[1])*F;

% (5) And solve the system MY=F:
Y = M\F;

% (6) Pre-pend the zero initial value
Y0 = [0; Y];

% and plot the solution:
U = Y0 + 1;
plot(t, U, 'k')

author: Sable

repo: mcbench-benchmarks


text:
function z = he_polynomial_zeros ( nt )

%*****************************************************************************80
%
%% HE_POLYNOMIAL_ZEROS zeros of He(i,x).
%
%  Discussion:
%
%    He(i,x) represents the probabilist's Hermite polynomial.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    13 February 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NT, the degree of the polynomial.
%
%    Output, real Z(NT,1), the zeros of the polynomial.
%
  aj = zeros ( nt, 1 );
  bj = sqrt ( ( 1 : nt )' / 2.0 );
  wts = zeros ( nt, 1 );
  wts(1,1) = sqrt ( sqrt ( pi ) );

  [ z, wts ] = imtqlx ( nt, aj, bj, wts );
%
%  Adjust for probabilist.
%
  z(1:nt,1) = z(1:nt,1) * sqrt ( 2.0 );

  return
end


text:
function y = heavisideNoiseOut(noise, mu, varsigma)

% HEAVISIDENOISEOUT Output from heaviside noise model.

% IVM
D = size(mu, 2);
for i = 1:D
  mu(:, i) = mu(:, i) + noise.bias(i);
end
y = sign(mu);


text:
classdef AnnotationMarkersPlotter < handle
    properties (Access = private, Constant)
        markerColors = {[1 0 0],[1 1 0],[0 1 0], [0 0 1], [0 1 1], [1 105/255 180/255], [0.5 0 0.5], [0 0 0]};
        markerLineWidths = [1,1,4,1,1,1,1,1];
    end

    properties (Access = public)
        markerYRange = [-1 1];
        markerHandles;
        shouldShowMarkers = true;
    end

    methods
        function set.shouldShowMarkers(obj,visible)
            obj.setMarkersVisibility(visible);
            obj.shouldShowMarkers = visible;
        end
    end

    methods (Access = public)

        function plotMarkers(obj, markers, plotAxes)

            nMarkers = length(markers);
            obj.markerHandles = repmat(AnnotationMarkerHandle,1,nMarkers);

            for i = 1 : length(markers)
                marker = markers(i);
                color = obj.markerColors(marker.label);
                lineWidth = obj.markerLineWidths(marker.label);

                markerHandle = AnnotationMarkerHandle();

                markerHandle.lineHandle = line(plotAxes,[marker.sample, marker.sample],...
                    [obj.markerYRange(1) obj.markerYRange(2)],...
                    'Color',color{1},'LineWidth',lineWidth,...
                    'LineStyle','-');

                if ~isempty(marker.text)
                    textY = double((obj.markerYRange(1) + obj.markerYRange(2)) / 2);
                    textHandle = text(plotAxes,double(marker.sample),...
                        textY , marker.text,...
                        'Rotation',90);

                    set(textHandle, 'Clipping', 'on');
                    markerHandle.textHandle = textHandle;
                end

                obj.markerHandles(i) = markerHandle;
            end

            obj.setMarkersVisibility(obj.shouldShowMarkers);
        end

        function deleteMarkers(obj)

            for i = 1 : length(obj.markerHandles)
                markerHandle = obj.markerHandles(i);
                delete(markerHandle.lineHandle);
                delete(markerHandle.textHandle);
            end
            obj.markerHandles = [];
        end

        function setMarkersVisibility(obj,visible)
            visibleStr = Helper.GetOnOffString(visible);
            for i = 1 : length(obj.markerHandles)
                markerHandle = obj.markerHandles(i);
                markerHandle.visible = visibleStr;
            end
        end
    end

end

author: avenix

repo: WDK

save_path: github-repos/MATLAB/avenix-WDK


text:
function mesh = mshCircle(N,rad)
%+========================================================================+
%|                                                                        |
%|                 OPENMSH - LIBRARY FOR MESH MANAGEMENT                  |
%|           openMsh is part of the GYPSILAB toolbox for Matlab           |
%|                                                                        |
%| COPYRIGHT : Matthieu Aussal (c) 2017-2018.                             |
%| 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       : mshCircle.m                                   |
%|    #    |   VERSION    : 0.50                                          |
%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |
%|  ( # )  |   CREATION   : 25.11.2018                                    |
%|  / 0 \  |   LAST MODIF : 25.11.2018                                    |
%| ( === ) |   SYNOPSIS   : Build uniform mesh for a circle               |
%|  `---'  |                                                              |
%+========================================================================+

% Polar discretization
h     = (2*pi)/N;
theta = (0:h:(2*pi-h))';

% Element
vtx  = rad * [cos(theta) sin(theta) zeros(N,1)];
elt  = [[(2:N)';1] (1:N)'];
mesh = msh(vtx,elt);
end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function model = mpt_enumeration_mpmilp(Matrices,options)
% Variable bounds when all binary variables are relaxed
[global_lower,global_upper] = mpt_detect_and_improve_bounds(Matrices,Matrices.lb,Matrices.ub,Matrices.binary_var_index,options);

Matrices.lb = global_lower;
Matrices.ub = global_upper;
if any(Matrices.lb(end-Matrices.nx+1:end) == Matrices.ub(end-Matrices.nx+1:end))
    model = [];
    return
end

% Enumerate a sufficent set of binary cases
% (exploit SOS and pure binary constraints)
[enums,Matrices] = mpt_enumerate_binary(Matrices);

model = [];
for i = 1:size(enums,2);
    if options.verbose & rem(i,20)==0
        disp(['Binary node ' num2str(i) '/' num2str(size(enums,2))]);
    end
    % Create node problem
    lower = global_lower;
    upper = global_upper;
    lower(Matrices.binary_var_index) = enums(:,i);
    upper(Matrices.binary_var_index) = enums(:,i);
    % Pre-solve, solve and merge
    model = mpt_solvenode(Matrices,lower,upper,Matrices,model,options);
end

author: yalmip

repo: YALMIP

save_path: github-repos/MATLAB/yalmip-YALMIP


text:
%kvthick 'Thickening'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros vthick.pane file
%
% Parameters:
% InputFile: i 'Input Image', required: 'input image'
% InputFile: str1 'Struct Element 1', required: 'Structuring Element'
% InputFile: str2 'Struct Element 2', required: 'Structuring Element'
% OutputFile: o 'Output Image ', required: 'resulting output image'
%
% Example: o = kvthick({i, str1, str2}, {'i','';'str1','';'str2','';'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% vthick - Thickening
%
%  DESCRIPTION
% .I vthick
% will do the thickening of an input image by two set structuring elements.
%
% The output image data type will be the same as that of the highest data type
% of the input image.
%
% Some useful pairs of structuring elements:
%
%                               0 0 0    1 1 1
%   Conditional Segmentation    0 1 0    0 0 0
%                               1 1 1    0 0 0
%
%                               0 0 0    1 0 0
%   Pseudo Convex Hull          0 1 1    1 0 0
%                               0 0 0    1 0 0
%
%                               1 0 0    0 0 0
%   Convex Hull                 1 0 0    0 1 0
%                               1 0 0    0 0 0
%
%                               0 0 0    1 1 1
%   Homotopic Pruning           0 1 0    1 0 1
%                               0 0 0    1 1 1
%
%
%
%  EXAMPLES
% vthick -i ball.xv -str1 b272.str -str2 b273.str -o outimage.xv
%
% Will do the thickening of image "ball.xv" by the structuring set b272.str and b273.str, with the resulting image written to "outimage.xv".
%
%  "SEE ALSO"
% vcast1(1)
%
%  RESTRICTIONS
% .I vthick
% can be defined for all data types supported by Khoros, but at the moment it has been implemented just for the bit and unsigned char types.
% The structuring elements are subsets of the 3x3 matrix and the origin is always at the center of this matrix.
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993-1997 Junior Barrera, Roberto Lotufo.  All rights reserved.
%

function varargout = kvthick(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kvthick(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'str1', '__input';'str2', '__input';'o', '__output'};
maxval={0,0,0,0};
minval={0,0,0,0};
istoggle=[0,0,0,0];
was_set=istoggle * 0;
paramtype={'InputFile','InputFile','InputFile','OutputFile'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=1; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(1,1);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
[varargout{:}]=callKhoros([w 'vthick"  '],Inputs,narglist);

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
% XOVMP.m                Multi-point crossover
%
%       Syntax: NewChrom =  xovmp(OldChrom, Px, Npt, Rs)
%
%       This function takes a matrix OldChrom containing the binary
%       representation of the individuals in the current population,
%       applies crossover to consecutive pairs of individuals with
%       probability Px and returns the resulting population.
%
%       Npt indicates how many crossover points to use (1 or 2, zero
%       indicates shuffle crossover).
%       Rs indicates whether or not to force the production of
%       offspring different from their parents.
%

% Author: Carlos Fonseca, 	Updated: Andrew Chipperfield
% Date: 28/09/93,		Date: 27-Jan-94

function NewChrom = xovmp(OldChrom, Px, Npt, Rs);

% Identify the population size (Nind) and the chromosome length (Lind)
[Nind,Lind] = size(OldChrom);

if Lind < 2, NewChrom = OldChrom; return; end

if nargin < 4, Rs = 0; end
if nargin < 3, Npt = 0; Rs = 0; end
if nargin < 2, Px = 0.7; Npt = 0; Rs = 0; end
if isnan(Px), Px = 0.7; end
if isnan(Npt), Npt = 0; end
if isnan(Rs), Rs = 0; end
if isempty(Px), Px = 0.7; end
if isempty(Npt), Npt = 0; end
if isempty(Rs), Rs = 0; end

Xops = floor(Nind/2);
DoCross = rand(Xops,1) < Px;
odd = 1:2:Nind-1;
even = 2:2:Nind;

% Compute the effective length of each chromosome pair
Mask = ~Rs | (OldChrom(odd, :) ~= OldChrom(even, :));
Mask = cumsum(Mask')';

% Compute cross sites for each pair of individuals, according to their
% effective length and Px (two equal cross sites mean no crossover)
xsites(:, 1) = Mask(:, Lind);
if Npt >= 2,
        xsites(:, 1) = ceil(xsites(:, 1) .* rand(Xops, 1));
end
xsites(:,2) = rem(xsites + ceil((Mask(:, Lind)-1) .* rand(Xops, 1)) ...
                                .* DoCross - 1 , Mask(:, Lind) )+1;

% Express cross sites in terms of a 0-1 mask
Mask = (xsites(:,ones(1,Lind)) < Mask) == ...
                        (xsites(:,2*ones(1,Lind)) < Mask);

if ~Npt,
        shuff = rand(Lind,Xops);
        [ans,shuff] = sort(shuff);
        for i=1:Xops
          OldChrom(odd(i),:)=OldChrom(odd(i),shuff(:,i));
          OldChrom(even(i),:)=OldChrom(even(i),shuff(:,i));
        end
end

% Perform crossover
NewChrom(odd,:) = (OldChrom(odd,:).* Mask) + (OldChrom(even,:).*(~Mask));
NewChrom(even,:) = (OldChrom(odd,:).*(~Mask)) + (OldChrom(even,:).*Mask);

% If the number of individuals is odd, the last individual cannot be mated
% but must be included in the new population
if rem(Nind,2),
  NewChrom(Nind,:)=OldChrom(Nind,:);
end

if ~Npt,
        [ans,unshuff] = sort(shuff);
        for i=1:Xops
          NewChrom(odd(i),:)=NewChrom(odd(i),unshuff(:,i));
          NewChrom(even(i),:)=NewChrom(even(i),unshuff(:,i));
        end
end

author: vonsylvia


text:
function cMap = makeColorMap(varargin)
%% MAKECOLORMAP makes smoothly varying colormaps
% a = makeColorMap(beginColor, middleColor, endColor, numSteps);
% a = makeColorMap(beginColor, endColor, numSteps);
% a = makeColorMap(beginColor, middleColor, endColor);
% a = makeColorMap(beginColor, endColor);
%
% all colors are specified as RGB triples
% numSteps is a scalar saying howmany points are in the colormap
%
% Examples:
%
% peaks;
% a = makeColorMap([1 0 0],[1 1 1],[0 0 1],40);
% colormap(a)
% colorbar
%
% peaks;
% a = makeColorMap([1 0 0],[0 0 1],40);
% colormap(a)
% colorbar
%
% peaks;
% a = makeColorMap([1 0 0],[1 1 1],[0 0 1]);
% colormap(a)
% colorbar
%
% peaks;
% a = makeColorMap([1 0 0],[0 0 1]);
% colormap(a)
% colorbar

% Reference:
% A. Light & P.J. Bartlein, "The End of the Rainbow? Color Schemes for
% Improved Data Graphics," Eos,Vol. 85, No. 40, 5 October 2004.
% http://geography.uoregon.edu/datagraphics/EOS/Light&Bartlein_EOS2004.pdf

defaultNum = 100;
errorMessage = 'See help MAKECOLORMAP for correct input arguments';

if nargin == 2 %endPoints of colormap only
    color.start  = varargin{1};
    color.middle = [];
    color.end    = varargin{2};
    color.num    = defaultNum;
elseif nargin == 4 %endPoints, midPoint, and N defined
    color.start  = varargin{1};
    color.middle = varargin{2};
    color.end    = varargin{3};
    color.num    = varargin{4};
elseif nargin == 3 %endPoints and num OR endpoints and Mid
    if numel(varargin{3}) == 3 %color
        color.start  = varargin{1};
        color.middle = varargin{2};
        color.end    = varargin{3};
        color.num    = defaultNum;
    elseif numel(varargin{3}) == 1 %numPoints
        color.start  = varargin{1};
        color.middle = [];
        color.end    = varargin{2};
        color.num    = varargin{3};
    else
        error(errorMessage)
    end
else
    error(errorMessage)
end

if color.num <= 1
    error(errorMessage)
end

if isempty(color.middle) %no midPoint
    cMap = interpMap(color.start, color.end, color.num);
else %midpointDefined
    [topN, botN] = sizePartialMaps(color.num);
    cMapTop = interpMap(color.start, color.middle, topN);
    cMapBot = interpMap(color.middle, color.end, botN);
    cMap = [cMapTop(1:end-1,:); cMapBot];
end

function cMap = interpMap(colorStart, colorEnd, n)

for i = 1:3
    cMap(1:n,i) = linspace(colorStart(i), colorEnd(i), n);
end

function [topN, botN] = sizePartialMaps(n)
n = n + 1;

topN =  ceil(n/2);
botN = floor(n/2);
% Copyright 2008 - 2009 The MathWorks, Inc.

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
function net = glm(nin, nout, outfunc, prior, beta)
%GLM	Create a generalized linear model.
%
%	Description
%
%	NET = GLM(NIN, NOUT, FUNC) takes the number of inputs and outputs for
%	a generalized linear model, together with a string FUNC which
%	specifies the output unit activation function, and returns a data
%	structure NET. The weights are drawn from a zero mean, isotropic
%	Gaussian, with variance scaled by the fan-in of the output units.
%	This makes use of the Matlab function RANDN and so the seed for the
%	random weight initialization can be  set using RANDN('STATE', S)
%	where S is the seed value. The optional argument ALPHA sets the
%	inverse variance for the weight initialization.
%
%	The fields in NET are
%	  type = 'glm'
%	  nin = number of inputs
%	  nout = number of outputs
%	  nwts = total number of weights and biases
%	  actfn = string describing the output unit activation function:
%	      'linear'
%	      'logistic'
%	      'softmax'
%	  w1 = first-layer weight matrix
%	  b1 = first-layer bias vector
%
%	NET = GLM(NIN, NOUT, FUNC, PRIOR), in which PRIOR is a scalar, allows
%	the field  NET.ALPHA in the data structure NET to be set,
%	corresponding  to a zero-mean isotropic Gaussian prior with inverse
%	variance with value PRIOR. Alternatively, PRIOR can consist of a data
%	structure with fields ALPHA and INDEX, allowing individual Gaussian
%	priors to be set over groups of weights in the network. Here ALPHA is
%	a column vector in which each element corresponds to a  separate
%	group of weights, which need not be mutually exclusive.  The
%	membership of the groups is defined by the matrix INDEX in which the
%	columns correspond to the elements of ALPHA. Each column has one
%	element for each weight in the matrix, in the order defined by the
%	function GLMPAK, and each element is 1 or 0 according to whether the
%	weight is a member of the corresponding group or not.
%
%	NET = GLM(NIN, NOUT, FUNC, PRIOR, BETA) also sets the  additional
%	field NET.BETA in the data structure NET, where beta corresponds to
%	the inverse noise variance.
%
%	See also
%	GLMPAK, GLMUNPAK, GLMFWD, GLMERR, GLMGRAD, GLMTRAIN
%

%	Copyright (c) Ian T Nabney (1996-2001)

net.type = 'glm';
net.nin = nin;
net.nout = nout;
net.nwts = (nin + 1)*nout;

outtfns = {'linear', 'logistic', 'softmax'};

if sum(strcmp(outfunc, outtfns)) == 0
  error('Undefined activation function. Exiting.');
else
  net.outfn = outfunc;
end

if nargin > 3
  if isstruct(prior)
    net.alpha = prior.alpha;
    net.index = prior.index;
  elseif size(prior) == [1 1]
    net.alpha = prior;
  else
    error('prior must be a scalar or structure');
  end
end

net.w1 = randn(nin, nout)/sqrt(nin + 1);
net.b1 = randn(1, nout)/sqrt(nin + 1);

if nargin == 5
  net.beta = beta;
end

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
%% This file will be used to generate the simulation data of
% the Belousov Zhabotinsky reaction.
% Code By: K
% Last Updated: 2019/06/24
%% Clear all
close all;clear all;clc;
%% Add path
[fld_status, fld_msg, fld_msgID]=mkdir('Datas');
[fld_status, fld_msg, fld_msgID]=mkdir('Figures');
addpath('Datas')
addpath('Figures')
addpath('Functions')
%% Define parameters for the simulation
% Define diffusion rate
Dx=0.01;Dz=0.01;Ds=1;Du=1;

% Others
q=0.1;f=1.5;ksi=0.3;alpha=0.3;beta=0.26;gama=0.4;ksi2=1.5;ksi3=0.003;phi=0;

% Define the time horizon
dt=0.001;T=1;
tspan=0:dt:T;

% Define the spatial domain
L=20; % Total length of each dimension
n=128; % Discretization point of each dimension
N=n*n; % Total points used, n^2

x2=linspace(-L/2,L/2,n+1); x=x2(1:n);
y=x;dx=x(2)-x(1);

kx=(2*pi/L)*[0:(n/2-1) -n/2:-1];
ky=kx;

% Get n-dimensional grid
[X,Y]=meshgrid(x,y);
[KX,KY]=meshgrid(kx,ky);
K2=KX.^2+KY.^2; K22=reshape(K2,N,1);
Kx=reshape(KX,N,1);Ky=reshape(KY,N,1);Kxx=reshape(KX,N,1);Kyy=reshape(KY,N,1);

% Create a time matrix
r_t=zeros(n,n,length(tspan));r=zeros(n,n,length(tspan));r_x=zeros(n,n,length(tspan));r_xx=zeros(n,n,length(tspan));r_y=zeros(n,n,length(tspan));r_yy=zeros(n,n,length(tspan));
z_t=zeros(n,n,length(tspan));z=zeros(n,n,length(tspan));z_x=zeros(n,n,length(tspan));z_xx=zeros(n,n,length(tspan));z_y=zeros(n,n,length(tspan));z_yy=zeros(n,n,length(tspan));
s_t=zeros(n,n,length(tspan));s=zeros(n,n,length(tspan));s_x=zeros(n,n,length(tspan));s_xx=zeros(n,n,length(tspan));s_y=zeros(n,n,length(tspan));s_yy=zeros(n,n,length(tspan));
u_t=zeros(n,n,length(tspan));u=zeros(n,n,length(tspan));u_x=zeros(n,n,length(tspan));u_xx=zeros(n,n,length(tspan));u_y=zeros(n,n,length(tspan));u_yy=zeros(n,n,length(tspan));
r_lap=zeros(n,n,length(tspan));z_lap=zeros(n,n,length(tspan));s_lap=zeros(n,n,length(tspan));u_lap=zeros(n,n,length(tspan));
%% Set a Guassian for the initial condition
r0=cos(sqrt(X.^2+Y.^2)).^2+GaussianFilter(X,Y,0.05,0.05,0,0)+GaussianFilter(X,Y,1,0.01,0,0)+GaussianFilter(X,Y,0.01,1,0,0)+GaussianFilter(X,Y,0.25,0.25,5,5)+GaussianFilter(X,Y,0.25,0.25,5,-5)+GaussianFilter(X,Y,0.25,0.25,-5,5)+GaussianFilter(X,Y,0.25,0.25,-5,-5)+0.1;
z0=sin(0.1*sqrt(X.^2+Y.^2)).^2+GaussianFilter(X,Y,0.05,0.01,0,0)+GaussianFilter(X,Y,0.25,0.25,5,5)+GaussianFilter(X,Y,0.25,0.25,5,-5)+GaussianFilter(X,Y,0.25,0.25,-5,5)+GaussianFilter(X,Y,0.25,0.25,-5,-5)+0.1;
s0=sin(sqrt(X.^2+Y.^2)).^2+GaussianFilter(X,Y,0.5,0.5,0,5)+GaussianFilter(X,Y,0.5,0.5,5,0)+GaussianFilter(X,Y,0.5,0.5,0,-5)+GaussianFilter(X,Y,0.5,0.5,-5,0)+0.1;
u0=cos(sqrt(X.^2+Y.^2)).^2+GaussianFilter(X,Y,0.5,0.01,0,0)+GaussianFilter(X,Y,0.01,0.5,0,0)+GaussianFilter(X,Y,0.25,0.25,5,5)+GaussianFilter(X,Y,0.25,0.25,5,-5)+GaussianFilter(X,Y,0.25,0.25,-5,5)+GaussianFilter(X,Y,0.25,0.25,-5,-5)+0.01;

%% Plot the initial conditions
figure(1)
surf(x,y,r0)
set(gca,'FontSize',18);
set(gcf,'Position',[100 100 600 600]);
set(gcf,'PaperPositionMode','auto');
view(-18,35)
box('off')
axis('off')

figure(2)
surf(x,y,z0)
set(gca,'FontSize',18);
set(gcf,'Position',[100 100 600 600]);
set(gcf,'PaperPositionMode','auto');
view(-18,35)
box('off')
axis('off')

figure(3)
surf(x,y,s0)
set(gca,'FontSize',18);
set(gcf,'Position',[100 100 600 600]);
set(gcf,'PaperPositionMode','auto');
view(-18,35)
box('off')
axis('off')

figure(4)
surf(x,y,u0)
set(gca,'FontSize',18);
set(gcf,'Position',[100 100 600 600]);
set(gcf,'PaperPositionMode','auto');
view(-18,35)
box('off')
axis('off')
%%
close all
% Transfer the initial guess to fourier domain
xzsu0t=[reshape(fft2(r0),1,N) reshape(fft2(z0),1,N) reshape(fft2(s0),1,N) reshape(fft2(u0),1,N)].';

tic
opts = odeset('RelTol',1e-12,'AbsTol',1e-13);
NeedDev=0;
[time,xzsusol]=ode45(@(time,xzsut)BZ_Reaction_PDE(time,xzsut,Kx,Kxx,Ky,Kyy,K22,n,N,Dx,Dz,Ds,Du,q,f,ksi,alpha,beta,gama,ksi2,ksi3,phi,NeedDev),tspan,xzsu0t,opts);
toc

%% Extract values
% After simulation, we extract the derivative
NeedDev=1;

for pin=1:length(tspan)
    % Get the derivative data
    [~,r_t(:,:,pin),z_t(:,:,pin),s_t(:,:,pin),u_t(:,:,pin),r(:,:,pin),z(:,:,pin),s(:,:,pin),u(:,:,pin),r_x(:,:,pin),z_x(:,:,pin),s_x(:,:,pin),u_x(:,:,pin),r_y(:,:,pin),z_y(:,:,pin),s_y(:,:,pin),u_y(:,:,pin),r_xx(:,:,pin),z_xx(:,:,pin),s_xx(:,:,pin),u_xx(:,:,pin),r_yy(:,:,pin),z_yy(:,:,pin),s_yy(:,:,pin),u_yy(:,:,pin),r_lap(:,:,pin),z_lap(:,:,pin),s_lap(:,:,pin),u_lap(:,:,pin)]=...
        BZ_Reaction_PDE(0,xzsusol(pin,:).',Kx,Kxx,Ky,Kyy,K22,n,N,Dx,Dz,Ds,Du,q,f,ksi,alpha,beta,gama,ksi2,ksi3,phi,NeedDev);
end
%% Test out whehter the derivative is correct here
for pin=2:length(tspan)
    % Test out the zt (All time derivative tested, the Fourier derivative result matches the finite differences result)
    %     u_t_dum(:,:,pin)=(u(:,:,pin)-u(:,:,pin-1))/dt;
    %     figure(1)
    %     clf
    %     surf(x,y,u_t_dum(:,:,pin))
    %
    %     figure(2)
    %     clf
    %     surf(x,y,u_t(:,:,pin))
    %
    %     Dum=u_t_dum(:,:,pin)-u_t(:,:,pin);
    %     norm(Dum(:))

    % Test out the r_x, r_y (All tested, the answer matches)
    %     figure(1)
    %     clf
    %     surf(x,y,u_x(:,:,pin))
    %
    %     for kk=1:n
    %        Dum(kk,:)=CalDerivative(u(kk,:,pin),dx,1);
    %     end
    %
    %     figure(2)
    %     clf
    %     surf(x,y,Dum)
    %
    %     figure(3)
    %     clf
    %     surf(x,y,u_y(:,:,pin))
    %
    %     for kk=1:n
    %        Dum(:,kk)=CalDerivative(u(:,kk,pin),dx,1);
    %     end
    %
    %     figure(4)
    %     clf
    %     surf(x,y,Dum)

    % Test r_xx (All tested, the results matches)
    %     figure(1)
    %     clf
    %     surf(x,y,u_xx(:,:,pin))
    %
    %     for kk=1:n
    %         Dum_x(kk,:)=CalDerivative(u(kk,:,pin),dx,1);
    %     end
    %
    %     for kk=1:n
    %         Dum_xx(kk,:)=CalDerivative(Dum_x(kk,:),dx,1);
    %     end
    %
    %     figure(2)
    %     clf
    %     surf(x,y,Dum_xx)
    %
    %     figure(3)
    %     clf
    %     surf(x,y,u_yy(:,:,pin))
    %
    %     for kk=1:n
    %         Dum_y(:,kk)=CalDerivative(u(:,kk,pin),dx,1);
    %     end
    %
    %     for kk=1:n
    %         Dum_yy(:,kk)=CalDerivative(Dum_y(:,kk),dx,1);
    %     end
    %
    %     figure(4)
    %     clf
    %     surf(x,y,Dum_yy)
    %
    %     figure(5)
    %     clf
    %     surf(x,y,u_lap(:,:,pin))
    %
    %     figure(6)
    %     clf
    %     surf(x,y,Dum_xx+Dum_yy)
    %
    %     figure(7)
    %     clf
    %     surf(x,y,u_xx(:,:,pin)+u_yy(:,:,pin))
end

%% Plot the result and save it to file
%Creat Movie
Save_Animation=1;

States=['r','z','s','u'];
for pin=1:4
    if pin==1
        Animate=r;
        limits=[0 1];
    elseif pin==2
        Animate=z;
        limits=[0 1];
    elseif pin==3
        Animate=s;
        limits=[0 1];
    elseif pin==4
        Animate=u;
        limits=[0 1];
    end
    if Save_Animation==1
        name=strcat('BZ_Diffusion_',States(pin),'_',num2str(T),'_Seconds');
        writerObj = VideoWriter(name,'MPEG-4'); % Name it.
        writerObj.FrameRate = 20; % How many frames per second.
        writerObj.Quality = 100;
        open(writerObj);
        for j=1:15:length(tspan)
            clf
            pcolor(x,y,Animate(:,:,j))
            shading interp
            colormap(parula)
            caxis(limits)
            colorbar
            %Make plot propotional
            set(gca,'FontSize',18);
            set(gcf,'Position',[50 50 1000 1000]);
            set(gcf,'PaperPositionMode','auto');
            set(gca,'DataAspectRatio',[1 1 1])
            drawnow limitrate
            Mov=getframe(gcf);
            writeVideo(writerObj,Mov);
        end
        % Close the object or you can't read the final file correctly
        close(writerObj)
    end
end

%% Save files
Save_File=1;
if Save_File==1
    save(strcat('Datas\Simulation_BZ_',num2str(T),'_Seconds_',num2str(n),'_Grid.mat'),'r_t','z_t','s_t','u_t','r','z','s','u',...
        'r_x','z_x','s_x','u_x','r_y','z_y','s_y','u_y','r_xx','z_xx','s_xx','u_xx',...
        'r_yy','z_yy','s_yy','u_yy','dt','T','tspan','dx','x')
end

author: dynamicslab

repo: SINDy-PI


text:
function phiFaceAverage = upwindMean2D(phi, u)
% This function gets the value of the field variable phi defined
% over the MeshStructure and calculates the upwind average on
% the cell faces, based on the direction of the velocity vector for a uniform mesh.
%
% SYNOPSIS:
%   phiFaceAverage = upwindMean2D(phi, u)
%
% PARAMETERS:
%
%
% RETURNS:
%
%
% EXAMPLE:
%
% SEE ALSO:
%

% Written by Ali A. Eftekhari
% See the license file

% extract the velocity data
% note: size(ux) = [1:m+1, 1:n] and size(uy) = [1:m, 1:n+1]
ux = u.xvalue;
uy = u.yvalue;

% check the size of the variable and the mesh dimension
Nxy = phi.domain.dims;
Nx = Nxy(1); Ny = Nxy(2);

% assign to a temp variable for boundary corrections
phi_tmp = phi.value;

% correct the value of phi at the boundary (calculation trick)
% assign the value of the left boundary to the left ghost cells
phi_tmp(1,:) = (phi.value(1,:)+phi.value(2,:))/2;
% assign the value of the right boundary to the right ghost cells
phi_tmp(end,:) = (phi.value(end,:)+phi.value(end-1,:))/2;
% assign the value of the bottom boundary to the bottom ghost cells
phi_tmp(:,1) = (phi.value(:,1)+phi.value(:,2))/2;
% assign the value of the top boundary to the top ghost cells
phi_tmp(:,end) = (phi.value(:,end)+phi.value(:,end-1))/2;

% calculate the average value
xvalue = (ux>0).*phi_tmp(1:Nx+1,2:Ny+1)+ ...
                        (ux<0).*phi_tmp(2:Nx+2,2:Ny+1)+ ...
                        0.5*(ux==0).*(phi.value(1:Nx+1,2:Ny+1)+phi.value(2:Nx+2,2:Ny+1));
yvalue = (uy>0).*phi_tmp(2:Nx+1,1:Ny+1)+ ...
                        (uy<0).*phi_tmp(2:Nx+1,2:Ny+2)+ ...
                        0.5*(uy==0).*(phi.value(2:Nx+1,1:Ny+1)+phi.value(2:Nx+1,2:Ny+2));
phiFaceAverage=FaceVariable(phi.domain, xvalue, yvalue, []);

author: simulkade

repo: FVTool

save_path: github-repos/MATLAB/simulkade-FVTool


text:
%GENDATS Generation of a simple classification problem of 2 Gaussian classes
%
%   A = GENDATS (N,K,D,LABTYPE)
%
% INPUT
%   N       Dataset size, or 2-element array of class sizes (default: [50 50]).
%   K       Dimensionality of the dataset to be generated (default: 2).
%   D       Distance between class means in the first dimension (default: 1).
%   LABTYPE Label type to generate, 'crisp' or 'soft' (default: 'crisp').
%
% OUTPUT
%   A       Dataset.
%
% DESCRIPTION
% Generation of a K-dimensional 2-class dataset A of N objects. Both classes
% are Gaussian distributed with identity matrix as covariance matrix. Their
% means are on a distance D. Class priors are P(1) = P(2) = 0.5.
%
% If N is a vector of sizes, exactly N(I) objects are generated for class I,
% I = 1,2.
%
% LABTYPE defines the desired label type: 'crisp' or 'soft'. In the latter
% case true posterior probabilities are set for the labels.
%
% SEE ALSO (PRTools Guide)
% DATASETS, PRDATASETS

% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands

% $Id: gendats.m,v 1.3 2009/01/27 13:01:42 duin Exp $

function A = gendats (N,k,d,labtype)

		if (nargin < 1),
		prwarning(2,'class sizes not specified, assuming [50 50]');
		N = [50 50];
	end
	if (nargin < 2),
		prwarning(2,'dimensionality not specified, assuming 2');
		k = 2;
	end
	if (nargin < 3),
		prwarning(2,'class mean distance not specified, assuming 1');
		d = 2;
	end
	if (nargin < 4),
		prwarning(2,'label type not specified, assuming "crisp"');
		labtype = 'crisp';
	end

	% Set equal priors and generate random class sizes according to these.
	p = [0.5 0.5]; N = genclass(N,p);

	% Unit covariance matrices, zero mean except for distance D in first dim.
	GA = eye(k); GB = eye(k);
	ma = zeros(1,k); mb = zeros(1,k); mb(1) = d;
	U = prdataset([ma;mb],[1 2]');
	U = setprior(U,p);

	% Create dataset.
	A = gendatgauss(N,U,cat(3,GA,GB),labtype);
	A = setname(A,'Simple Problem');

return

author: marianux

repo: ecg-kit

save_path: github-repos/MATLAB/marianux-ecg-kit


text:
% book : Signals and Systems Laboratory with MATLAB
% authors : Alex Palamides & Anastasia Veloni

%problem 3 - Inverse Fourier Transform of sin(w)/w

syms t w
X=sin(w)/w;
x=ifourier(X,t)
ezplot(x, [-3 3])


text:
function CERRImportDCM4CHE()
% CERRImportDCM4CHE
% imports the DICOM data into CERR plan format. This function is based on
% the Java code dcm4che.
% written DK, WY
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR 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.
%
% CERR 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 CERR.  If not, see <http://www.gnu.org/licenses/>.

global stateS
if ~isfield(stateS,'initDicomFlag')
    flag = init_ML_DICOM;
    if ~flag
        return;
    end
elseif isfield(stateS,'initDicomFlag') && ~stateS.initDicomFlag
    return;
end

% Get the path of the directory to be selected for import.
dirPath = uigetdir(pwd','Select the DICOM directory to scan:');
%pause(0.1);

if ~dirPath
    disp('DICOM import aborted');
    return
end

tic;

% Read options file
pathStr = getCERRPath;
optName = [pathStr,'CERROptions.json'];
optS = opts4Exe(optName);

%hWaitbar = waitbar(0,'Scanning Directory Please wait...');
%CERRStatusString('Scanning DICOM directory');
disp('CERR>>  Scanning DICOM directory')

dcmdirS = [];
patientNum = 1;
excludePixelDataFlag = true;

patient = scandir_mldcm(dirPath, excludePixelDataFlag);
if ~isempty(patient)
    for j = 1:length(patient.PATIENT)
        dcmdirS.(['patient_' num2str(patientNum)]) = patient.PATIENT(j);
        patientNum = patientNum + 1;
    end
end
if isfield(optS,'importDICOMsubDirs') && strcmpi(optS.importDICOMsubDirs,'yes') % && ~isempty(dirsInCurDir)

    [filesInCurDir,dirsInCurDir] = rdir(dirPath);

    for i = 1:length(dirsInCurDir)
        %     patient = scandir_mldcm(fullfile(dirPath, dirs(i).name), hWaitbar, i);
        patient = scandir_mldcm(dirsInCurDir(i).fullpath, excludePixelDataFlag);
        if ~isempty(patient)
            for j = 1:length(patient.PATIENT)
                dcmdirS.(['patient_' num2str(patientNum)]) = patient.PATIENT(j);
                patientNum = patientNum + 1;
            end
        end
    end
end

if isempty(dcmdirS)
    %close(hWaitbar);
    msgbox('There is no dicom data!','Application Info','warn');
    return;
end

%close(hWaitbar);

mergeScansFlag = 'No'; % define it in CERROptions?
%selected = showDCMInfo(dcmdirS);
selected = 'all';
patNameC = fieldnames(dcmdirS);
if isempty(selected)
    return
elseif strcmpi(selected,'all')
    combinedDcmdirS = struct('STUDY',dcmdirS.(patNameC{1}).STUDY,'info',dcmdirS.(patNameC{1}).info);
    count = 0;
    for studyCount = 1:length(combinedDcmdirS.STUDY)
        for seriesCount = 1:length(combinedDcmdirS.STUDY(studyCount).SERIES)
            count = count + 1;
            newCombinedDcmdirS.STUDY.SERIES(count) = combinedDcmdirS.STUDY(studyCount).SERIES(seriesCount);
        end
    end
    combinedDcmdirS = newCombinedDcmdirS;

    for i = 2:length(patNameC)
        for  k = 1:length(dcmdirS.(patNameC{i}).STUDY)
            for j = 1:length(dcmdirS.(patNameC{i}).STUDY(k).SERIES)
                combinedDcmdirS.STUDY.SERIES(end+1) = dcmdirS.(patNameC{i}).STUDY(k).SERIES(j);
            end
        end
    end
    % Pass the java dicom structures to function to create CERR plan
    planC = dcmdir2planC(combinedDcmdirS,mergeScansFlag,optS);
else
    % Pass the java dicom structures to function to create CERR plan
    planC = dcmdir2planC(dcmdirS.(selected),mergeScansFlag,optS); %wy
end

indexS = planC{end};

%-------------Store CERR version number---------------%
[version, date] = CERRCurrentVersion;
planC{indexS.header}.CERRImportVersion = [version, ', ', date];

toc;
pause(0.05)
save_planC(planC,planC{indexS.CERROptions});

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function asa111_test01 ( )

%*****************************************************************************80
%
%% TEST01 tests PPND.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST01:\n' );
  fprintf ( 1, '  PPND computes percentage points of the normal distribution.\n' );
  fprintf ( 1, '  Compare to tabulated values.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '         CDF      X                         X  ' );
  fprintf ( 1, '                    DIFF\n' );
  fprintf ( 1, '               (tabulated)                 (PPND)\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, x, fx ] = normal_01_cdf_values ( n_data );

    if ( n_data == 0 )
      break
    end

    [ x2, ifault ] = ppnd ( fx );

    fprintf ( 1, '  %10.4e  %24.16e  %24.16e  %10.4e\n', ...
    fx, x, x2, abs ( x - x2 ) );

  end

  return
end


text:
function lvmClassVisualisePath(call)

% LVMCLASSVISUALISEPATH Latent variable model path drawing in latent space.

% MLTOOLS

global visualiseInfo

switch call
 case 'click'
  visualiseInfo.clicked = ~visualiseInfo.clicked;
  if visualiseInfo.clicked
    [x, y]  = localCheckPointPosition(visualiseInfo);
    if ~isempty(x)
      visualiseInfo.latentPos = [x, y];
      visualiseInfo.posTrail = [x, y];
      visualiseInfo.lastTime = clock;
      visualiseInfo.timeTrail = 0;
    end
  end
 case 'move'
  if visualiseInfo.clicked
    [x, y]  = localCheckPointPosition(visualiseInfo);
    if ~isempty(x)
      visualiseInfo.latentPos=[x, y];
      % Draw connecting lines
      iplot(visualiseInfo.plotAxes, x, y);
      visualiseInfo.posTrail = [visualiseInfo.posTrail; [x, y]];
      timeNow = clock;
      visualiseInfo.timeTrail = [visualiseInfo.timeTrail; visualiseInfo.timeTrail(end)+etime(timeNow, ...
                                                        visualiseInfo.lastTime)];
      visualiseInfo.lastTime = timeNow;
    end
  end
end

function point = localGetNormCursorPoint(figHandle)

point = get(figHandle, 'currentPoint');
figPos = get(figHandle, 'Position');
% Normalise the point of the curstor
point(1) = point(1)/figPos(3);
point(2) = point(2)/figPos(4);

function [x, y] = localGetNormAxesPoint(point, axesHandle)

position = get(axesHandle, 'Position');
x = (point(1) - position(1))/position(3);
y = (point(2) - position(2))/position(4);
lim = get(axesHandle, 'XLim');
x = x*(lim(2) - lim(1));
x = x + lim(1);
lim = get(axesHandle, 'YLim');
y = y*(lim(2) - lim(1));
y = y + lim(1);

function [x, y] = localCheckPointPosition(visualiseInfo)

% Get the point of the cursor
point = localGetNormCursorPoint(gcf);

% get the position of the axes
position = get(visualiseInfo.plotAxes, 'Position');

% Check if the pointer is in the axes
if point(1) > position(1) ...
      & point(1) < position(1) + position(3) ...
      & point(2) > position(2) ...
      & point(2) < position(2) + position(4);

  % Rescale the point according to the axes
  [x y] = localGetNormAxesPoint(point, visualiseInfo.plotAxes);

  % Find the nearest point
else
  % Return nothing
  x = [];
  y = [];
end