text:
%% logit
% Below is a demonstration of the features of the |logit| function

%%
clear; close all; clc;

%% Syntax
% |y=logit(x);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


text:
classdef AnalysisBvalues < AnalysisWindow
    % ANALYSISBVALUES shows b-value plot (FMD)
    properties
        bobj; % points to an existing bobj (bdiff2 object)
    end

    methods
        function obj = AnalysisBvalues(ax, other_bobj)
            obj@AnalysisWindow(ax);
            obj.nMarkers = 2;
            if exist('other_bobj','var')
                obj.bobj = other_bobj;
            end
        end

        function prepare_axes(obj)
            % label and scale the axes
            obj.ax.Tag          = 'dvBval';
            obj.ax.YScale       = 'log';
            obj.ax.YLim         = [1 10000];
            obj.ax.XLim         = [-inf inf];
            obj.ax.Title.String = 'B-Value';
            obj.ax.XLabel.String= 'Magnitude';
            obj.ax.YLabel.String= '# Events';
        end

        function h=add_series(obj, catalog, tagID, varargin)
            % obj.ADD_SERIES(catalog, tagID, [[Name, Value],...])
            % fit line
            xlm = obj.ax.XLimMode;
            xl = obj.ax.XLim;

            p = inputParser();
            p.addRequired('tagID', @(x)ischarlike(tagID));
            p.addParameter('Ypos', 0.6);
            p.KeepUnmatched = true;
            p.parse(tagID, varargin{:});

            countProps = p.Unmatched;
            countProps.LineStyle = 'none';
            countProps.MarkerIndices = 'all';
            countProps.LineWidth = 1;
            obj.ax.XLimMode = 'auto';

            h = add_series@AnalysisWindow(obj, catalog, tagID, countProps);

            obj.ax.XLimMode = 'Manual';

            seriesText = obj.bobj.descriptive_text([]);
            textHandle = findobj('Type', 'text', '-and', '-regexp', 'Tag', [tagID,' txt']);
            xStart = range(xlim(obj.ax)) * 0.6 + min(xlim(obj.ax));
            if ~isempty(textHandle)
                textHandle.String = seriesText;
                textHandle.Position(1) = xStart;
            else
                logLim = log10(ylim(obj.ax));
                myLogY = p.Results.Ypos * range(logLim) + min(logLim);
                if ~isfield(p.Unmatched,'Color')
                    p.Unmatched.Color = [.2 .2 .2];
                end
                text(obj.ax, xStart, 10^myLogY, seriesText, 'Color', p.Unmatched.Color .* 0.75,...
                    'Tag', [tagID,' txt'], 'EdgeColor', 'none');
            end

            % maybe each other add_series should contribute to h, too.

            % magnitude of completeness point
            %McProps = p.Unmatched;
            %McProps.DisplayName = '';
            %if ~isfield(McProps,'Color')
            %    McProps.MarkerFaceColor = get(findobj(obj.ax,'Tag',tagID),'Color');
            %else
            %    McProps.MarkerFaceColor = McProps.Color;
            %end
            %add_series@AnalysisWindow(obj, catalog, [tagID ' Mc'], 'UseCalculation',@obj.getMc, McProps);

            % linear fit
            lineProps = p.Unmatched;
            lineProps.LineWidth         = 2;
            lineProps.MarkerFaceColor   = 'auto';
            lineProps.DisplayName       = '';
            lineProps.MarkerIndices     = 2;
            lineProps.MarkerSize        = 10;
            add_series@AnalysisWindow(obj, catalog, [tagID, ' line'], 'UseCalculation', @obj.getBvalLine, lineProps);
            obj.ax.XLim     = xl;
            obj.ax.XLimMode = xlm;
        end

        function [x,y] = calculate(obj,catalog)
            % Cumulative events by magnitude
            if isempty(catalog)
                x = nan;
                y = nan;
            else
                if isa(catalog,'ZmapCatalog')
                    obj.bobj.RawCatalog = catalog;
                else
                    obj.bobj.RawCatalog = catalog.Catalog;
                end
                obj.bobj.Calculate();
                x = obj.bobj.mag_bin_centers;
                y = obj.bobj.cum_b_values;
            end
        end

        function [x,y] = getMc(obj,~)
            % Determine magnitude of completion. X is magnitude, y is approximately # of events below MC
            if isempty(obj.bobj)
                y = nan;
                x = nan;
            else
                x = obj.bobj.Result.Mc_value;
                y = obj.bobj.cum_b_values(obj.bobj.Result.index_low) * 1.5;
            end
        end

        function [x,y] = getBvalLine(obj,~)
            % Show the B-value trend line
            if isempty(obj.bobj) || isempty(obj.bobj.Result.mag_zone)
                x = [nan nan];
                y = [nan nan];
            else
                x = obj.bobj.Result.mag_zone([1 end]);
                y = obj.bobj.fitted([1 end]);
            end
        end

        function remove_series(obj,tagID)
            % remove  B-value graphical objects associated with this tag
            if iscell(tagID) || isstring(tagID)
                for j=1:numel(tagID)
                    obj.remove_series(tagID{j});
                end
            else
                remove_series@AnalysisWindow(obj,tagID);
                % remove_series@AnalysisWindow(obj,[tagID ' Mc']);
                remove_series@AnalysisWindow(obj,[tagID ' line']);
                remove_series@AnalysisWindow(obj,[tagID ' txt']);
            end
        end
    end
end

author: CelsoReyes


text:
function test_ft_respiration

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_respiration

fs = 500;
nchan = 32;
start_time = -1; % seconds
end_time = 2.5; % seconds
nsamples = (end_time - start_time) * fs + 1;

data = [];
data.time{1} = linspace(start_time, end_time, nsamples);
data.trial{1} = randn(nchan,nsamples);
data.label = cellstr(num2str((1:nchan).'));

cfg = [];
cfg.channel = '11';
cfg.peakseparation = 1;
cfg.envelopewindow = 0.5;
cfg.feedback = 'no';
dataout = ft_respiration(cfg,data);

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function ip = inner_product_cdcf(xf, yf)

% Computes the inner product between two filters.

ip_cell = cellfun(@(xf, yf) real(2*(xf(:)' * yf(:)) - reshape(xf(:,end,:), [], 1, 1)' * reshape(yf(:,end,:), [], 1, 1)), xf, yf, 'uniformoutput', false');
ip = sum(cell2mat(ip_cell));

% ip_cell = cellfun(@(xf, yf) real(xf(:)' * yf(:)), xf, yf, 'uniformoutput', false');
% ip = sum(cell2mat(ip_cell));

author: martin-danelljan

repo: Continuous-ConvOp


text:
function [dat] = ft_preproc_hilbert(dat, option)

% FT_PREPROC_HILBERT computes the Hilbert transpose of the data and optionally
% performs post-processing on the complex representation, e.g. the absolute
% value of the Hilbert transform of a band-pass filtered signal corresponds
% with the amplitude envelope.
%
% Use as
%   [dat] = ft_preproc_hilbert(dat, option)
% where
%   dat        data matrix (Nchans X Ntime)
%   option     string that determines whether and how the Hilbert transform
%              should be post-processed, can be
%                'abs'
%                'complex'
%                'real'
%                'imag'
%                'absreal'
%                'absimag'
%                'angle'
%
% The default is to return the absolute value of the Hilbert transform.
%
% See also PREPROC

% Copyright (C) 2008, Robert Oostenveld
%
% 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$

% set the defaults if option is not specified
if nargin<2 || isempty(option)
  option = 'abs';
end

% preprocessing fails on channels that contain NaN
if any(isnan(dat(:)))
  ft_warning('FieldTrip:dataContainsNaN', 'data contains NaN values');
end

% use the non-conjugate transpose to be sure
dat = transpose(hilbert(transpose(dat)));

% do postprocessing of the complex representation
switch option
    case {'yes' 'abs'}
        dat = abs(dat);   % this is the default if 'yes' is specified
    case {'no' 'complex'}
        dat = dat;        % this is the default if 'no' is specified
    case 'real'
        dat = real(dat);
    case 'imag'
        dat = imag(dat);
    case 'absreal'
        dat = abs(real(dat));
    case 'absimag'
        dat = abs(imag(dat));
    case 'angle'
        dat = (angle(dat./abs(dat)));
    case 'unwrap_angle'
        dat = unwrap(angle(dat./abs(dat)),[],2);
    otherwise
        ft_error('incorrect specification of the optional input argument');
end

author: spm


text:
% conda.m
% a simple MATLAB utility to control conda
% environments on *nix systems
%
% usage
%
% MATLAB 			   Shell
% ===================================
% conda.getenv         conda env list
% conda.setenv(env)    source activate env
%
% Srinivas Gorur-Shandilya

classdef conda

properties
end

methods

end

methods (Static)

	function varargout = conda(varargin)

		varargout = {};

		if nargin == 2
			if strcmp(varargin{1},'env') && strcmp(varargin{2},'list')
				conda.getenv();
				return
			elseif strcmp(varargin{1},'activate')
				conda.setenv(varargin{2})
				return
			else
				error('Unknown argument syntax')
			end
		else
			error('Unknown argument syntax')
		end

	end

	function init()

		try
			getpref('condalab','base_path');
		catch
			str = input('Enter the path to your conda installation:  \n','s');
			str = strrep(str,[filesep 'conda'],'');
			setpref('condalab','base_path',str)
		end

		conda.addBaseCondaPath()

	end

	function addBaseCondaPath()

		try
			condalab_base_path = getpref('condalab','base_path');
		catch
			conda.init()
			condalab_base_path = getpref('condalab','base_path');
		end

		[e,o]=system('which conda');
		if e == 0
			% conda is somewhere on the path, so do nothing
			return
		end

		P = strsplit(getenv('PATH'),pathsep);
		add_to_path = true;
		for i = 1:length(P)
			if strcmp(P{i},condalab_base_path)
				add_to_path = false;
			end
		end
		if add_to_path
			setenv('PATH',[condalab_base_path pathsep getenv('PATH') ]);
		end

	end

	function varargout = getenv()
		conda.addBaseCondaPath;
		[~,envs] = system('conda env list');
		envs = strsplit(envs,'\n');

		p = strsplit(getenv('PATH'),pathsep);

		% remove the asterix because it always is on root
		for i = length(envs):-1:1
			envs{i} = strrep(envs{i},'*',' ');
			if isempty(envs{i})
				continue
			end
			if strcmp(envs{i}(1),'#')
				continue
			end

			this_env = strsplit(envs{i});
			env_names{i} = this_env{1};
			env_paths{i} = this_env{2};

			active_path = 0;
			for j = 1:length(env_paths)
				this_env_path = [env_paths{j} filesep 'bin'];
				if any(strcmp(this_env_path,p))
					active_path = j;
				end
			end

		end

		if nargout
			varargout{1} = env_names;
			varargout{2} = env_paths;
			varargout{3} = active_path;
		else
			fprintf('\n')
			for i = 1:length(env_names)
				if isempty(env_names{i})
					continue
				end
				if active_path == i
					disp(['*' env_names{i} '     ' env_paths{i}])
				else
					disp([env_names{i} '     ' env_paths{i}])
				end
			end
		end
	end % end getenv

	function setenv(env)
		conda.addBaseCondaPath;
		[~,envs] = system(['conda env list']);
		envs = strsplit(envs,'\n');

		[env_names, env_paths] = conda.getenv;

		% check that envs exists in the list
		assert(any(strcmp(env_names,env)), 'env you want to activate is not valid')

		p = getenv('PATH');
		% delete every conda env path from the path
		p = strsplit(p,pathsep);
		rm_this = false(length(p),1);
		for i = 1:length(p)
			% remove "bin" from the end
			this_path = strtrim(strrep(p{i}, [filesep 'bin'],''));
			if any(strcmp(this_path,env_paths))
				rm_this(i) = true;
			end
		end
		p(rm_this) = [];

		% add the path of the env we want to switch to
		this_env_path = [env_paths{strcmp(env_names,env)} filesep 'bin'];
		p = [this_env_path p];
		p = strjoin(p,pathsep);

		% append the base path to this, because apparently
		% conda decides to change everything every 2 months
		p = [p pathsep getpref('condalab','base_path')];

		setenv('PATH', p);

	end % setenv

	% asks the python interpreter where it is located
	function test()
		system(['python ' fileparts(which(mfilename)) filesep 'test.py']);
	end

end

end % end classdef

author: opencobra

repo: cobratoolbox


text:
function header = read_spike6mat_header(filename)

% read_spike6mat_header() - read Matlab files exported from Spike 6
%
% Usage:
%   >> header = read_spike6mat_header(filename);
%
% Inputs:
%   filename - [string] file name
%
% Outputs:
%   header   - FILEIO toolbox type structure
% _______________________________________________________________________
% Copyright (C) 2008 Institute of Neurology, UCL
% Vladimir Litvak

if nargin < 1
  help read_spike6mat_header;
  return;
end;

try
    vars = struct2cell(load(filename));
catch
    ft_error('File not found or wrong format.');
end

header = [];
header.nChans      = length(vars);
header.label = {};
header.orig = {};

fsample = [];
onsets = [];
lengths = [];
for i = 1:numel(vars)
    fsample(i) = round(1./vars{i}.interval);
    onsets(i)  = 1e-3*round(1e3*vars{i}.times(1));
    lengths(i) = vars{i}.length;
    header.label{i} = vars{i}.title;
    header.orig{i} = rmfield(vars{i}, {'values', 'times'});
end

if length(unique(fsample))>1 || length(unique(onsets))>1 || length(unique(lengths))>1
    ft_error('Only files with identical channel parameters are supported');
end

header.Fs          = unique(fsample);

header.nSamples    = unique(lengths);

header.nSamplesPre = -round(unique(onsets)*header.Fs);

header.nTrials     = 1;

header.label       = header.label(:);


text:
function  h11=derotated_dtcwt(n,Yh)
%FUNCTION to perform a derotated DT_CWT

% n  -> No. of levels of wavelet decomposition
% Yh -> A cell array containing the 6 complex highpass subimages for
%  each level.
% h11 ->detotated Yh
h11{n}=Yh{n};
for k=n:-1:2
    for m=1:6
        xp=imresize(Yh{k}(:,:,m),2);%
        argxp=angle(xp);
        argx=angle(Yh{k-1}(:,:,m));
        argx=argx-2.*argxp;
        absx=abs(Yh{k-1}(:,:,m));
        xa=absx.*cos(argx);
        xb=absx.*sin(argx);
        h11{k-1}(:,:,m)=complex(xa,xb);
    end
end
%figure;
%cimage5(h11{1}(:,:,4));
%figure;
%cimage5(h1{1}(:,:,4));
%figure;
%cimage5(h11{2}(:,:,4));
%figure;
%cimage5(h1{2}(:,:,4));

author: xingchenzhang

repo: VIFB

save_path: github-repos/MATLAB/xingchenzhang-VIFB


text:
function [S,Li] = eeg_interp_sph_spline(V,X,Y,Z,Npoints)

% eeg_interp_sph_spline - Spherical Spline Laplacian of Potential
%
% Useage: [S,Li] = eeg_lap_sph_spline(voltage,X,Y,Z,Npoints)
%
% where:    'voltage' is an EEG/ERP measurement at time t from
%           electrode positions (X,Y,Z) on a scalp surface.  All
%           input arrays are the same size, assumed (Nelec x 1).
%           The origin of X,Y,Z is assumed (0,0,0).
%
%           S  => the x,y,z points on a hemisphere
%           Li => spherical spline Laplacian of voltages
%
%           S is generated by 'elec_sphere_points' with
%           Rpoints=Npoints and Epoints=16.
%
% Notes:    This function calculates the spherical spline Laplacian
%           of Perrin et al (1989).  Electroenceph. & Clin.
%             Neurophysiology, 72: 184-187.
%

% $Revision: 1.1 $ $Date: 2009-04-28 22:13:52 $

% Licence:  GNU GPL, no implied or express warranties
% History:  08/01  Darren.Weber_at_radiology.ucsf.edu, with
%                  mathematical and matlab advice from
%                  Dr. Murk Bottema (Flinders University of SA)
%
%           08/01  Needs testing & verification!
%                  With large electrode arrays, the result should be
%                  regularized (not sure why).
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Check for correct size & orientation of X,Y,Z,V
    [x1,x2] = size(X);
    [y1,y2] = size(Y);
    [z1,z2] = size(Z);
    [v1,v2] = size(V);
    if ~and(isequal(x1,y1,z1,v1),isequal(x2,y2,z2,v2))
        error('ERROR: all X, Y, Z, V must be size (Nx1)');
    end
    if x1 < x2, X = X'; [x1,x2] = size(X); end
    if y1 < y2, Y = Y'; [y1,y2] = size(Y); end
    if z1 < z2, Z = Z'; [z1,z2] = size(Z); end
    if v1 < v2, V = V'; [v1,v2] = size(V); end
    if ~(isequal(x2,y2,z2,v2,1))
        error('ERROR: all X, Y, Z, V must be size (Nx1)');
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Computations derived from Perrin et al. (1989)

    % G * C = V,  where:
    %
    % G  (NxN)    spherical spline
    % C  (Nx1)    spline coefficients
    % V  (Nx1)    voltage potentials at (X,Y,Z) electrode locations
    %
    % solve for C = V * Sp' (C = V\Sp; (see "help slash"))

    % First calc G, where G is a function of the cosine of
    % the angle (theta) between electrode point vectors
    A   = [ X Y Z ];
    COS = cosines(A,A);
    G   = spheric_spline(COS);
    C   = spline_coefficients(G,V); % spline coefficients (Co,C1,...,Cn)
    Co  = C(1);
    Ci  = C(2:end);

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Obtain interpolated potentials at S (eq.1, Perrin et al., 1989)
    % V(s) = Co + sum( Ci * g(x) )

    % get spherical electrode radius
    [r,x,y,z] = elec_sphere_fit(X,Y,Z,0,0,0,0);
    % Generate spherical points for interpolation
    [x,y,z]   = elec_sphere_points(16,Npoints,r);
    S         = [x y z];

    fprintf('...Spherical Interpolation Progress:\n');
    rows = 80;  % progress indicator

    for p = 1:length(S)

        B = S(p,:);
        Cos = cosines(A,B);         %(1xN)

        Gx  = spheric_spline(Cos);  %(1xN)

        CiGx = Ci .* Gx';           %(1xN)

        Vi(p,1) = Co + sum(CiGx);

        fprintf('.');  % progress indicator
        if([p] == rows ) fprintf('\n'); rows = rows + 80; end
    end

return

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Solve eq. 3 Perrin et al. (1989)
% g(COS) = 1/4pi * sum[n=1:inf] (( (2*n+1)/(n^m * (n+1)^m) ) * Pn(COS));

function [Gx] = spheric_spline(Cosine)

    m = 4;    N = 7;    % gives accuracy of 10^-6

    P = legendre(N,Cosine);
    %P = LEGENDRE(N,X) computes the associated Legendre functions
    %of degree N and order m = 0, 1, ..., N, evaluated for each element
    %of X.
    %In general, P has one more dimension than X.
    %Each element P(m+1,i,j,k,...) contains the associated Legendre
    %function of degree N and order m evaluated at X(i,j,k,...).

    ndim = ndims(P);
    switch ndim
    case 2, P = P(2:N+1,:);
    case 3, P = P(2:N+1,:,:);
    case 4, P = P(2:N+1,:,:,:);
    otherwise
    end

    k = (1/4 * pi);

    for n = 1:(N),  Series(n,1) = (2*n + 1) / (n^(m-1) * (n+1)^(m-1));  end

    if min(size(Cosine)) == 1,    Gx      = k * ( Series' * P );
    else
        for i = 1:length(Cosine), Gx(i,:) = k * ( Series' * P(:,:,i) );
        end
    end
return

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Solve eq. 2 Perrin et al. (1989)
function [C] = spline_coefficients(Gx,V)

    % add ones to first row & column of Gx
    tmp =  ones(size(V));       Gx   = [tmp Gx];
    tmp = [ones(size(V))' 1]';  Gx   = [tmp Gx']';

    Gx(1,1) = 0;    % according to Murk
    %Gx(1,1) = 1;    % according to EMSE, Greenblatt

    CoV = [0 V']';

    C = Gx\CoV;
return

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Cos] = cosines(A,B)

    for     a = 1:size(A,1),  Aa = A(a,:); A_len = norm(Aa);
        for b = 1:size(B,1),  Bb = B(b,:); B_len = norm(Bb);

            Cos(a,b) = dot(Aa,Bb) / (A_len * B_len);
        end
    end
return

author: PatternRecognition

repo: OpenBMI


text:
function [ph_uw,msd]=uw_unwrap_from_grid(xy,pix_size)
%UW_UNWRAP_FROM_GRID unwrap PS from unwrapped gridded ifgs
%
%   Andy Hooper, June 2007
%
% ============================================================
% 03/2012 AH: Allow for all zero wrapped phase values
% 03/2012 AH: Allow for non-complex wrapped phase
% ============================================================

fprintf('Unwrapping from grid...\n')

uw=load('uw_grid','nzix','n_ps','grid_ij','ph_in','ph_in_predef');
uu=load('uw_phaseuw');

[n_ps,n_ifg]=size(uw.ph_in);
gridix=zeros(size(uw.nzix));
gridix(uw.nzix)=[1:uw.n_ps];

ph_uw=zeros(n_ps,n_ifg,'single');

for i=1:n_ps
    ix=gridix(uw.grid_ij(i,1),uw.grid_ij(i,2));
    if ix==0
        ph_uw(i,:)=nan; % wrapped phase values were zero
    else
        ph_uw_pix=uu.ph_uw(ix,:);
        if isreal(uw.ph_in)
          ph_uw(i,:)=ph_uw_pix+angle(exp(1i*(uw.ph_in(i,:)-ph_uw_pix)));
        else
          ph_uw(i,:)=ph_uw_pix+angle(uw.ph_in(i,:).*exp(-1i*ph_uw_pix));
        end
    end
end

if ~isempty(uw.ph_in_predef)
    predef_ix=~isnan(uw.ph_in_predef);
    meandiff=nanmean(ph_uw-uw.ph_in_predef);
    meandiff=2*pi*round(meandiff/2/pi);
    uw.ph_in_predef=uw.ph_in_predef+repmat(meandiff,n_ps,1);
    ph_uw(predef_ix)=uw.ph_in_predef(predef_ix);
end

msd=uu.msd;

author: dbekaert

repo: StaMPS

save_path: github-repos/MATLAB/dbekaert-StaMPS


text:
function title = p09_title ( )

%*****************************************************************************80
%
%% P09_TITLE returns the title of problem P09.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string TITLE, the title of the problem.
%
  title = 'Problem 9, Enright and Pryce #B4';

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function [Zpca T U mu eigVecs] = myPCA(Z,r)
%--------------------------------------------------------------------------
% Syntax:       Zpca = myPCA(Z,r);
%               [Zpca T U mu] = myPCA(Z,r);
%               [Zpca T U mu eigVecs] = myPCA(Z,r);
%
% Inputs:       Z is an (d x n) matrix containing n samples of a
%               d-dimensional random vector
%
%               r is the desired number of principal components
%
% Outputs:      Zpca is a (r x n) matrix containing the r principal
%               components - scaled to variance 1 - of the input samples
%
%               U and T are the PCA transformation matrices such that
%               Zr = U / T * Zpca + repmat(mu,1,n);
%               is the r-dimensional PCA approximation of Z
%
%               mu is the (d x 1) sample mean of Z
%
%               eigVecs is a (d x r) matrix containing the scaled
%               eigenvectors of the sample covariance of Z
%
% Description:  This function performs principal component analysis (PCA)
%               on the input samples
%
% Author:       Brian Moore
%               brimoor@umich.edu
%
% Date:         April 26, 2015
%--------------------------------------------------------------------------

% Center data
[Zc mu] = myCenter(Z);

% Compute truncated SVD
%[U S V] = svds(Zc,r); % Equivalent, but usually slower than svd()
[U S V] = svd(Zc,'econ');
U = U(:,1:r);
S = S(1:r,1:r);
V = V(:,1:r);

% Compute principal components
Zpca = S * V';
%Zpca = U' * Zc; % Equivalent but slower

% Whiten data, if desired
%[Zpca T] = myWhiten(Zpca);
T = eye(r); % No whitening

% Return scaled eigenvectors, if necessary
if (nargout >= 5)
    [~,n] = size(Z);
    eigVecs = bsxfun(@times,U,diag(S)' / sqrt(n));
end

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


text:
function scale = p14_scale ( neqn )

%*****************************************************************************80
%
%% P14_SCALE returns scale factors for problem p14.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NEQN, the number of equations.
%
%    Output, real SCALE(NEQN), the scaling factors.
%
  scale(1:neqn,1) = 1.0;

  return
end


text:
function ShowImage(data, height, width, nRow, nColumn, reverse)

[p, m] = size(data);
if width * height ~= p
    error('<EigFace>: incorrect width or height.\n');
end

if nColumn * nRow > m
    error('<EigFace>: incorrect column number or row number.\n');
end

lineW = 1;
horiW = lineW;
vertW = lineW;
% scaling data
data = data/max(data(:));
canvH = height*nRow+horiW*(nRow+1);
canvW = width*nColumn+vertW*(nColumn+1);

% construct canvas
canvColor = .5;
if reverse
    canvColor = 1-canvColor;
end
Y = canvColor*ones(canvH,canvW);

% draw the datas
vertProb = lineW;
for i=1:nRow
    horiProb = lineW;
    for j=1:nColumn
        if reverse
            Y(vertProb+(1:height),  horiProb+(1:width)) = 1-reshape(data(:,(i-1)*nColumn+j),[height,width]);
        else
            Y(vertProb+(1:height),  horiProb+(1:width)) = reshape(data(:,(i-1)*nColumn+j),[height,width]);
        end
        % draw dashed line
        if j~=nColumn
            Y(vertProb+(1:floor(height/3):height), horiProb+width+1) = ~canvColor;
        end
        if i~=nRow
            Y(vertProb+height+1, horiProb+(1:floor(width/3):width)) = ~canvColor;
        end
        % move horizontal probe
        horiProb = horiProb+width+vertW;
    end
    % move vertical probe
    vertProb = vertProb+height+horiW;
end

% rescaling
Y = Y*255;

% show the image
imagesc(Y);
colormap(gray);
axis image off;

author: andrewssobral

repo: lrslibrary


text:
function results = PTKDivideVolumeIntoSlices(region_mask, dimension, reporting)
    % PTKDivideVolumeIntoSlices. Divides an image volume into a number of thick slices
    %
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2014.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.

    [xc_mm, yc_mm, zc_mm] = region_mask.GetDicomCoordinates;
    midpoint_mm = [min(xc_mm(:)) + max(xc_mm(:)), min(yc_mm(:)) + max(yc_mm(:)), min(zc_mm(:)) + max(zc_mm(:))]/2;
    bounds = region_mask.GetBounds;
    coord_voxel_length_mm = region_mask.VoxelSize(dimension);

    % Get all values of coordinate between min and maximum values
    switch dimension
        case PTKImageOrientation.Axial
            coord_values = bounds(5) : bounds(6);
            coords = zc_mm;
        case PTKImageOrientation.Coronal
            coord_values = bounds(1) : bounds(2);
            coords = yc_mm;
        case PTKImageOrientation.Sagittal
            coord_values = bounds(3) : bounds(4);
            coords = xc_mm;
        otherwise
            reporting.Error('PTKDivideLungsIntoAxialBins:UnsupportedOrientation', 'The orientation was not recognised');
    end

    coord_values_mm = coords(coord_values);

    lung_base_mm = min(coord_values_mm) - coord_voxel_length_mm/2;
    lung_top_mm = max(coord_values_mm) + coord_voxel_length_mm/2;

    coord_offsets_for_all_voxels_mm = coords - lung_base_mm;

    % Compute the coordinates of the boundaries between bins
    bin_size_mm = 16;

    bin_locations = lung_base_mm + bin_size_mm/2 : bin_size_mm : lung_top_mm - bin_size_mm/2;
    bin_distance_from_base = bin_locations - lung_base_mm;

    % Compute bin numbers for each k coordinate
    bin_number = uint8(1 + max(0, floor(coord_offsets_for_all_voxels_mm/bin_size_mm)));

    switch dimension
        case PTKImageOrientation.Axial
            bin_matrix = repmat(shiftdim(bin_number, -2), region_mask.ImageSize(1), region_mask.ImageSize(2));
        case PTKImageOrientation.Coronal
            bin_matrix = repmat(bin_number, [1, region_mask.ImageSize(2), region_mask.ImageSize(3)]);
        case PTKImageOrientation.Sagittal
            bin_matrix = repmat(shiftdim(bin_number, -1), [region_mask.ImageSize(1), 1, region_mask.ImageSize(3)]);
        otherwise
            reporting.Error('PTKDivideLungsIntoAxialBins:UnsupportedOrientation', 'The orientation was not recognised');
    end

    bin_image_raw = bin_matrix.*uint8(region_mask.RawImage);
    bin_image = region_mask.BlankCopy;
    bin_image.ChangeRawImage(bin_image_raw);
    bin_image.ImageType = PTKImageType.Colormap;

    regions = PTKRegionDefinition.empty;
    for bin_index = 1 : numel(bin_distance_from_base)
        coordinates = PTKPoint(midpoint_mm(1), midpoint_mm(2), midpoint_mm(3));
        coordinates = PTKPoint.SetCoordinate(coordinates, dimension, bin_locations(bin_index));
        regions(bin_index) = PTKRegionDefinition(bin_index, bin_index, bin_distance_from_base(bin_index), coordinates);
    end

    results = [];
    results.BinImage = bin_image;
    results.BinRegions = regions;
end

author: tomdoel

repo: pulmonarytoolkit


text:
%GETVALUEOFASSIGNMENT Gets the value of a variable assignment in a factor.
%
%   v = GETVALUEOFASSIGNMENT(F, A) returns the value of a variable assignment,
%   A, in factor F. The order of the variables in A are assumed to be the
%   same as the order in F.var.
%
%   v = GETVALUEOFASSIGNMENT(F, A, VO) gets the value of a variable assignment,
%   A, in factor F. The order of the variables in A are given by the vector VO.
%
%   See also SETVALUEOFASSIGNMENT

% Copyright (C) Daphne Koller, Stanford University, 2012

function v = GetValueOfAssignment(F, A, VO)

if (nargin == 2),
    indx = AssignmentToIndex(A, F.card);
else
    map = zeros(length(F.var), 1);
    for i = 1:length(F.var),
        map(i) = find(VO == F.var(i));
    end;
    indx = AssignmentToIndex(A(map), F.card);
end;

v = F.val(indx);

author: anhncs

repo: Probabilistic-Graphical-Models


text:
function facenb=faceneighbors(t,opt)
%
% facenb=faceneighbors(t,opt)
%
% to find 4 face-neighboring elements of a tetrahedron
%
% author: Qianqian Fang, <q.fang at neu.edu>
%
% input:
%     t: tetrahedron element list, 4 columns of integers
%     opt: if opt='surface', return boundary triangle list
%          (should be the same as the face output from v2m)
%          if opt='rowmajor', same as 'surface', except the
%          order of the triangles are in the row-major order
%%
%          otherwise, return the element list for each element:
%          each row contains 4 numbers, representing the element
%          indices sharing triangular faces [1 2 3],[1 2 4],[1 3 4]
%          and [2 3 4] in order, where 1~4 is the node local index.
%          if the index is 0, indicating the face has no neighbor
%          (i.e. a boundary face)
%
% output:
%     facenb: see opt
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

faces=[t(:,[1,2,3]);
       t(:,[1,2,4]);
       t(:,[1,3,4]);
       t(:,[2,3,4])];

faces=sort(faces,2);
[foo,ix,jx]=unique(faces,'rows');
if(isoctavemesh)
        u=unique(jx);
        qx=u(hist(jx,u)==2);
else
        vec=histc(jx,1:max(jx));
        qx=find(vec==2);
end

nn=max(t(:));
ne=size(t,1);
facenb=zeros(size(t));

% now I need to find all repeatitive elements
% that share a face, to do this, unique('first')
% will give me the 1st element, and 'last' will
% give me the second. There will be no more than 2

% doing this is 60 times faster than doing find(jx==qx(i))
% inside a loop

if(isoctavemesh || datenum(version('-date'))>datenum('January 27 2006')) % compare to matlab 7.2
	[ujx,ii]=unique(jx,'first');
	[ujx,ii2]=unique(jx,'last');
else
	ujx=unique(jx);
	[t1,ii2]=ismember(ujx,jx);
	[t1,ii]=ismember(ujx,flipwd(jx(:)));
	ii=length(jx)-ii+1;
end

% iddup is the list of all pairs that share a common face

iddup=[ii(qx) ii2(qx)];
faceid=ceil(iddup/ne);
eid=mod(iddup,ne);
eid(eid==0)=ne;

% now rearrange this list into an element format

for i=1:length(qx)
	facenb(eid(i,1),faceid(i,1))=eid(i,2);
	facenb(eid(i,2),faceid(i,2))=eid(i,1);
end

% facenb may contain 0s, that just means the corresponding
% face is a boundary face and has no neighbor.

% if the second option is 'surface', I am going to find
% and return surface patches only

if(nargin==2)
  if(strcmp(opt,'surface'))
	facenb=faces(find(facenb==0),:);
  elseif(strcmp(opt,'rowmajor'))
	index=[1:length(faces)];
	index=(reshape(index,[],4))';
	faces=faces(index(:),:);
	facenb=faces(find(facenb'==0),:);
  else
        error(['supplied option "' opt '" is not supported.']);
  end
end

author: fangq


text:
function [coef, res, wres, ymoco] = robust_ar_fit( y, Pmax )
    [~, res] = ar_fit(y, Pmax);

    w = wfun(res);
    [coef, ~] = ar_fit(w.*y, Pmax);

    res     = filter([1; -coef(2:end)], 1, y-coef(1));
    wres    = filter([1; -coef(2:end)], 1, w.*y-coef(1));

    ymoco   = filter(1, [1; -coef(2:end)], w.*res);
end

function w = wfun(r)
    s = mad(r, 0) / 0.6745;
    r = r/s/4.685;

    w = (1 - r.^2) .* (r < 1 & r > -1);
end

author: BUNPC


text:
function tbxStruct=Demos
% Demos   Demo List infomation for NURBS Toolbox

% D.M. Spink
% Copyright (c) 2000

if nargout == 0; demo toolbox; return; end

tbxStruct.Name='nurbs';
tbxStruct.Type='Toolbox';

tbxStruct.Help= ...
        {' The NURBS Toolbox provides commands for the construction'
         ' and use of Non-Uniform Rational B-Splines (NURBS).'
         ' '};

tbxStruct.DemoList={
                '3D Line','demoline',
                'Rectangle','demorect',
                'Circle and Arc','democirc',
                'Helix','demohelix',
                'Ellipse', 'demoellip',
                'Test Curve','democurve',
                'Test Surface','demosurf',
                'Bilinear Surface','demo4surf',
                'Knot Insertion','demokntins',
                'Degree Elevation','demodegelev',
                'Curve derivatives','demodercrv',
                'Surface derivatives','demodersrf'
                'Cylinderical arc','democylind',
                'Ruled Surface','demoruled',
                'Coons Surface','democoons',
                'Test Extrusion','demoextrude',
                'Test Revolution - Cup','demorevolve',
                'Test Revolution - Ball & Torus','demotorus',
                '2D Geomtery','demogeom'};

author: Sable

repo: mcbench-benchmarks


text:
function sVF = rdivide(sVF, sF2)
%
% Syntax
%   sVF = sVF ./ sF
%   sVF = sVF ./ a
%
% Input
%  sVF - @S2VectorFieldTri
%  sF  - @S2Fun
%  a   - double
%
% Output
%  sF - @S2VectorFieldTri
%

if isnumeric(sF2)
  sVF.values = sVF.values ./ sF2;
else
  sVF.values = sVF.values ./ sF2.values;
end

end

author: mtex-toolbox

repo: mtex

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


text:
function mesh_write_fs_overlay(p)

% mesh_write_fs_overlay - Save mesh CData to FreeSurfer overlay file
%
% USEAGE: mesh_write_fs_overlay(p)
%
% Write a binary overlay file (*.w) for each mesh in p.mesh.data.
% If any cells of p.mesh.data.meshtype are empty, they are skipped.
%
% This function outputs an *.w overlay file from the
% vertex scalar data contained in p.mesh.data.Cdata - if it
% contains a timeseries, the output values are taken from
% the column specified in p.mesh.samplePoint.
%
% All output is handled by fs_write_wfile.
%
% See the FreeSurfer website at http://surfer.nmr.mgh.harvard.edu/
% for more information.
%

% $Revision: 1.1 $ $Date: 2009-04-28 22:13:58 $

% Licence:  GNU GPL, no implied or express warranties
% History:  10/2002, Darren.Weber_at_radiology.ucsf.edu
%           01/2003, Darren.Weber_at_radiology.ucsf.edu
%                    now using fs_write_surf and fs_write_wfile
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

fprintf('\nMESH_WRITE_FS_OVERLAY...\n');

if ~exist('p','var'),
    error('...no input p struct.\n');
elseif isempty(p),
    error('...input p struct is empty.\n');
elseif isempty(p.mesh.data),
    error('...input p struct has no mesh data.\n');
end

[path,name,ext] = fileparts(strcat(p.mesh.path,filesep,p.mesh.file));
file = fullfile(path,[name ext]);

fprintf('...writing FreeSurfer overlays to:\n\t%s\n',path);

tic;

Meshes = p.mesh.data.meshtype;

[path,name,ext] = fileparts(file);

for i=1:size(Meshes,2),

    if Meshes{i},

        % check for mesh Cdata
        if size(p.mesh.data.Cdata,2) >= i,
            if ~isempty(p.mesh.data.Cdata{i}),
                if size(p.mesh.data.Cdata{i},2) > 1,
                    % Obtain the Cdata at the selected time point
                    w = p.mesh.data.Cdata{i}(:,p.mesh.samplePoint);
                else
                    w = p.mesh.data.Cdata{i};
                end

                outputExt = [ext, '.w'];
                outputName = strcat(name,'.',Meshes{i});
                outputFile = fullfile(path,[outputName outputExt]);

                fprintf('...writing overlay: %s\n',[outputName outputExt]);
                fs_write_wfile(outputFile,w);
            else
                msg = sprintf('\np.mesh.data.Cdata{%d} is empty\n',i);
                warning(msg);
            end
        else
            msg = sprintf('\nno p.mesh.data.Cdata{%d}\n',i);
            warning(msg);
        end
    end
end

t=toc; fprintf('...done (%5.2f sec).\n\n',t);

return


text:
function     draw(graphic,value,v_EbN0_dB,v_ber,figur);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%                                                                       %
%%      Name: Draw.m                                                     %
%%                                                                       %
%%       Description: This file draws each one of the results of the     %
%%        different tests.                                               %
%%                                                                       %
%%       Parameters: It receives the necessary parameters to be able     %
%%        to draw the corresponding graphs.                              %
%%                                                                       %
%%       Result: It gives back grapsh for each simulations.              %
%%                                                                       %
%%                                                                       %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
grids on;
switch graphic
    case 'Channels'       % Here "value" is equivalent of the channel that we are simulating.
        switch value
            case 1
                form = 'y-';
            case 2
                form = 'm-o';
            case 3
                form = 'c-o';
            case 4
                form = 'r-o';
            case 5
                form = 'g-o';
            case 6
                form = 'b-*';
        end
        semilogy(v_EbN0_dB,v_ber,form);
        hold on;drawnow;

    case 'Encode'      % "value" is representing whether encoding is being used or not.
        switch value
            case 0                              % Uncoded
                form = 'o-';
            case 1                              % Encoded
                form = 'g-o';
        end
        semilogy(v_EbN0_dB,v_ber,form);
        hold on;drawnow;

    case 'CP'        % "value" is the size of the Cyclic Prefix.
        switch value
            case 1/4
                form = 'y-';
            case 1/8
                form = 'm-';
            case 1/16
                form = 'c-';
            case 1/32
                form = 'r-';
        end
        semilogy(v_EbN0_dB,v_ber,form);
        hold on;drawnow;

     case 'BW'            % Here "value" is equivalent to the bandwidth-BW.
        switch value
            case 28
                form = 'y-.';
            case 20
                form = 'm-.';
            case 15
                form = 'c-.';
            case 10
                form = 'r-.';
            case 2.50
                form = 'g-.';
            case 1.25
                form = 'b-*';
        end
        semilogy(v_EbN0_dB,v_ber,form);
        hold on;drawnow;

end


text:
function varargout=roteu2qr(varargin)
%
% For calling details please see v_roteu2qr.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_roteu2qr.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: roteu2qr.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_roteu2qr(varargin{:});
else
    v_roteu2qr(varargin{:});
end

author: ImperialCollegeLondon

repo: sap-voicebox


text:
function obj=MOcovMFile(fn)
% instantiate MOcov m-file representation of line coverage
%
% obj=MOcovMFile(fn)
%
% Input:
%   fn                  Filename of .m file
%
% Output:
%   obj                 MOcovMFile instance that contains, internally,
%                       the filename, each line of the m-file, which lines
%                       are executable, and an array counting how often
%                       each line has been executed.

    props=get_mfile_props(fn);
    obj=class(props,'MOcovMFile');

function props=get_mfile_props(fn)
    % get properties of a matlab file. The output has
    %   .filename: filename of mfile
    %   .executable:        Nx1 boolean array for N lines,
    %                       indicating which lines can be executed
    %   .executed_count:    Nx1 false array
    %   .lines              Nx1 cellstr with lines of mfile

    % read the matlab file
    fid=fopen(fn);
    cleaner=onCleanup(@()fclose(fid));
    s=fread(fid,inf,'char=>char')';

    % split by newline character
    lines=regexp(s,sprintf('\n'),'split');

    % state variables
    in_line_continuation = false;  % whether the previous line contained a
                                   % line continuation, i.e. ended with '...'

    inside_class = false;  % the file contains a `classdef` statement

    inside_properties = false; % a `properties` section was opened
                               % but not closed.

    % see which lines are executable
    n=numel(lines);
    executable=false(n,1);
    for k=1:n
        line=lines{k};

        line_without_quotes=regexprep(line,'''.*''','');

        comment_start=find(line_without_quotes=='%',1);
        if isempty(comment_start)
            line_code=line_without_quotes;
        else
            line_code=line_without_quotes(1:(comment_start-1));
        end

        line_code_trimmed=regexprep(line_code,'\s','');
        if isempty(line_code_trimmed)
            continue;
        end

        % Check for statements that ~changes/depends on~ the 'parser' state
        classdef_statement = line_is_class_def(line_code_trimmed);
        inside_class = inside_class || classdef_statement;

        properties_section = line_opens_properties_section(...
            line_code_trimmed, inside_class);
        % When a properties section is opened set the inside_properties flag
        inside_properties = inside_properties || properties_section;
        % When inside_properties is set and an 'end' appears, the section
        % is closed.
        % This can be considered a hack, since assumes no code that includes
        % an `end` is allowed inside properties.
        inside_properties = inside_properties && ...
            ~line_ends_with_end_statement(line_code_trimmed);

        % classify line
        executable(k)=~(...
            in_line_continuation || ...
            line_is_function_def(line_code_trimmed) || ...
            classdef_statement || ...
            line_opens_methods_section(line_code_trimmed, inside_class) || ...
            inside_properties || ...  % Arbitrary code cannot run inside
            ...                       % properties section, just a subset
            line_is_case_statement(line_code) || ...
            line_is_elseif_statement(line_code) || ...
            line_is_else_statement(line_code) || ...
            line_is_sole_end_statement(line_code_trimmed));

        in_line_continuation=line_has_line_continuation(line_code);
    end

    % put results in struct
    props=struct();
    props.filename=mocov_get_absolute_path(fn);
    props.executable=executable;
    props.executed_count=zeros(size(props.executable));
    props.lines=lines;

function tf=line_is_function_def(line)
    % returns true if the string in line indicates a function definition
    newline=sprintf('\n');
    pat=[newline '\s*function([\[\]\w ,~]*=)?[ ]*'...
                 '(?<name>[a-zA-Z]\w*)(\([^\)]*\))?'];

    tf=~isempty(regexp([newline line],pat,'once'));

function tf=line_is_class_def(line)
    % returns true if the line opens a class definition
    tf=~isempty(regexp(line,'^\s*classdef\W*','once'));

function tf=line_opens_methods_section(line, inside_class)
    % returns true if the line opens a method section inside class definition
    tf=inside_class && ...
       ~isempty(regexp(line,'^\s*methods\s*(\([^\(\)]*\))?\s*$','once'));

function tf=line_opens_properties_section(line, inside_class)
    % returns true if the line opens a properties section inside class definition
    tf=inside_class && ...
       ~isempty(regexp(line,'^\s*properties\s*(\([^\(\)]*\))?\s*$','once'));

function tf=line_is_sole_end_statement(line)
    % returns true if the string in line is just an end statement
    tf=isempty(regexprep(line,'([\s,;]|^)?end([\s,;]|$)?',''));

function tf=line_is_case_statement(line)
    tf=~isempty(regexp(line,'^\s*case\W*','once'));

function tf=line_is_elseif_statement(line)
    tf=~isempty(regexp(line,'^\s*elseif\W*','once'));

function tf=line_is_else_statement(line)
    tf=~isempty(regexp(line,'^\s*else\W*','once'));

function tf=line_ends_with_end_statement(line)
    % returns true if the line has a finishing 'end'
    tf=~isempty(regexp(line,'(^|\W)end\s*[,;]?\s*$','once'));

function tf=line_has_line_continuation(line)
    % returns true if the line contains a line continuation
    tf=~isempty(regexp(line,'\.\.\.','once'));

author: qMRLab

repo: qMRLab

save_path: github-repos/MATLAB/qMRLab-qMRLab


text:
function solver = fiordos(self)

% The first dimin equalities are used to fix some parameters
aux = self.model.F_struc(1:self.dimin,:);

% remove these
self.model.F_struc(1:self.dimin(1),:) = [];
self.model.K.f = self.model.K.f - self.dimin(1);

% Extract all bounds and move from Ab to ub/lb
temp =  presolve_bounds_from_modelbounds(self.model,1);
self.model = temp;
% Any bound constraints?
n = length(temp.lb);
bounded_ub = find(~isinf(temp.ub));
bounded_lb = find(~isinf(temp.lb));
if length(bounded_lb) == n && length(bounded_ub) == n
    % All have finite bounds.
    X = EssBox(n, 'l',temp.lb, 'u',temp.ub);
    X = SimpleSet(X);
elseif  ~isempty(bounded_ub) || ~isempty(bounded_lb)
    % Only some bounds. Keep them as general constraints
    X = [];
    for i = 1:n
        if isinf(temp.lb(i)) && isinf(temp.ub(i))
            X{end+1} = EssRn(1);
        elseif  ~isinf(temp.lb(i)) && ~isinf(temp.ub(i))
            X{end+1} =  EssBox(1, 'l',temp.lb(i), 'u',temp.ub(i));
        elseif isinf(temp.ub(i))
            X{end+1} =  EssRnplus(1, 'shift', temp.lb(i));
        else
            X{end+1} =  EssRnplus(1, 'shift', temp.ub(i),'rot',-1);
        end
    end
    X = SimpleSet(X{:});
else
    % No bounds
    X = EssRn(n);
    X = SimpleSet(X);
end

% Put back a placeholder for fixing the parameters
self.model.F_struc = [aux;self.model.F_struc];
self.model.F_struc(1:self.dimin(1),1)=0; % Now fixed to zero
self.model.K.f = self.model.K.f + self.dimin(1);

op = OptProb('H',2*full(self.model.Q), 'g',self.model.c, 'X',X, 'Ae',-self.model.F_struc(1:self.model.K.f,2:end), 'be','param');

%instantiate solver
s = Solver(op,'approach','primal-dual');
%, 'algoOuter','gm', 'algoInner','fgm');
%optionally change settings, e.g.
%-maximum number of iterations
%s.setSettings('algoOuter', 'maxit',10000);
%s.setSettings('algoInner', 'maxit',9000);
%-gradient-map stopping criterion
%s.setSettings('algoOuter', 'stopg',true, 'stopgEps',1e-3);
%s.setSettings('algoInner', 'stopg',true, 'stopgEps',1e-5);
%generate solver code
s.generateCode('prefix','demo_','forceOverwrite',1);
demo_mex_make();

compiledsolver = @(x)demo_mex(x);
b0 = self.model.F_struc(1:self.model.K.f,1);
B0 = [eye(self.dimin(1));zeros(self.model.K.f-self.dimin(1),self.dimin(1))];
map = self.map;
dimout = self.dimout;
mask = self.mask{1};
solver = @(x)(fiordos_call(compiledsolver,x,B0,b0,mask,map,dimout));

author: yalmip

repo: YALMIP

save_path: github-repos/MATLAB/yalmip-YALMIP


text:
% dbm_get_hidden
% Copyright (C) 2011 KyungHyun Cho, Tapani Raiko, Alexander Ilin
%
%This program is free software; you can redistribute it and/or
%modify it under the terms of the GNU General Public License
%as published by the Free Software Foundation; either version 2
%of the License, or (at your option) any later version.
%
%This program is distributed in the hope that it will be useful,
%but WITHOUT ANY WARRANTY; without even the implied warranty of
%MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%GNU General Public License for more details.
%
%You should have received a copy of the GNU General Public License
%along with this program; if not, write to the Free Software
%Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
%
function [h_mf] = dbm_get_hidden(x0, D, max_iter, tol, reg)

if nargin < 3
    max_iter = 10;
end

if nargin < 4
    tol = 1e-6;
end

if nargin < 5
    reg = 0;
end

h_mf = dbm_get_hidden_raw(x0, D.data.binary, D.structure.layers, ...
    D.W, D.biases, D.sigmas, max_iter, tol, reg, D.centering.use, D.centering.centers);

author: kyunghyuncho

repo: deepmat


text:
% averef() - convert common-reference EEG data to average reference
%            Note that this old function is not being used in EEGLAB. The
%            function used by EEGLAB is reref().
%
% Usage:
%   >> data = averef(data);
%   >> [data_out W_out S_out meandata] = averef(data,W);
%
% Inputs:
%   data - 2D data matrix (chans,frames*epochs)
%   W    - ICA weight matrix
%
% Outputs:
%   data_out - Input data converted to average reference.
%   W_out    - ICA weight matrix converted to average reference
%   S_out    - ICA sphere matrix converted to eye()
%   meandata - (1,dataframes) mean removed from each data frame (point)
%
% Note: If 2 args, also converts the weight matrix W to average reference:
%         If ica_act = W*data, then data = inv(W)*ica_act;
%         If R*data is the average-referenced data,
%         R*data=(R*inv(W))*ica_act and W_out = inv(R*inv(W));
%         The average-reference ICA maps are the columns of inv(W_out).
%
% Authors: Scott Makeig and Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 1999
%
% See also: reref()

% Copyright (C) 1999 Scott Makeig, SCCN/INC/UCSD, scott@sccn.ucsd.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

% 12/16/99 Corrected denomiator on the suggestion of Ian Nimmo-Smith, Cambridge UK
% 01-25-02 reformated help & license -ad

function [data, W, S, meandata] = averef(data, W, S)

if nargin<1
  help averef
  return
end
chans = size(data,1);
if chans < 2
  help averef
  return
end

% avematrix = eye(chans)-ones(chans)*1/chans;
% data = avematrix*data; % implement as a matrix multiply
% else (faster?)

meandata = sum(data)/chans;
data = data - ones(chans,1)*meandata;

% treat optional ica parameters
if nargin == 2
	winv  = pinv(W);
    size1 = size(winv,1);
	avematrix = eye(size1)-ones(size1)*1/size1;
	W = pinv(avematrix*winv);
end;
if nargin >= 3
	winv = pinv(W*S);
    size1 = size(winv,1);
	avematrix = eye(size1)-ones(size1)*1/size1;
	W = pinv(avematrix*winv);
	S = eye(chans);
end;


text:
function seg = segCreate(name, classPath,  grayPath, anatFile);
% Create an empty segmentation object. Includes a description of
% the segmentation format.
%
% seg = segCreate(<name>, <classPath>, <grayPath>, <anatFile>);
%
% If any of the input arguments are omitted, prompts for them.
%
% returns a struct with the following fields:
%   name: name of the segmentation. E.g., 'Right', 'Left', 'Both'.
%   subject: subject info.
%   class: path to classification file, or loaded class struct (see
%           readClassFile for description).
%   nodes: 8xN list of gray nodes (see segGet for a description).
%   edges: set of gray edges.
%   mesh: cell array of meshes which may be loaded/built from this
%   segmentation.
%   anatFile: name or path to anat file that was segmented.
%   created: date stamp, set in this function, when it was first created.
%   modified: date stamp, describing the time when it was last modified.
%
% Note that the segmentation struct, in itself, doesn't contain info on the
% anatomy that was segmented. Rather, it simply points to the original
% segmented file. This is because I am intending for segmentations to be
% attached to an mr struct, rather than the other way around (e.g., left,
% right, and both segmentations on the anatomy).
%
%
% ras, 04/06.
if notDefined('name')
    name = inputdlg('Name of Segmentation?', mfilename, 1, {'Right'});
    if isempty(name), return; else, name = name{1}; end
end

if notDefined('classPath')
    classPath = mrvSelectFile('r', '*lass', 'Select Class File');
end

[p f ext] = fileparts(classPath);

if notDefined('grayPath') & ~strfind(ext, 'nii')
	% (don't need a gray graph for NIFTI classifications...)
    grayPath = mrvSelectFile('r', '*ray', 'Select Gray File', p);
end

if notDefined('anatFile')
	ttl = 'Select the anatomy file that was segmented';
    anatFile = mrvSelectFile('r', '*', ttl, fileparts(p));
end

seg.name = name;
seg.subject = [];
seg.anatFile = anatFile;
seg.class = classPath;
seg.gray = grayPath;
seg.nodes = [];
seg.edges = [];
seg.mesh = {};
seg.settings.mesh = 0; % currently selected mesh
seg.params.numLayers = 3;
seg.params.layer0 = 0;
seg.params.meshDir = '';
seg.created = datestr(clock);
seg.modified = datestr(clock);
if isempty('grayPath')
	[seg.nodes seg.edges] = mrgGrowGray(classPath, seg.params.numLayers, ...
                                    seg.params.layer0);
else
	[seg.nodes seg.edges] = readGrayGraph(grayPath);
end

try
	hdr = mrLoadHeader(anatFile);
	seg.subject = hdr.info;
	seg.voxelSize = hdr.voxelSize(1:3);
catch
	disp('Couldn''t load subject header info. Guessing 1x1x1 voxel size')
	seg.voxelSize = [1 1 1];
end

if exist(fullfile(fileparts(seg.class), '3DMeshes'), 'dir')
    seg.params.meshDir = fullfile(fileparts(seg.class), '3DMeshes');
end

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
%GETOUT_CONV Get out_conv field in mapping
%
%    OUT_CONV = GETOUT_CONV(W)

author: marianux

repo: ecg-kit

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


text:
function y = aprod( mode, m, n, x, iw, rw )
% This is the simplest example for testing  LSQR.
% :math:`A = rw`.
% If `mode = 1`, `aprod` computes :math:`y = A x`.
% Ff `mode = 2`, `aprod` computes :math:`y = A^T x`.
% for some matrix  `A`.

if mode == 1,
   y = rw*x;
else
   y = rw'*x;
end

author: opencobra

repo: cobratoolbox


text:
function [x,rec] = fsearch(fun,x0,varargin)
% FSEARCH Finds the minimum of a combinatorial function using forward search
%
%   X = FSEARCH(FUN, X0) attempts to find a combination of elements
%   of X0 which locally minimize the function FUN using forward
%   search. FUN accepts input X and returns scalar function value F
%   evaluated at X. X0 must be a vector of candidate indexes.
%   Returned X contains indexes locally minimizing the function
%   FUN.
%
%   X = FSEARCH(FUN, X0, OPTIONS) allows use of optional
%   search parameters. See FSEARCH_OPT for details.
%
%   X = FSEARCH(FUN, X0, OPTIONS, P1, ..., Pn) P1,...,Pn are
%   additional parameters passed to the function FUN.
%
%   [X,REC] = FSEARCH(FUN, X0, ...) returns record of search as a
%   array of structs.
%
%   In forward search the elements are chosen one at the time. The
%   element that minimizes the function value when added to the set
%   is chosen at each round. In a case of tie choose randomly.
%
% Copyright (c) Aki Vehtari (2007)

% This software is distributed under the GNU General Public
% License (version 3 or later); please refer to the file
% License.txt, included with the software, for details.

% 2007-02-23  Aki Vehtari  <Aki.Vehtari@hut.fi>
%             Use same parameter order as in fminunc etc.
%             Minimize instead of maximize
%             Total rewrite.
if nargin>2
  opt=varargin{1};
  varargin(1)=[];
end

x0=x0(:)';
nx = size(x0,2);  % number of elements
chosen = [];      % the elements chosen sofar
nchosen = 0;      % number of chosen elements
% Options
opt = fsearch_opt(opt);
if opt.nsel>nx
  opt.nsel=nx;
end

% The loop
value=Inf;
minvalue=value;
while (nchosen < opt.nsel)
  values=zeros(nx,1);
  for i1=1:nx
    values(i1) = feval(fun,union(chosen,x0(i1)),varargin{:});
    if (opt.display >= 2)
      fprintf('%d %.5g\n', x0(i1),  values(i1));
    end
  end
  % Let's get the index of the best element
  % In a case of tie, choose randomly
  value=min(values);
  mini=randpick(find(values==value));
  if (opt.stop && value>=minvalue)
    if opt.display
      fprintf('Stopping because value not decreasing\n');
    end
    break
  end
  chosen = union(chosen,x0(mini));   % Add the element into the set of chosen
  nchosen = nchosen + 1;
  % copy some information of this round to struct rec
  rec(nchosen).chosen = chosen;
  rec(nchosen).candidates = x0;
  rec(nchosen).values = values;
  x0(mini) = [];                     % remove it from the x0
  nx=nx-1;
  if value<minvalue
    minvalue=value;
    minvaluei=nchosen;
  end

  if (opt.display >= 1)
    fprintf(' Value: %.4g\n Chosen: %s\n', value, num2str(chosen));
  end

  if (minvalue<opt.stopvalue)
    if opt.display
      fprintf('Objective function value smaller than specified goal\n');
    end
    break
  end
end
x=rec(minvaluei).chosen;

author: gpstuff-dev

repo: gpstuff

save_path: github-repos/MATLAB/gpstuff-dev-gpstuff


text:
% Examples employing logarithms, exponentials, and entropy functions
%
%  max_entropy.m                    - Entropy maximization
%  sparse_covariance_est.m          - Sparse covariance estimation for Gaussian variables
%  sparse_covariance_est_tradeoff.m - Sparse covariance estimation for Gaussian variables
%  weighted_analytic_center.m       - Weighted analytic center of a set of linear inequalities
help Contents

author: cvxr

repo: CVX

save_path: github-repos/MATLAB/cvxr-CVX


text:
function point = projPointOnLine3d(point, line)
%PROJPOINTONLINE3D Project a 3D point orthogonally onto a 3D line.
%
%   PT2 = projPointOnLine3d(PT, LINE).
%   Computes the (orthogonal) projection of 3D point PT onto the 3D line
%   LINE.
%
%   Function works also for multiple points and lines. In this case, it
%   returns multiple points.
%   Point PT1 is a N-by-3 array, and LINE is a N-by-6 array.
%   Result PT2 is a N-by-3 array, containing coordinates of orthogonal
%   projections of PT1 onto lines LINE.
%
%
%   See also
%   projPointOnLine, distancePointLine3d

% ------
% Author: David Legland
% E-mail: david.legland@inrae.fr
% Created: 2012-08-23
% Copyright 2012-2022 INRA - TPV URPOI - BIA IMASTE

% direction vector of the line
vx = line(:, 4);
vy = line(:, 5);
vz = line(:, 6);

% difference of point with line origin
dx = point(:,1) - line(:,1);
dy = point(:,2) - line(:,2);
dz = point(:,3) - line(:,3);

% Position of projection on line, using dot product
delta = vx .* vx + vy .* vy + vz .* vz;
tp = (dx .* vx + dy .* vy + dz .* vz) ./ delta;

% convert position on line to cartesian coordinates
point = [line(:,1) + tp .* vx, line(:,2) + tp .* vy, line(:,3) + tp .* vz];

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function [ind,value] = cnn_classifier(A,dims,classifier,thr)

%cnn_classifer classify spatial components using a pretrained CNN
%classifier using the keras importer add on.
%   IND = cnn_classifier(A,dims,classifier,thr) returns a binary vector indicating
%   whether the set of spatial components A, with dimensions of the field
%   of view DIMS, pass the threshold THR for the given CLASSIFIER
%
%   [IND,VALUE] = cnn_classifier(A,dims,classifier,thr) also returns the
%   output value of the classifier
%
%   INPUTS:
%   A:              2d matrix
%   dims:           vector with dimensions of the FOV
%   classifier:     path to pretrained classifier model (downloaded if it
%                       doesn't exist)
%   thr:            threshold for accepting component (default: 0.2)
%
%   note: The function requires Matlab version 2017b (9.3) or later, Neural
%   Networks toolbox version 2017b (11.0) or later, the Neural Network
%   Toolbox(TM) Importer for TensorFlow-Keras Models.

%   Written by Eftychios A. Pnevmatikakis. Classifier trained by Andrea
%   Giovannucci, Flatiron Institute, 2017

K = size(A,2);                          % number of components

if verLessThan('matlab','9.3') || verLessThan('nnet','11.0') || isempty(which('importKerasNetwork'))
    warning(strcat('The function cnn_classifier requires Matlab version 2017b (9.3) or later, Neural\n', ...
        'Networks toolbox version 2017b (11.0) or later, the Neural Networks ', ...
        'Toolbox(TM) Importer for TensorFlow-Keras Models.'))
    ind = true(K,1);
    value = ones(K,1);
else
    if ~exist('thr','var'); thr = 0.2; end

    A = A/spdiags(sqrt(sum(A.^2,1))'+eps,0,K,K);      % normalize to sum 1 for each compoennt
    A_com = extract_patch(A,dims,[50,50]);  % extract 50 x 50 patches

    if ~exist(classifier,'file')
        url = 'https://www.dropbox.com/s/1csymylbne7yyt0/cnn_model.h5?dl=1';
        classifier = 'cnn_model.h5';
        outfilename = websave(classifier,url);
    end

    net_classifier = importKerasNetwork(classifier,'ClassNames',["rejected","accepted"]);
    out = predict(net_classifier,double(A_com));
    value = out(:,2);
    ind = (value >= thr);
end

author: flatironinstitute

repo: CaImAn-MATLAB


text:
% EX_STOKES_TWISTED_PIPE: solve the Stokes problem on a twisted pipe using a B-spline discretization.

% 1) PHYSICAL DATA OF THE PROBLEM
clear problem_data
% Physical domain, defined as NURBS map given in a text file
problem_data.geo_name = 'geo_twisted_pipe.mat';

% Type of boundary conditions for each side of the domain
problem_data.nmnn_sides   = [1 2];
problem_data.drchlt_sides = [3 4 5 6];

% Physical parameters
problem_data.viscosity = @(x, y, z) ones (size (x));

% Force term
fx = @(x, y, z) ones(size(x));
fy = @(x, y, z) zeros(size(x));
fz = @(x, y, z) zeros(size(x));
problem_data.f  = @(x, y, z) cat(1, reshape (fx (x,y,z), [1, size(x)]), reshape (fy (x,y,z), [1, size(x)]), reshape (fz (x,y,z), [1, size(x)]));

% Boundary terms
problem_data.h  = @(x, y, z, iside) zeros ([3, size(x)]); %Dirichlet boundary condition
problem_data.g  = @(x, y, z, iside) zeros ([3, size(x)]); %Neumann boundary condition

% 2) CHOICE OF THE DISCRETIZATION PARAMETERS
clear method_data
method_data.element_name = 'TH';
method_data.degree       = [2 2 2]; % Degree of the splines (pressure space)
method_data.regularity   = [1 1 1]; % Regularity of the splines
method_data.nsub         = [2 2 2]; % Number of subdivisions
method_data.nquad        = [4 4 4]; % Points for the Gaussian quadrature rule

% 3) CALL TO THE SOLVER
[geometry, msh, space_v, vel, space_p, press] = solve_stokes (problem_data, method_data);

% 4) POST-PROCESSING
% 4.1) EXPORT TO PARAVIEW

output_file = 'TwistedPipe_BSP_Deg2_Reg1_Sub2';

fprintf ('The result is saved in the files %s \n and %s \n \n', ...
           [output_file '_vel'], [output_file '_press']);
vtk_pts = {linspace(0, 1, 10), linspace(0, 1, 10), linspace(0, 1, 10)};
sp_to_vtk (press, space_p, geometry, vtk_pts, [output_file '_press'], 'press')
sp_to_vtk (vel,   space_v, geometry, vtk_pts, [output_file '_vel'  ], {'velocity', 'divergence'}, {'value', 'divergence'})

%!test
%! problem_data.geo_name = 'geo_twisted_pipe.mat';
%! problem_data.nmnn_sides   = [1 2];
%! problem_data.drchlt_sides = [3 4 5 6];
%! problem_data.viscosity = @(x, y, z) ones (size (x));
%! fx = @(x, y, z) ones(size(x));
%! fy = @(x, y, z) zeros(size(x));
%! fz = @(x, y, z) zeros(size(x));
%! problem_data.f  = @(x, y, z) cat(1, reshape (fx (x,y,z), [1, size(x)]), reshape (fy (x,y,z), [1, size(x)]), reshape (fz (x,y,z), [1, size(x)]));
%! problem_data.h  = @(x, y, z, iside) zeros ([3, size(x)]); %Dirichlet boundary condition
%! problem_data.g  = @(x, y, z, iside) zeros ([3, size(x)]); %Neumann boundary condition
%! method_data.element_name = 'TH';
%! method_data.degree       = [2 2 2]; % Degree of the splines (pressure space)
%! method_data.regularity   = [1 1 1]; % Regularity of the splines
%! method_data.nsub         = [2 2 2]; % Number of subdivisions
%! method_data.nquad        = [4 4 4]; % Points for the Gaussian quadrature rule
%! [geometry, msh, space_v, vel, space_p, press] = solve_stokes (problem_data, method_data);
%! assert (msh.nel, 192)
%! assert (space_p.ndof, 576)
%! assert (space_v.ndof, 8400)

author: rafavzqz

repo: geopdes

save_path: github-repos/MATLAB/rafavzqz-geopdes


text:
%% GENERIC WAYPOINT CLASS (waypoint.m) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This class is designed to define a generic waypoint object, to be placed
% within the simulation. Upon achieving the waypoint, the waypoint object
% will be removed from the simulation.

% Author: James A. Douthwaite 05/06/2017

classdef waypoint < objectDefinition
%%% WAYPOINT BASE CLASS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % This class contains the basic properties of a generic agent, neither
    % aerial or ground based.
    properties
        % Default ownership table
        ownership = struct(...
            'objectID',NaN,...
            'name','all',...
            'priority',0);
        % Associated agent [objectID, name, priority]
    end
    %% ///////////////////////// MAIN METHODS /////////////////////////////
    methods
        % Constructor
        function [this] = waypoint(varargin)
            % This function is to construct the waypoint object using the
            % object defintions held in the 'objectDefinition' base class.
            % We want to allow a waypoint to be called into existance and
            % made valid for any number of agent ID's (objectID's).

            % Call the super class
            this = this@objectDefinition(varargin);

            % Allocate way-point defaults
            this = this.SetGLOBAL('type',OMAS_objectType.waypoint);
            this = this.SetGLOBAL('hitBoxType',OMAS_hitBoxType.spherical);
            this = this.SetGLOBAL('symbol','v');
            this = this.SetGLOBAL('priorState',this.localState);

            % IF SIMPLE CONSTRUCTION.. RETURN NOW
            if length(varargin) < 1
                return
            end

            % DEFAULT CONFIGURATION PARAMETERS
            priority = 0;
            agentSet = [];

            tmp = strncmpi(varargin,'owner',5);
            if any(tmp)
                agentSet = varargin{find(tmp) + 1};
            end
            tmp = strncmpi(varargin,'priority',5);
            if any(tmp)
                priority = varargin{find(tmp) + 1};
            end

            % ALLOCATE ASSOCIATED AGENT PROPERTIES
            if ~isempty(agentSet)
                for allocatedAgent = 1:length(agentSet)
                    [this] = this.CreateAgentAssociation(agentSet{allocatedAgent},priority);
                end
            else
                % NO SPECIFIC AGENTS, ASSIGN PRIORITY TO THE GENERAL CASE
                this.ownership.priority = priority;
            end

            % //////////////// Check for user overrides ///////////////////
            this = this.ApplyUserOverrides(varargin); % Recursive overrides
            % /////////////////////////////////////////////////////////////
        end
    end
    %% /////////////////// WAYPOINT OWNERSHIP FUNCTIONS /////////////////////
    methods
        % CREATE ASSOCIATION BETWEEN AGENT AND WAYPOINT
        function [this] = CreateAgentAssociation(this,agentObject,priority)
            % This method is used to add an association between the
            % waypoint and a given agent object.

            % INPUT HANDLING
            if ~exist('priority','var')
               priority = this.ownership.priority;
            end

            % Create a blank ownership table
            newOwnership = this.CreateOwnershipTable();
            newOwnership.objectID = agentObject.objectID;   % Assign a objectID
            newOwnership.name     = agentObject.name;       % Assign a name
            newOwnership.priority = priority;               % Assign a priority

            % OVERRIDE 'all' CASE
            if isnan(this.ownership(1).objectID)
                % If this is the first allocated object, redefine
                this.ownership(1) = newOwnership;
                this.SetGLOBAL('colour',agentObject.GetGLOBAL('colour'));
                return
            end
            % Check if ID is already present on the table
            ownershipIDs = [this.ownership.objectID];
            IDindex = ownershipIDs(ownershipIDs == agentObject.objectID);
            if ~isempty(IDindex)
                warning('Unable to add agent to waypoint, agent already associated.');
                return
            else
                % Otherwise append the new ownership entry
                this.ownership = vertcat(this.ownership,newOwnership);
            end
        end
        % REMOVE ASSOCIATION BETWEEN AGENT AND WAYPOINT
        function [this] = RemoveAgentAssociation(this,agentObject)
            % This function removes the waypoints association with a
            % specific objectID
            % INPUT HANDLING
            if nargin < 1
                error('Provide either an object ID or class object');
            elseif isnumeric(agentObject)
                agentID = agentObject;
            else
                agentID = agentObject.objectID;
            end

            % GET THE AGENTS ASSOCIATION
            [~,IDindex] = this.GetAgentAssociation(agentID);

            if isempty(IDindex)
                warning('Cannot remove; agent not associated with waypoint.');
                return
            end
            % REMOVE THE AGENT FROM THE WAYPOINT OWNERSHIP
            this.ownership(IDindex) = [];
        end
        % FETCH ASSOCIATION BETWEEN AGENT AND WAYPOINT
        function [isAssociated] = IDAssociationCheck(this,agentID)
            % Simple binary check if is waypoint is associated with the
            % provided object ID number.

            % Input sanity check
            assert(isnumeric(agentID),'Agent ID must be a valid objectID');
            % CHECK THE OWNERSHIP INDEX FOR THIS ID
            isAssociated = logical(any(this.ownership.objectID == agentID));
        end
        % FETCH ASSOCIATION BETWEEN AGENT AND WAYPOINT
        function [ownershipItem,IDindex] = GetAgentAssociation(this,agentObject)
            % This method is used to remove an association between the
            % waypoint and a given agent object.
            % INPUTS:
            % agentObject - Either the agent object or objectID.
            % OUTPUT:
            % this         - The updated waypoint object

            % INPUT HANDLING
            if nargin < 1
                error('Provide either an object ID or class object');
            elseif isnumeric(agentObject)
                agentID = agentObject;
            else
                agentID = agentObject.objectID;
            end
            % CREATE VECTOR OF ASSOCIATED IDs
            ownershipIDs = [this.ownership.objectID];
            % IF ASSOCIATION IS NOT THERE, THROW WARNING
            IDindex = find(ownershipIDs == agentID);
            if isempty(IDindex)
                warning('Agent is not associated with waypoint.');
                ownershipItem = [];
                return
            end
            % RETURN THE ASSOCIATION
            ownershipItem = this.ownership(IDindex);
        end
    end
    %% Private waypoint methods
    methods (Static, Access = private)
        % Create a new ownership table
        function [ownership] = CreateOwnershipTable()
            % Initialise the ownership table
            ownership = struct(...
                'objectID','',...
                'name','',...
                'priority',0);
        end
    end
end %%% STATE VECTOR IS DEFINED AS [x;y;z;v;u;w;psi;the;phi;p;q;r] %%%%%%%%

repo: OpenMAS


text:
function [datafiles] = linsert(filename, handles,datafiles,s,nos)

% tstool/linsert
% status = linsert(filename, handles)
% Einfuegen eines Namens in die Liste, gleichzeitig wird die
% Selektion auf diesen Namen gesetzt

if isempty(s)
  [status,datafiles]=writelevel(filename,datafiles);
  [path,fname,ext] = fileparts(filename);
else
  [status,datafiles]=siglevel(s,datafiles);
  fname=name(s);
end

if ~nos
  datafiles=sortdatafiles(datafiles);
  filllistbox(datafiles,handles,fname);
end

author: benfulcher

repo: hctsa

save_path: github-repos/MATLAB/benfulcher-hctsa


text:
function h_group = im_pix_line(h_parent,x_init,y_init)
%IM_PIX_LINE Create draggable and resizable line pixel by pixel.
% H = IM_PIX_LINE(HPARENT, X, Y) creates a draggable line on
%   the object specified by HPARENT.  The function returns H, a handle to
%   the line, which is an hggroup object.  HPARENT specifies the hggroups's
%   parent, which is typically an axes object, but can also be any other
%   object that can be the parent of an hggroup. X and Y specify the
%   initial end point positions of the line in the form
%   X = [X1 X2], Y =[Y1 Y2].
%
%   A draggable line can be dragged interactively using the mouse.
%
%   The draggable line has a context menu associated with it that allows you to
%   copy the current end point positions to the clipboard in the form
%   [X1 Y1; X2 Y2] and change the color used to display the line.
%
%   API Function Syntaxes
%   ---------------------
%   A draggable line contains a structure of function handles, called
%   an API, that can be used to manipulate it.  To retrieve this
%   structure from the draggable line, use the IPTGETAPI function.
%
%       API = IPTGETAPI(H)
%
%   Functions in the API, listed in the order of the structure fields, include:
%
%   setPosition
%
%       Sets the end point positions of the line.
%
%           api.setPosition(X,Y)
%           api.setPosition([X1 Y1; X2 Y2])
%
%   getPosition
%
%       Returns the end point positions of the line.
%
%           pos = api.getPosition()
%
%       where pos is a 2-by-2 array [X1 Y1; X2 Y2].
%
%   delete
%
%       Deletes the draggable line associated with the API.
%
%           api.delete()
%
%   setColor
%
%       Sets the color used to draw the draggable line.
%
%           api.setColor(new_color)
%
%       where new_color is a three-element vector specifying an RGB
%       value.
%
%   addNewPositionCallback
%
%       Adds the function handle FCN to the list of new-position callback
%       functions.
%
%           id = api.addNewPositionCallback(fcn)
%
%       Whenever the draggable line changes its position, each
%       function in the list is called with the syntax:
%
%           fcn(pos)
%
%       where pos is a 2-by-2 array [X1 Y1; X2 Y2].
%
%       The return value, id, is used only with removeNewPositionCallback.
%
%   removeNewPositionCallback
%
%       Removes the corresponding function from the new-position callback
%       list.
%
%           api.removeNewPositionCallback(id)
%
%       where id is the identifier returned by api.addNewPositionCallback.
%
%   setDragConstraintFcn
%
%       Sets the drag constraint function to be the specified function
%       handle, fcn.
%
%           api.setDragConstraintFcn(fcn)
%
%       Whenever the draggable line is moved or resized because of a mouse drag,
%       the constraint function is called using the syntax:
%
%           constrained_position = fcn(new_position)
%
%       where new_position is a 2-by-2 array [X1 Y1; X2 Y2].
%
%       This allows a client, for example, to control where the line may be
%       moved and how the line may be resized.
%
%   getDragConstraintFcn
%
%       Returns a function handle to the current drag constraint function.
%
%           fcn = api.getDragConstraintFcn()
%
%   Remarks
%   -------
%   If you use IM_PIX_LINE with an axis that contains an image object,
%   and do not specify a drag constraint function, users can drag
%   the point outside the extent of the image and lose the point.
%   When used with an axis created by the PLOT function, the axis
%   limits automatically expand to accommodate the movement of
%   the point.
%
%   Examples
%   --------
%       % Use a custom color for displaying the line.
%       figure, imshow('pout.tif');
%       h = im_pix_line(gca,[10 100], [100 100]);
%       api = iptgetapi(h);
%       api.setColor([0 1 0]);
%       % Now, explore the context menu of the draggable line by right
%       % clicking on the line.
%       % Try to zoom in and out, you will find the line is drawed pixel
%       % by pixel
%
%       % Use addNewPositionCallback API function.
%       figure, imshow('pout.tif');
%       h = im_pix_line(gca,[10 100], [100 100]);
%       api = iptgetapi(h);
%       id = api.addNewPositionCallback(@(pos) title(mat2str(pos,3)));
%       % Now move the mouse, note that the 2-by-2 position vector of the
%       % line is displayed in the title above the image.  Finally, remove
%       % the callback using removeNewPositionCallback
%       api.removeNewPositionCallback(id);
%
%       % Use makeConstrainToRectFcn to prevent dragging out line outside
%       % extent of image.
%       figure, imshow('pout.tif');
%       h = im_pix_line(gca,[10 100], [100 100]);
%       api = iptgetapi(h);
%       % IMPORTANT: use 'imline' here since makeConstrainToRectFcn can
%       % only recognize one of the imline, imrect, impoint !!!
%       fcn = makeConstrainToRectFcn('imline',get(gca,'XLim'),get(gca,'YLim'));
%       api.setDragConstraintFcn(fcn);
%
%   See also IMPOINT, IMRECT, IPTGETAPI, makeConstrainToRectFcn.

%   Copyright 2004-2005 The MathWorks, Inc.
%   $Revision: 1.1.6.3 $  $Date: 2005/12/12 23:22:09 $
%
%   adopted by gauss.1982@gmali.com
%   15:52 2006-12-15 $
%

iptchecknargin(3, 3, nargin, mfilename);
if ~ishandle(h_parent)
    error('Images:im_pix_line:invalidHandle', ...
        'HPARENT must be a valid graphics handle.');
end
if strcmp(get(h_parent, 'type'), 'axes')
    h_axes = h_parent;
else
    h_axes = ancestor(h_parent, 'axes');
    if isempty(h_axes)
        error('Images:im_pix_line:noAxesAncestor', ...
            'HPARENT must be a descendent of an axes object.');
    end
end

try
    h_group = hggroup('ButtonDownFcn', @startDrag, 'Parent', h_parent);
catch
    error('Images:im_pix_line:failureToParent', ...
        'HPARENT must be able to have an hggroup object as a child.');
end

%Returns API used to draw line graphic.
draw_api = pixLineSymbol(h_group);

% Initialize position variable for managing end point positions of line.
% This position variable is created to allow for abstraction of drag
% behavior in future.  Position is in the form [X1 Y1; X2 Y2]
position = [reshape(x_init,2,1),reshape(y_init,2,1)];

% constraint_function is used by dragMotion() to give a client the
% opportunity to constraint where the draggable line can be
% dragged.
drag_constraint_function  = identityFcn;

% new_position_callback_functions is used by sendNewPosition() to
% notify interested clients whenever the rectangle position changes.
new_position_callback_functions = makeList;

% Pattern for set associated with callbacks that get called as a
% result of the set.
insideSetPosition = false;

% Size of SelectionHighlight markers on end of line is 5 pixels.  This
% constant is used throughout im_pix_line
marker_end_size = 5;

h_fig = iptancestor(h_axes, 'figure');
cmenu = uicontextmenu('Parent', h_fig);

%In order for IMDISTLINE to be draggable in IMTOOL, the HitTest property
%of the line objects created by LineSymbol() must be set to 'on'.
%this requires that the context menu be associated with the line objects
%rather than the h_group.
set(findobj(h_group,'Type','line'), 'UIContextMenu', cmenu);

uimenu(cmenu, ...
    'Label', 'Copy Position', ...
    'Callback', @copyPosition');

set_color_menu = uimenu(cmenu, ...
    'Label', 'Set Line Color');
color_choices = getColorChoices;

for k = 1:numel(color_choices)
    uimenu(set_color_menu, 'Label', color_choices(k).Label, ...
        'Callback', @(varargin) setColor(color_choices(k).Color));
end
setColor(color_choices(1).Color);

api.setPosition                 = @setPosition;
api.getPosition                 = @getPosition;
api.delete                      = @deleteLine;
api.setColor                    = @setColor;
api.addNewPositionCallback      = @addNewPositionCallback;
api.removeNewPositionCallback   = @removeNewPositionCallback;
api.getDragConstraintFcn        = @getDragConstraintFcn;
api.setDragConstraintFcn        = @setDragConstraintFcn;

setappdata(h_group, 'API', api);

updateView(position);

% Create update function that knows how to get the position it needs when it
% will be called from HG contexts where it may not have access to the position
% otherwise.
update_fcn = @(varargin) updateView(api.getPosition());

% Install pointer manager in figure.
iptPointerManager(h_fig);

% Store pointer behavior in the hggroup object and all its children.
enterFcn = @(f,cp) set(f, 'Pointer', 'fleur');
iptSetPointerBehavior(findobj(h_group), enterFcn);

updateAncestorListeners(h_group,update_fcn);

    %----------------------------
    function setPosition(varargin)

        % Validate inputs before caling break recursion pattern.
        iptchecknargin(1, 2, nargin, sprintf('%s/setPosition',mfilename));

        % Pattern to break recursion
        if insideSetPosition
            return
        else
            insideSetPosition = true;
        end

        switch nargin
            case 1
                position = varargin{1};
            case 2
                %Ensure that position vector always remains
                %in the form [X1 Y1; X2 Y2] independent of whether data is
                %entered as row or column vectors
                position = [reshape(varargin{1},2,1),...
                    reshape(varargin{2},2,1)];
        end

        updateView(position);
        sendNewPosition;

        % Pattern to break recursion
        insideSetPosition = false;
    end

    %-------------------------
    function pos = getPosition
        pos = position;
    end

    %---------------------------------------
    function id = addNewPositionCallback(fun)
        id = new_position_callback_functions.appendItem(fun);
    end

    %------------------------------------
    function removeNewPositionCallback(id)
        new_position_callback_functions.removeItem(id);
    end

    %--------------------------------
    function setDragConstraintFcn(fun)
        drag_constraint_function = fun;
    end

    %---------------------------------
    function fh = getDragConstraintFcn
        fh = drag_constraint_function;
    end

    %--------------------------------
    function deleteLine(src, varargin) %#ok varargin needed by HG caller
        if ishandle(h_group)
            delete(h_group);
        end
    end

    %---------------------------
    function updateView(position)
        draw_api.updateView(position);
    end

    %----------------------
    function setColor(color)
        draw_api.setColor(color)
    end

    %------------------------------
    function copyPosition(varargin) %#ok varargin needed by HG caller

        clipboard('copy', position);

    end

    %--------------------------------
    function sendNewPosition(varargin) %#ok varargin needed by HG caller

        list = new_position_callback_functions.getList();
        for k = 1:numel(list)
            fun = list{k};
            fun(position);
        end

    end

    %-------------------------------
    function startDrag(varargin) %#ok varargin needed by HG caller

        % Calculate scale of current axes.  CurrentPoint property of axes
        % is reported in axes units.  Convert marker size to axes units to
        % determine whether an end point has been selected.

        [dx_per_pixel,dy_per_pixel]=getAxesScale(h_axes);

        if strcmp(get(h_fig, 'SelectionType'), 'normal')
            % Get the mouse location in data space.
            [start_click_x,start_click_y] = getCurrentPoint(h_axes);

            % Disable figure's pointer manager.
            iptPointerManager(h_fig, 'disable');

            initial_pos_x = position(:,1);
            initial_pos_y = position(:,2);
            start_position = position;

            end_point_index = ...
                abs(initial_pos_x-start_click_x)< marker_end_size*dx_per_pixel...
                & abs(initial_pos_y-start_click_y) < marker_end_size*dy_per_pixel;

            if ( any(end_point_index) )
                %move end point
                drag_motion_callback_id = iptaddcallback(h_fig, ...
                    'WindowButtonMotionFcn', ...
                    @endPointMotion);

                drag_up_callback_id = iptaddcallback(h_fig, ...
                    'WindowButtonUpFcn', ...
                    @stopEndPointMotion);
            else
                %translate entire line
                drag_motion_callback_id = iptaddcallback(h_fig, ...
                    'WindowButtonMotionFcn', ...
                    @dragMotion);

                drag_up_callback_id = iptaddcallback(h_fig, ...
                    'WindowButtonUpFcn', ...
                    @stopDrag);
            end

        end

        %---------------------------
        function dragMotion(varargin) %#ok varargin needed by HG caller

            if ~ishandle(h_axes)
                return;
            end

            [new_x new_y] = getCurrentPoint(h_axes);
            delta_x = new_x - start_click_x;
            delta_y = new_y - start_click_y;

            candidate_position = start_position + ...
                [repmat(delta_x,2,1) repmat(delta_y,2,1)];

            new_position = drag_constraint_function(candidate_position);

            setPosition(new_position);

        end % end dragMotion

        %-------------------------
        function stopDrag(varargin) %#ok varargin needed by HG caller
            dragMotion();

            iptremovecallback(h_fig, 'WindowButtonMotionFcn', ...
                drag_motion_callback_id);
            iptremovecallback(h_fig, 'WindowButtonUpFcn', ...
                drag_up_callback_id);

            % Enable figure's pointer manager.
            iptPointerManager(h_fig, 'enable');

        end % end stopDrag

        %-------------------------------
        function endPointMotion(varargin) %#ok varargin needed by HG caller

            ax = ancestor(h_group, 'axes');
            if ~ishandle(ax)
                return;
            end

            [new_x new_y] = getCurrentPoint(h_axes);
            delta_x = new_x - start_click_x;
            delta_y = new_y - start_click_y;

            if (all(end_point_index))
                %if end points overlap, arbitrarily choose one of the end
                %points to drag
                end_point_index = logical([1 0]);
            end

            fixed_point = start_position(~end_point_index,:);
            moving_point = start_position(end_point_index,:);

            candidate_position(end_point_index,:) =...
                moving_point + [delta_x delta_y];

            candidate_position(~end_point_index,:) = fixed_point;

            new_position=drag_constraint_function(candidate_position);
            setPosition(new_position);

        end % end endPointMotion

        %-----------------------------------
        function stopEndPointMotion(varargin) %#ok varargin needed by HG caller
            endPointMotion();

            iptremovecallback(h_fig, 'WindowButtonMotionFcn', ...
                drag_motion_callback_id);
            iptremovecallback(h_fig, 'WindowButtonUpFcn', ...
                drag_up_callback_id);

            % Enable figure's pointer manager.
            iptPointerManager(h_fig, 'enable');

        end % end stopEndPointMotion

    end % end startDrag

end %end im_pix_line


text:
function [K] = kv0v0(x, xp, hyp, ubar, vbar, ubarp, vbarp, dt, i)

logsigmau = hyp(1);
logthetau = hyp(2);
logsigmav = hyp(3);
logthetav = hyp(4);

a1 = hyp(5);
a2 = hyp(6);

n_x = size(x,1);
n_xp = size(xp,1);

x = repmat(x,1,n_xp);
xp = repmat(xp',n_x,1);

ubar = repmat(ubar,1,n_xp);
vbar = repmat(vbar,1,n_xp);
ubarp = repmat(ubarp',n_x,1);
vbarp = repmat(vbarp',n_x,1);

switch i

case 0

K=exp(1).^(logsigmav+(-1/2).*exp(1).^((-1).*logthetav).*(x+(-1).*xp).^2)+ ...
  dt.^2.*exp(1).^(logsigmau+(-4).*logthetau+(-1/2).*exp(1).^((-1).* ...
  logthetau).*(x+(-1).*xp).^2).*(a2.*exp(1).^(2.*logthetau).*(ubar.^2+ ...
  vbar.^2).*(a2.*exp(1).^(2.*logthetau).*(ubarp.^2+vbarp.^2)+a1.*((-1).* ...
  exp(1).^logthetau+(x+(-1).*xp).^2))+(-1).*a1.*(a2.*exp(1).^(2.* ...
  logthetau).*(ubarp.^2+vbarp.^2).*(exp(1).^logthetau+(-1).*(x+(-1).*xp) ...
  .^2)+(-1).*a1.*(3.*exp(1).^(2.*logthetau)+(-6).*exp(1).^logthetau.*(x+( ...
  -1).*xp).^2+(x+(-1).*xp).^4)));

case 1 % logsigmau

K=dt.^2.*exp(1).^(logsigmau+(-4).*logthetau+(-1/2).*exp(1).^((-1).* ...
  logthetau).*(x+(-1).*xp).^2).*(a2.*exp(1).^(2.*logthetau).*(ubar.^2+ ...
  vbar.^2).*(a2.*exp(1).^(2.*logthetau).*(ubarp.^2+vbarp.^2)+a1.*((-1).* ...
  exp(1).^logthetau+(x+(-1).*xp).^2))+(-1).*a1.*(a2.*exp(1).^(2.* ...
  logthetau).*(ubarp.^2+vbarp.^2).*(exp(1).^logthetau+(-1).*(x+(-1).*xp) ...
  .^2)+(-1).*a1.*(3.*exp(1).^(2.*logthetau)+(-6).*exp(1).^logthetau.*(x+( ...
  -1).*xp).^2+(x+(-1).*xp).^4)));

case 2 % logthetau

K=dt.^2.*exp(1).^(logsigmau+(-4).*logthetau+(-1/2).*exp(1).^((-1).* ...
  logthetau).*(x+(-1).*xp).^2).*(a2.*exp(1).^(3.*logthetau).*(ubar.^2+ ...
  vbar.^2).*((-1).*a1+2.*a2.*exp(1).^logthetau.*(ubarp.^2+vbarp.^2))+(-1) ...
  .*a1.*exp(1).^logthetau.*(a2.*exp(1).^logthetau.*(ubarp.^2+vbarp.^2).*( ...
  3.*exp(1).^logthetau+(-2).*(x+(-1).*xp).^2)+(-6).*a1.*(exp(1) ...
  .^logthetau+(-1).*(x+(-1).*xp).^2))+2.*a2.*exp(1).^(2.*logthetau).*( ...
  ubar.^2+vbar.^2).*(a2.*exp(1).^(2.*logthetau).*(ubarp.^2+vbarp.^2)+a1.*( ...
  (-1).*exp(1).^logthetau+(x+(-1).*xp).^2))+(a2.*exp(1).^(2.*logthetau).*( ...
  ubar.^2+vbar.^2).*(a2.*exp(1).^(2.*logthetau).*(ubarp.^2+vbarp.^2)+a1.*( ...
  (-1).*exp(1).^logthetau+(x+(-1).*xp).^2))+(-1).*a1.*(a2.*exp(1).^(2.* ...
  logthetau).*(ubarp.^2+vbarp.^2).*(exp(1).^logthetau+(-1).*(x+(-1).*xp) ...
  .^2)+(-1).*a1.*(3.*exp(1).^(2.*logthetau)+(-6).*exp(1).^logthetau.*(x+( ...
  -1).*xp).^2+(x+(-1).*xp).^4))).*((-4)+(1/2).*exp(1).^((-1).*logthetau).* ...
  (x+(-1).*xp).^2));

case 3 % logsigmav

K=exp(1).^(logsigmav+(-1/2).*exp(1).^((-1).*logthetav).*(x+(-1).*xp).^2); ...

case 4 % logthetav

K=(1/2).*exp(1).^(logsigmav+(-1).*logthetav+(-1/2).*exp(1).^((-1).* ...
  logthetav).*(x+(-1).*xp).^2).*(x+(-1).*xp).^2;

case 5 % a1

K=dt.^2.*exp(1).^(logsigmau+(-4).*logthetau+(-1/2).*exp(1).^((-1).* ...
  logthetau).*(x+(-1).*xp).^2).*((-1).*a2.*exp(1).^(2.*logthetau).*( ...
  ubarp.^2+vbarp.^2).*(exp(1).^logthetau+(-1).*(x+(-1).*xp).^2)+a2.*exp(1) ...
  .^(2.*logthetau).*(ubar.^2+vbar.^2).*((-1).*exp(1).^logthetau+(x+(-1).* ...
  xp).^2)+(-1).*a1.*((-3).*exp(1).^(2.*logthetau)+6.*exp(1).^logthetau.*( ...
  x+(-1).*xp).^2+(-1).*(x+(-1).*xp).^4)+a1.*(3.*exp(1).^(2.*logthetau)+( ...
  -6).*exp(1).^logthetau.*(x+(-1).*xp).^2+(x+(-1).*xp).^4));

case 6 % a2

K=dt.^2.*exp(1).^(logsigmau+(-2).*logthetau+(-1/2).*exp(1).^((-1).* ...
  logthetau).*(x+(-1).*xp).^2).*(a2.*exp(1).^(2.*logthetau).*(ubar.^2+ ...
  vbar.^2).*(ubarp.^2+vbarp.^2)+(ubar.^2+vbar.^2).*(a2.*exp(1).^(2.* ...
  logthetau).*(ubarp.^2+vbarp.^2)+a1.*((-1).*exp(1).^logthetau+(x+(-1).* ...
  xp).^2))+(-1).*a1.*(ubarp.^2+vbarp.^2).*(exp(1).^logthetau+(-1).*(x+(-1) ...
  .*xp).^2));

otherwise

        K = zeros(n_x, n_xp);
end

if K == 0

    K = zeros(n_x, n_xp);

end

end

author: maziarraissi

repo: HPM

save_path: github-repos/MATLAB/maziarraissi-HPM


text:
% This code was originally written and distributed as part of the
% PASCAL VOC challenge, with minor modifications for ILSVRC2013
function rec = VOCreadrecxml(path,hash)

x=VOCreadxml(path);
x=x.annotation;

rec.folder=x.folder;
rec.filename=x.filename;
rec.source.database=x.source.database;
%% rec.source.annotation=x.source.annotation;
%% rec.source.image=x.source.image;

rec.size.width=str2double(x.size.width);
rec.size.height=str2double(x.size.height);

rec.imgname=[x.folder x.filename];
rec.imgsize=str2double({x.size.width x.size.height});
rec.database=rec.source.database;

if isfield(x,'object')
    for i=1:length(x.object)
        rec.objects(i)=xmlobjtopas(x.object(i),hash);
    end
else
    rec.objects = [];
end

function p = xmlobjtopas(o,hash)

p.class=o.name;

p.label= get_class2node( hash, p.class );

p.bbox=str2double({o.bndbox.xmin o.bndbox.ymin o.bndbox.xmax o.bndbox.ymax});

p.bndbox.xmin=str2double(o.bndbox.xmin);
p.bndbox.ymin=str2double(o.bndbox.ymin);
p.bndbox.xmax=str2double(o.bndbox.xmax);
p.bndbox.ymax=str2double(o.bndbox.ymax);

author: zhoubolei

repo: CAM

save_path: github-repos/MATLAB/zhoubolei-CAM