text:
% A single JIDE property field in a JIDE property grid.
% This is an internal class and is not intended to be used directly.
%
% References:
% http://www.jidesoft.com/products/JIDE_Grids_Developer_Guide.pdf
%
% See also: PropertyGrid

% Copyright 2010 Levente Hunyadi
classdef JidePropertyGridField < handle
    properties
        % A PropertyGridField instance.
        PropertyData;
    end
    properties (Dependent)
        Value;
    end
    properties (Access = private)
        % Children the property field might have.
        Children = JidePropertyGridField.empty(0,1);
        % A JIDE DefaultProperty instance.
        Control;
        % JIDE editor context (if any).
        Context;
        % JIDE editor context type (if any).
        ContextType;
    end
    methods
        function self = JidePropertyGridField(data)
            if nargin > 0
                self.Initialize(data);
            end
        end

        function self = Initialize(self, data)
        % Initializes a JIDE property based on a property grid field.
        % May register editor contexts with the global CellEditorManager.
            validateattributes(self, {'JidePropertyGridField'}, {'scalar'});

            self.PropertyData = data;
            field = com.jidesoft.grid.DefaultProperty();
            field.setName(data.Name);  % JIDE automatically uses a hierarchical naming scheme
            field.setCategory(data.Category);
            field.setDisplayName(data.DisplayName);
            field.setDescription(data.Description);
            field.setEditable(~data.ReadOnly);
            switch data.Type.Shape
                case 'scalar'
                    switch data.Type.PrimitiveType
                        case {'denserealdouble','sparserealdouble'}  % add a double-precision floating point property
                            matlabtype = 'double';  % MatLab type that is marshalled to Java
                        case {'denserealsingle','sparserealsingle'}  % add a single-precision floating point property
                            matlabtype = 'single';
                        case {'int8','uint8','int16'}
                            matlabtype = 'int16';
                        case {'uint16','int32'}  % add an integer property
                            matlabtype = 'int32';
                        case {'uint32','int64'}
                            matlabtype = 'int64';
                        case 'logical'  % add a logical property
                            matlabtype = 'logical';
                            field.setEditorContext(com.jidesoft.grid.BooleanCheckBoxCellEditor.CONTEXT);
                        case {'densecomplexdouble','sparsecomplexdouble','densecomplexsingle','sparsecomplexsingle'}
                            matlabtype = [];
                            field.setType(javaclass('char',1));  % edit as string and convert with eval
                        otherwise
                            matlabtype = [];
                            field.setEditable(false);
                            %error('PropertyGrid:ArgumentTypeMismatch', 'Scalar %s is not supported.', data.Type.PrimitiveType);
                    end
                    if ~isempty(matlabtype)
                        javatype = javaclass(matlabtype);
                        field.setType(javatype);
                        if ~isempty(data.Type.Domain)
                            if iscell(data.Type.Domain)  % explicit enumeration of domain elements
                                self.AddComboBoxEditor(field, javatype, data.Type.Domain);
                            elseif isnumeric(data.Type.Domain) && isinteger(data.Type)  % domain expressed as interval
                                self.AddSpinnerEditor(field, javatype, min(data.Type.Domain), max(data.Type.Domain));
                            end
                        end
                    end
                case {'row','column'}
                    InitializeVector(self, field);
                case 'matrix'
                    InitializeMatrix(self, field);
                case 'empty'
                    field.setEditable(false);
                otherwise
                    error('PropertyGrid:ArgumentTypeMismatch', 'Data shape %s is not supported.', data.Type.Shape);
            end
            self.Control = field;
            self.Value = data.Value;

            for k = 1 : numel(data.Children)
                self.Children(k) = JidePropertyGridField(data.Children(k));
                self.Control.addChild(self.Children(k).Control);
            end
        end

        function delete(self)
        % Deallocates registered editor contexts.
            if ~isempty(self.Context)
                com.jidesoft.grid.CellEditorManager.unregisterEditor(self.ContextType, self.Context);
            end
        end

        function value = get.Value(self)
        % Gets the native MatLab value of a property.
            javavalue = self.Control.getValue();
            [value,stringconversion] = self.PropertyData.Type.ConvertFromJava(javavalue);
            if stringconversion  % display pretty-formatted value
                javavalue = self.PropertyData.Type.ConvertToJava(value);
                self.Control.setValue(javavalue);
            end
        end

        function set.Value(self, value)
        % Sets the Java value of a property based on the native value.
            javavalue = self.PropertyData.Type.ConvertToJava(value);
            self.Control.setValue(javavalue);
        end

        function tf = CanAccept(self, value)
        % Tests if the property can be assigned the native value.
        %
        % Input arguments:
        % value:
        %    a native MatLab value
            validateattributes(self, {'JidePropertyGridField'}, {'scalar'});
            tf = self.PropertyData.Type.CanAccept(value);
        end

        function self = FindByName(selfarray, name)
        % Finds the property field with the given name in an array.
            self = selfarray.FindByNameRecurse(strsplit(name, '.'));
        end

        function properties = GetProperties(selfarray)
            properties = PropertyGridField.empty(0,1);
            for k = 1 : numel(selfarray)
                properties(k) = selfarray(k).PropertyData;
            end
        end

        function list = GetTableModel(selfarray)
            n = numel(selfarray);
            ctrls = cell(1,n);
            for k = 1 : n
                ctrls{k} = selfarray(k).Control;
            end
            list = javaArrayList(ctrls);
        end
    end
    methods (Access = private)
        function self = FindByNameRecurse(selfarray, nameparts)
            names = getclassfield(getclassfield(selfarray, 'PropertyData'), 'Name');
            ix = strmatch(nameparts{1}, names, 'exact');
            if isempty(ix)
                self = JidePropertyGridField.empty(0,1);
                return;
            end
            ix = ix(1);
            namerest = nameparts(2:end);
            if isempty(namerest)
                self = selfarray(ix);
            else
                self = selfarray(ix).Children.FindByNameRecurse(namerest);
            end
        end

        function InitializeVector(self, field)
            data = self.PropertyData;
            switch data.Type.PrimitiveType
                case 'char'  % add a string property
                    switch data.Type.Shape
                        case 'row'
                            field.setType(javaclass('char',1));
                            if ~isempty(data.Type.Domain)
                                self.AddComboBoxEditor(field, javaclass('char',1), javaStringArray(data.Type.Domain));
                            end
                        otherwise
                            field.setType(javaclass('char',1));  % edit as string and convert with eval
                    end
                case 'cellstr'
                    field.setType(javaclass('char',1));
                    field.setEditorContext(com.jidesoft.grid.MultilineStringCellEditor.CONTEXT);
                case 'logical'
                    if ~isempty(data.Type.Domain)
                        field.setType(javaclass('cellstr',1));  % java.lang.String array
                        self.AddCheckBoxListEditor(field, data.Type.Domain);
                    else
                        field.setType(javaclass('char',1));  % edit as string and convert with eval
                    end
                case {...
                        'denserealdouble','sparserealdouble','denserealsingle','sparserealsingle',...
                        'densecomplexdouble','sparsecomplexdouble','densecomplexsingle','sparsecomplexsingle',...
                        'int8','uint8','int16','uint16','int32','uint32','int64','uint64'}
                    field.setType(javaclass('char',1));  % edit as string and convert with eval
                otherwise
                    field.setEditable(false);
                    %error('PropertyGrid:ArgumentTypeMismatch', 'Unsupported type: %s %s.', data.Type.Shape, data.Type.PrimitiveType);
            end
        end

        function InitializeMatrix(self, field)
            data = self.PropertyData;
            switch data.Type.PrimitiveType
                case {...
                        'denserealdouble','sparserealdouble','denserealsingle','sparserealsingle',...
                        'densecomplexdouble','sparsecomplexdouble','densecomplexsingle','sparsecomplexsingle',...
                        'char','int8','uint8','int16','uint16','int32','uint32','int64','uint64','logical'}
                    field.setType(javaclass('char',1));  % edit as string and convert with eval
                otherwise
                    field.setEditable(false);
                    %error('PropertyGrid:ArgumentTypeMismatch', 'Matrix %s is not supported.', data.Type.PrimitiveType);
            end
        end

        function ApplyContext(self, field, javatype, editor, editortype)
        % Registers a context for an editor.
        %
        % Input arguments:
        % field:
        %    a com.jidesoft.grid.Property instance
        % javatype:
        %    the Java type to be associated with the context
        % editor:
        %    a cell editor instance
        % editortype:
        %    the key used for generating the name of the context
            self.Context = com.jidesoft.grid.EditorContext(['JIDE_' editortype '_' int2str(self.GetContextCounterValue())]);
            self.ContextType = javatype;
            com.jidesoft.grid.CellEditorManager.registerEditor(javatype, editor, self.Context);  % register new context
            field.setEditorContext(self.Context);  % apply context to property
        end

        function AddCheckBoxListEditor(self, field, labels)
        % Registers a new check box list context.
        %
        % Input arguments:
        % field:
        %    a com.jidesoft.grid.Property instance
        % labels:
        %    a cell array of strings to label elements in the set shown
            editor = com.jidesoft.grid.CheckBoxListComboBoxCellEditor(javaStringArray(labels), javaclass('cellstr',1));
            self.ApplyContext(field, javaclass('cellstr',1), editor, 'checkboxlist');
        end

        function AddComboBoxEditor(self, field, javatype, javadomain)
        % Registers a new list selection context.
        % A drop-down combo box allows the user to select a single value
        % from a predefined set of values.
        %
        % Input arguments:
        % field:
        %    a com.jidesoft.grid.Property instance
        % javatype:
        %    a java.lang.Class instance
        % javadomain:
        %    an array of Java objects whose type corresponds to javatype
            editor = com.jidesoft.grid.ListComboBoxCellEditor(javadomain);
            self.ApplyContext(field, javatype, editor, 'combobox');
        end

        function AddSliderEditor(self, field, javatype, lower, upper)
        % Registers a new slider context.
        % The slider has a limited range.
        %
        % field:
        %    a com.jidesoft.grid.Property instance
        % javatype:
        %    a java.lang.Class instance
        % lower:
        %    an integer representing the upper lower of the interval
        % upper:
        %    an integer representing the upper bound of the interval
            editor = com.jidesoft.grid.SliderCellEditor(int32(lower), int32(upper));
            self.ApplyContext(field, javatype, editor, 'slider');
        end

        function AddSpinnerEditor(self, field, javatype, lower, upper)
        % Registers a new spinner context.
        % The spinner has a limited range and a fixed step.
        %
        % field:
        %    a com.jidesoft.grid.Property instance
        % javatype:
        %    a java.lang.Class instance
        % lower:
        %    an integer representing the upper lower of the interval
        % upper:
        %    an integer representing the upper bound of the interval
            spinner = javax.swing.SpinnerNumberModel(int32(lower), int32(lower), int32(upper), int32(1));
            editor = com.jidesoft.grid.SpinnerCellEditor(spinner);
            self.ApplyContext(field, javatype, editor, 'spinner');
        end
    end
    methods (Static, Access = private)
        function counter = GetContextCounterValue()
        % The current counter value for the JIDE editor context.
            persistent jide_counter;
            if isempty(jide_counter)  % if not yet assigned
                jide_counter = 0;
            end
            jide_counter = jide_counter + 1;  % increment global field counter
            counter = jide_counter;           % return current value
        end
    end
end

author: CovertLab

repo: WholeCell

save_path: github-repos/MATLAB/CovertLab-WholeCell


text:
%  Testing the function  y=Kalman1D(x,q)
%  Note : many test were done for  better performance by choosing
%  the values R and Q in the function Kalman1D(X) to be respectively
%  : Q=1e-2, and R=0.05.
%  For other functions, tery choosing optimal Q and R values .
%  july 2012
%  KHMOU Youssef

fprintf('>>Simulating 1D Kalman Filter: \n\n');
%Global parameters
t=0:pi/100:200;
F=200.00;
n=length(t);

% First test
fprintf('>>1st Signal : f(t)=4*sin(t/10)*exp(-t/200)\n');
x1=(4*sin(t./10)).*exp(-inv(F).*t);
W1=randn(size(x1));
X1=(x1+W1);
Q1=1e-4;
fprintf('>>AWGN1 parameters : m1=%3.f\tv1=%.3f\n',mean(W1),var(W1));
[Y1,K1,P1]=Kalman1D(X1,Q1);
% Statistical parametrs for the first signal
Max_x1= max(x1);
Max_y1= max(Y1);
MSE1 = 0.00 ;
for i=1:n
    MSE1=MSE1+((x1(i)-Y1(i))^2);
end
MSE1=MSE1/n;
PSNR1=20*log10(max(Max_x1,Max_y1)/(MSE1^2));
fprintf('>>Mean Square Error1 mse1=%3.f\n',MSE1);
fprintf('>>Peak Signal to Noise Ratio1 psnr1=%.3f\tdB\n\n',PSNR1);
f1=figure(1);set(f1,'Name','Testing 1: f(t)=4*sin(t/10)*exp(-t/200)+W, W~N(m,v)');
subplot(2,3,1), plot(t,x1,'MarkerSize',1.2), title(' original signal '), grid on ,
subplot(2,3,2), plot(t,X1,'g'), title(' noisy signal  (awgn)'), grid on,
subplot(2,3,3), plot(t,Y1,'r'), title(' Filtered signal,R=1e-2,Q=1e-5'), grid on,
subplot(2,3,4), plot(t,x1,'b--','MarkerSize',2), hold on, plot(t,X1,'g+','MarkerSize',1.2), plot(t,Y1,'r--'),...
    title(' Superposition'), legend(' original','noisy','filtered'), grid on,
subplot(2,3,5), plot(K1(1:100)), title(strcat(' Kalman Gain',' convergence=',num2str(K1(100)))), grid on,xlabel(' iterations')
subplot(2,3,6), plot(P1(1:100)), title(strcat(' variance error',' convergence=',num2str(min(P1)))), grid on,xlabel('iterations')

% Second test
fprintf('>>2nd  Signal : g(t)=0.5*square(pi*t/20);\n');
x2=0.5*square(pi*t/20);
W2=randn(size(x2))/10;
X2=(x2+W2);
Q2=1e-4;
fprintf('>>AWGN2 parameters : m2=%.3f\tv2=%.3f\n',mean(W2),var(W2));
[Y2,K2,P2]=Kalman1D(X2,Q2);
% Statistical parameters for the second signal
Max_x2= max(x2);
Max_y2= max(Y2);
MSE2 = 0.00 ;
for i=1:n
    MSE2=MSE2+((x2(i)-Y2(i))^2);
end
MSE2=MSE2/n;
PSNR2=20*log10(max(Max_x2,Max_y2)/(MSE2^2));
fprintf('>>Mean Square Error2 mse2=%3.f\n',MSE2);
fprintf('>>Peak Signal to Noise Ratio2 psnr2=%.3f\tdB\n',PSNR2);
f2=figure(2);set(f2,'Name','Testing 2: g(t)=1/2 *square(pi*t/20)+W, W~N(m,v)');
subplot(2,3,1), plot(t,x2,'MarkerSize',1.2), title(' original signal, Square(pulsetr) '), grid on ,axis([0 200 -1 1])
subplot(2,3,2), plot(t,X2,'g'),axis([0 200 -1 1]), title(' noisy signal  (awgn)'), grid on,
subplot(2,3,3), plot(t,Y2,'r'), title(' Filtered signal,R=1e-2,Q=1e-5'), grid on,
subplot(2,3,4), plot(t,x2,'b--','MarkerSize',2), hold on, plot(t,X2,'g+','MarkerSize',1.2), plot(t,Y2,'r--'),...
    title(' Superposition'), legend(' original','noisy','filtered'), grid on,
subplot(2,3,5), plot(K2(1:100)), title(strcat(' Kalman Gain',' convergence=',num2str(K2(100)))), grid on,xlabel(' iterations')
subplot(2,3,6), plot(P2(1:100)), title(strcat(' variance error',' convergence=',num2str(min(P2)))), grid on,xlabel('iterations')

author: Sable

repo: mcbench-benchmarks


text:
function [u v] = opticalFlow_Classic_NL(frame1, frame2)

%tic
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
uv = estimate_flow_interface(frame1, frame2, 'classic+nl-fast');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%toc

u = uv(:,:,1);
v = uv(:,:,2);

author: thomas-koehler

repo: SupER


text:
function title = p11_title ( )

%*****************************************************************************80
%
%% P11_TITLE returns the title of problem P11.
%
%  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 11, Enright and Pryce #C1';

  return
end

author: johannesgerer

repo: jburkardt-m


text:
% STD_READERSP - load ERSP measures for data channels or  for all
%                  components of a specified cluster. This function is
%                  also being used to read ITC and ERPimage data.
% Usage:
%   >> [STUDY, erspdata, times, freqs, erspbase] = ...
%                   std_readersp(STUDY, ALLEEG, varargin);
% Inputs:
%       STUDY - studyset structure containing some or all files in ALLEEG
%      ALLEEG - vector of loaded EEG datasets
%
% Optional inputs:
%  'design'    - [integer] read files from a specific STUDY design. Default
%                is empty (use current design in STUDY.currentdesign).
%  'channels'  - [cell] list of channels to import {default: none}
%  'clusters'  - [integer] list of clusters to import {[]|default: all but
%                the parent cluster (1) and any 'NotClust' clusters}
%  'singletrials' - ['on'|'off'] load single trials spectral data (if
%                available). Default is 'off'.
%  'forceread' - ['on'|'off'] Force rereading data from disk.
%                Default is 'off'.
%  'subject'   - [string] select a specific subject {default:all}
%  'component' - [integer] select a specific component in a cluster.
%                This is the index of the component in the cluster not the
%                component number {default:all}
%  'datatype'  - {'ersp'|'itc'|'erpim'} This function is used to read all
%                2-D STUDY matrices stored on disk (not only ERSP). It may
%                read ERSP ('ersp' option), ITC ('itc' option) or ERPimage
%                data ('erpim' option).
%
% ERSP specific options:
%  'timerange' - [min max] time range {default: whole measure range}
%  'freqrange' - [min max] frequency range {default: whole measure range}
%  'subbaseline' - ['on'|'off'] subtract the ERSP baseline for paired
%                conditions. The conditions for which baseline is removed
%                are indicated on the command line. See help
%                std_studydesign for more information about paired and
%                unpaired variables.
%
% ERPimage specific option:
%   This function is used to read all 2-D STUDY matrices stored on disk
%   (this includes ERPimages). It therefore takes as input specific
%   ERPimage options. Note that the 'singletrials' optional input is
%   irrelevant for ERPimages (which are always stored as single trials).
%   'concatenate' - ['on'|'off'] read concatenated ERPimage data ('on') or
%                   stacked ERPimage data. See help std_erpimage for more
%                   information.
%   'timerange'   - [min max] time range {default: whole measure range}
%   'trialrange'  - [min max] read only a specific range of the ERPimage
%                   output trials {default: whole measure range}
% Output:
%  STUDY    - updated studyset structure
%  erspdata - [cell array] ERSP data (the cell array size is
%             condition x groups). This may also be ITC data or ERPimage
%             data (see above).
%  times    - [float array] array of time points
%  freqs    - [float array] array of frequencies. For ERPimage this
%             contains trial indices.
%  erspbase - [cell array] baseline values
%  events   - [cell array] events (ERPimage only).
%
% Author: Arnaud Delorme, CERCO, 2006-

% Copyright (C) Arnaud Delorme, arno@salk.edu
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

function [STUDY, erspdata, alltimes, allfreqs, erspbase, events, unitPower] = std_readersp(STUDY, ALLEEG, varargin)

if nargin < 2
    help std_readersp;
    return;
end
events = {};
unitPower = 'dB';
erspbase = [];

disp('This function is obsolete and only partially backward compatible use std_readdata instead');
[STUDY, erspdata, alltimes, allfreqs, events] = std_readdata(STUDY, ALLEEG, 'datatype', 'ersp', varargin{:});

author: sccn

repo: eeglab

save_path: github-repos/MATLAB/sccn-eeglab


text:
function [LU_or_x,info,c] = klu (A,operation,b,opts)                        %#ok
%KLU sparse left-looking LU factorization, using a block triangular form.
%
%   Example:
%   LU = klu (A)            factorizes R\A(p,q) into L*U+F, returning a struct
%   x = klu (A,'\',b)       x = A\b, using KLU
%   x = klu (b,'/',A)       x = b/A, using KLU
%   x = klu (LU,'\',b)      x = A\b, where LU = klu(A)
%   x = klu (b,'/',LU)      x = b/A, where LU = klu(A)
%
%   KLU(A) factorizes a square sparse matrix, L*U+F = R\A(p,q), where L and U
%   are the factors of the diagonal blocks of the block, F are the entries
%   above the diagonal blocks.  r corresponds to the 3rd output of dmperm; it
%   specifies where the block boundaries are.  The kth block consists of
%   rows/columns r(k) to r(k+1)-1 of A(p,q).
%
%   Note that the use of the scale factor R differs between KLU and UMFPACK
%   (and the LU function, which is based on UMFPACK).  In LU, the factorization
%   is L*U = P*(R1\A)*Q; in KLU it is L*U+F = R2\(P*A*Q).  R1 and R2 are related
%   via R2 = P*R1*P', or equivalently R2 = R1(p,p).
%
%   The LU output is a struct containing members L, U, p, q, R, F, and r.
%
%   opts is an optional input struct which appears as the last input argument.
%   Entries not present are set to their defaults:
%
%                       default
%       opts.tol        0.001   partial pivoting tolerance; valid range 0 to 1.
%       opts.btf        1       use block triangular form (BTF) if nonzero
%       opts.ordering   0       how each block is ordered:
%                               0: AMD, 1: COLAMD, 2: natural,
%                               3: CHOLMOD's ordering of (A'*A),
%                               4: CHOLMOD's ordering of (A+A')
%       opts.scale      2       1: R = diag(sum(abs(A)')), row-sum
%                               2: R = diag(max(abs(A)')), max in each row
%                               otherwise: none (R=I)
%       opts.maxwork    0       if > 0, limit work in BTF ordering to
%                               opts.maxwork*nnz(A); no limit if <= 0.
%
%       The CHOLMOD ordering is to try AMD (for A+A') or COLAMD (for A'*A)
%       first.  If the fill-in with AMD or COLAMD is high, METIS is tried (on
%       A+A' or A'*A), and the best ordering found is selected.  CHOLMOD, METIS,
%       CAMD, and CCOLAMD are required.  If not available, only ordering options
%       0, 1, and 2 may be used (AMD and COLAMD are always required by KLU).
%
%   Two optional outputs, [LU,info,c] = klu (A) or [x,info,c] = klu (A,'\',b)
%   provide statistics about the factorization:
%
%       info.noffdiag   number of off-diagonal pivots chosen (after preordering)
%       info.nrealloc   number of memory reallocations of L and U
%       info.rcond      a very cheap estimate of 1/(condition number)
%       info.rgrowth    reciprocal pivot growth
%       info.flops      flop count
%       info.nblocks    # of blocks in BTF form (1 if not computed)
%       info.ordering   AMD, COLAMD, natural, cholmod(AA'), cholmod(A+A')
%       info.scale      scaling (<=0: none, 1: sum, 2: max)
%       info.lnz        nnz(L), including diagonal
%       info.unz        nnz(U), including diagonal
%       info.offnz      nnz(F)
%       info.tol        pivot tolerance used
%       info.memory     peak memory usage in bytes
%       c               the same as MATLAB's condest
%
%   info and c are relevant only if the matrix is factorized (LU = klu (A),
%   x = klu (A,'/',b), or x = klu (b,'/',A) usages).
%
%   See also BTF, LU, DMPERM, CONDEST, CHOLMOD, AMD, COLAMD, CAMD, CCOLAMD.

% Copyright 2004-2009 Timothy A. Davis, Univ. of Florida
% http://www.cise.ufl.edu/research/sparse

error ('klu mexFunction not found') ;

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
classdef ScrollPanel < hgsetget
%SCROLLPANEL A uipanel container with scrolling capabilities
%   Uipanels provide containment and groups axes and their children.  The
%   ScrollPanel provides the ability to define a scrollable area and the
%   panel is the viewport onto that area.
%
%   ScrollPanel does support the border properties of the uipanel object,
%   but in a slightly different way.  The border of the ScrollPanel does
%   not intrude upon the client area, but extends outward from it.  The
%   border of a panel is lightweight and would be obscured by the scrolling
%   objects in the scroll area.  The position of the object with the border
%   may be set using the OuterPosition property.
%
%   ScrollPanel properties:
%       Parent        - Identifies the figure or uipanel that contains the
%                       ScrollPanel object.
%       ScrollArea    - Defines the area relative the the object's position
%                       that can be scrolled through.  This area may never
%                       be less than the object's area.
%       Position      - The position of the object relative to its
%                       containing parent.  This position also serves as a
%                       viewport or window into the ScrollArea.
%       OuterPosition - The position of the object relative to its
%                       container, but including the border.
%       Backgroundcolor - The color of the viewport area.
%       Units         - The units of the ScrollPanel object as well as the
%                       ScrollArea.  The units of th me.
%       Visible       - Sets the visibility of the object.
%       ScrollMode          - Controls the appearance of scrollbars on the panel.
%                       'auto'       - automatically shows the appropriate
%                                      verticle or horizontal scrollbar if the
%                                      height or width of the ScrollArea is
%                                      greater than the height or width of the
%                                      object's position. This setting is the
%                                      default.
%                       'verticle'   - Will always display only a verticle
%                                      scrollbar.
%                       'horizontal' - will always display only a
%                                      horizontal scrollbar.
%                       'both'       - will always display both scrollbars.
%       handle        - This handle value should be used parent Handle
%                       Graphics objects to the ScrollPanel object, e.g.
%                       set(ax, 'Parent', h.handle).
%       BorderWidth, BorderPanel, Highlight Color, Shadow color - the
%                       properties of the ScrollPanel object equivalent to
%                       the ones on the uipanel object.
%
%
%   Examples:
%
%       Create a plot larger than the viewport panels position:
%           h=ScrollPanel;
%           set(h,'Position',[.25 .25 .5 .5];
%           set(h, 'ScrollArea', [0 0 2 2])
%           ax=axes('parent',h.handle)
%           plot(ax,magic(3))
%
%       Scroll around a large image:
%           imdata = imread('ngc6543a.jpg');
%           h=ScrollPanel('Position',[.25 .25 .5 .5], ...
%                         'ScrollArea', [0 0 3 3]);
%           axes('Parent', h.handle, 'Position', [0 0 1 1]);
%           image(imdata);
%
%   An important point to note is that the ScrollPanel object has the same
%   limitations as the uipanel object in terms of clipping.  Heavyweight
%   objects such as uicontrols will not be clipped.  Since scrolling will
%   tend to move these heavyweight object outside the viewport position,
%   care much be used to achieve the desired result.
%
%   The use of OpenGL and surface objects in general is also problematic
%   since they are heavyweight.  So, it is advisable to stick to 2D without
%   transparency.
%
%   See also UIPANEL.

%   Author: Jason Kinchen, MATLAB 7.11.0.514 (R2010b)
%   Contact: jason.kinchen@gmail.com
%   Revision: 1.0 (12-Dec-2010)
%
%   Comments:
%

    properties (Hidden = true, Access = private)
        hBorderPanel            % A panel to manage the borders that won't clipped.
        hViewportPanel          % The main panel
        hScrollingPanel         % The container for the ScrollingArea
        hVScrollBar
        hHScrollBar
        scrollBarWidth = 15;
        privateMode = 'auto'    % The dependent workaround for the ScrollMode property
    end
    properties (Dependent)
        %PARENT Parent object of the SCROLLBAR.
        %   Since ScrollPanel is not an internal Handle Graphics object,
        %   parenting must be done explicitly.  Use this property to set
        %   the parent container of the ScrollPanel object.
        %
        %   See also UIPANEL.
        Parent

        %SCROLLAREA The position vector relative to the object's Position.
        %   The ScrollArea property of the ScrollPanel defines the region
        %   that the main viewport panel may scroll.
        %
        %   See also UIPANEL.
        ScrollArea

        %POSITION This position vector defines where the visible viewport
        %   of the ScrollPanel appears relative to it's parent.
        %
        %   See also UIPANEL.
        Position

        %OUTERPOSITION This position vector defines the postion of the
        %   including the client region and the border.  Use this property
        %   to place the object if its place in the container is more
        %   important than the size of the scrolling viewport.
        OuterPosition

        %BACKGROUNDCOLOR The background color of the ScrollArea using a
        %   ColorSpec.
        %
        %   See also UIPANEL.
        BackgroundColor

        %UNITS The units (pixels, points, characters, inches, centimeters,
        %   normalized) of both the main viewport and the ScrollArea.
        %
        %   See also UIPANEL.
        Units

        %VISIBLE Hides or shows the ScrollPanel without changing any other
        %   property values.
        %
        %   See also UIPANEL.
        Visible

        %SCROLLMODE Determines how the scrollbars appear.  Valid values are:
        %      'auto'       - automatically shows the appropriate
        %                     verticle or horizontal scrollbar if the
        %                     height or width of the ScrollArea is
        %                     greater than the height or width of the
        %                     object's position.
        %      'verticle'   - Will always display only a verticle
        %                     scrollbar.
        %      'horizontal' - will always display only a
        %                     horizontal scrollbar.
        %       'both'      - will always display both scrollbars.
        %
        %   See also UIPANEL.
        ScrollMode = 'auto';

        %BORDERWIDTH The width of the main viewport panel's border in
        %   pixels.
        %
        %   See also UIPANEL.
        BorderWidth = 1;

        %BORDERTYPE
        %   none | {etchedin} | etchedout | beveledin | beveledout | line
        %
        %   Border of the main viewport. Used to define the panel area graphically.
        %   Etched and beveled borders provide a 3-D look. Use the HighlightColor
        %   and ShadowColor properties to specify the border color of etched and
        %   beveled borders. A line border is 2-D. Use the ForegroundColor
        %   property to specify its color.
        %
        %   See also UIPANEL.
        BorderType = 'etchedin';

        %FOREGROUNDCOLOR Color used for the 2-D border line. A three-element
        %   RGB vector or one of the MATLAB predefined names, specifying the
        %   font or line color. See the ColorSpec reference page for more
        %   information on specifying color.
        %
        %   See also UIPANEL.
        ForegroundColor = [1 1 1];

        %HIGHLIGHTCOLOR 3-D frame highlight color. A three-element RGB vector
        %   or one of the MATLAB predefined names, specifying the highlight
        %   color. See the ColorSpec reference page for more information on
        %   specifying color.
        %
        %   See also UIPANEL, COLORSPEC.
        HighlightColor = [1 1 1];

        %SHADOWCOLOR 3-D frame shadow color. A three-element RGB vector or
        %   one of the MATLAB predefined names, specifying the shadow color.
        %   See the ColorSpec reference page for more information on specifying
        %   color.
        %
        %   See also UIPANEL, COLORSPEC.
        ShadowColor = [.5 .5 .5];

    end
    properties (SetAccess = private)
        %HANDLE Since ScrollPanel is not a builtin Handle Graphics object,
        %   this property is used to directly parent object to the
        %   ScrollArea.  This handle should not be used to parent the
        %   ScrollPanel object to some other container.  Use the Parent
        %   property for that.
        %
        %   See also UIPANEL.
        handle
    end

    methods
        % The ScrollPanel constructor which takes parameter-value pairs.
        function obj = ScrollPanel(varargin)
            fig = gcf;
            % Detect if the Parent was passed in, otherwise use current
            % figure.
            for i = 1 : 2 : length(varargin)
                name = varargin{i};
                value = varargin{i+1};
                switch name
                    case 'Parent'
                      	fig = value;
                    break;
                    otherwise;
                end
            end

            % Create the objects that make up the ScrollPanel.
            obj.hBorderPanel = uipanel('Parent', fig, 'BackgroundColor', 'b',...
                                       'HandleVisibility', 'off');

            obj.hViewportPanel = uipanel('Parent', fig, 'BackgroundColor', 'r',...
                                         'BorderType', 'none',...
                                         'HandleVisibility', 'off');
            obj.Parent = fig;
            % The ScrollArea defaults to the same size as the Main Viewport
            % panel.
            obj.hScrollingPanel = uipanel('Parent', obj.hViewportPanel, ...
                                          'BorderType', 'none',...
                                          'HandleVisibility','off');

            % The slider uicontrols (scrollbars) are created invisible, but
            % are positioned in anticipation of being used.
            obj.hVScrollBar = uicontrol('Style', 'slider',...
                                       'Parent', obj.hViewportPanel,...
                                       'Units','pixels',...
                                       'Visible', 'off',...
                                       'Enable', 'off',...
                                       'HandleVisibility', 'off');

            obj.hHScrollBar = uicontrol('Style', 'slider',...
                                       'Parent', obj.hViewportPanel,...
                                       'Units','pixels',...
                                       'Position', [0 0 1 .05],...
                                       'Visible', 'off',...
                                       'Enable', 'off',...
                                       'HandleVisibility', 'off');

            % Setup the scrollbar listeners.
            addlistener(obj.hVScrollBar, 'Action', @obj.scroll);
            addlistener(obj.hHScrollBar, 'Action', @obj.scroll);
            % Setup the main viewport's size listener.  Lot's of stuff
            % needs to happen when that viewport changes.
            addlistener(obj.hViewportPanel, 'SizeChange', @obj.resize);

            % The ScrollingPanel is the exposed handle so that objects can
            % be children of it.
            obj.handle = obj.hScrollingPanel;

            % Work through the parameter-value pairs and set the initial
            % state of the properties.
            for i = 1 : 2 : length(varargin)
                name = varargin{i};
                value = varargin{i+1};
                switch name
                    case 'Units'
                        obj.Units = value;
                    case 'Position'
                        obj.Position = value;
                        drawnow;
                    case 'OuterPostion'
                        obj.ScrollArea = value;
                    case 'ScrollArea'
                        obj.ScrollArea = value;
                    case 'ScrollMode'
                        obj.ScrollMode = value;
                    case 'Visible'
                        obj.Visible = value;
                    case 'BorderWidth'
                        obj.BorderWidth = value;
                    case 'BorderType'
                        obj.BorderType = value;
                    case 'ForeGroundColor'
                        obj.ForeGroundColor = value;
                    case 'HighlightColor'
                        obj.HighlightColor = value;
                    case 'ShadowColor'
                        obj.ShadowColor = value;
                    otherwise
                        error(['Invalid property ' name]);
                end
            end
            obj.privateMode = obj.ScrollMode;
            obj.setSBPosition('both');
        end

        function set.Parent(obj, val)
            set(obj.hViewportPanel, 'Parent', val);
        end
        function val = get.Parent(obj)
            val = get(obj.hViewportPanel, 'Parent');
        end
        function set.ScrollArea(obj, pos)
            % If normalized, the position relative to the figure window is
            % not useful.  From the ScrollArea's perspective, it is from
            % zero -> one.
            if (strcmp(get(obj.hViewportPanel, 'Units'), 'normalized'))
                mPos = [0 0 1 1];
            else
                mPos = get(obj.hViewportPanel, 'Position');
                mPos(1:2)=[0 0];
            end

            % The ScrollArea must completely contain the main viewport
            % area.  If it is larger than the viewport, it must either be
            % inside it's position rectangle or lined up on the sides.
            newSPos(1:2:3) = limitLines(mPos(1:2:3), pos(1:2:3));
            newSPos(2:2:4) = limitLines(mPos(2:2:4), pos(2:2:4));
            if (strcmp(get(obj.hViewportPanel, 'Units'), 'pixels'))
                newSPos(1:2) = newSPos(1:2) + 1;
            end

            if pos(3) > mPos(3) || pos(4) > mPos(4)
                set(obj.hScrollingPanel, 'Position', newSPos);

                % In auto mode, the appropriate scrollbars must appear if the
                % length or width of the ScrollArea is greater than that of
                % the main viewport.
                if strcmp(obj.ScrollMode, 'auto')
                    if newSPos(3) > mPos(3)
                        set(obj.hHScrollBar, 'Visible', 'on', 'Enable', 'on');
                    else
                        set(obj.hHScrollBar, 'Visible', 'off', 'Enable', 'off');
                    end
                    if newSPos(4) > mPos(4)
                        set(obj.hVScrollBar, 'Visible', 'on', 'Enable', 'on');
                    else
                        set(obj.hVScrollBar, 'Visible', 'off', 'Enable', 'off');
                    end
                end
            else
                % The ScrollArea cannot be smaller than the main viewport,
                % so if we get here, the height and width is stored in the
                % position vector, the origin needs to be zero, unless the
                % units are pixels, which are 1 based.
                if strcmp(get(obj.hViewportPanel, 'Units'), 'pixels')
                    set(obj.hScrollingPanel, 'Position', [1 1 mPos(3) mPos(4)]);
                else
                    set(obj.hScrollingPanel, 'Position', [0 0 mPos(3) mPos(4)]);
                end

                %  Scrollbars need to go away if the ScrollArea and main
                %  viewport are the same size.
                if strcmp(obj.ScrollMode, 'auto')
                    set(obj.hHScrollBar, 'Visible', 'off', 'Enable', 'off');
                    set(obj.hVScrollBar, 'Visible', 'off', 'Enable', 'off');
                end
            end

            % Make sure the scrollbars are the right size and the thumbs
            % are set to the right position and width.
            obj.setSBPosition('both');
        end
        function pos = get.ScrollArea(obj)
            pos = get(obj.hScrollingPanel, 'Position');
        end
        function set.Position(obj, pos)
            % Go ahead and set the main viewport's position.
            drawnow;
            set(obj.hViewportPanel, 'Position', pos);
            setBorderPosition(obj);

            if (strcmp(get(obj.hViewportPanel, 'Units'), 'normalized'))
                pos = [0 0 1 1];
            end
            sPos = get(obj.hScrollingPanel, 'Position');
            if sPos(3) <= pos(3)
                % Don't let the width become smaller than the viewport, and
                % turn off the scrollbar if in auto mode.
                sPos(3) = max([pos(3) sPos(3)]);
                if strcmp(obj.ScrollMode, 'auto')
                    set(obj.hHScrollBar, 'Enable', 'off', 'Visible', 'off');
                end
            else
                if strcmp(obj.ScrollMode, 'auto')
                    set(obj.hHScrollBar, 'Enable', 'on', 'Visible', 'on');
                end
            end
            if sPos(4) <= pos(4)
                % Don't let the height become smaller than the viewport,
                % and turn off the scrollbar if in auto mode.
                sPos(4) = max([pos(4) sPos(4)]);
                if strcmp(obj.ScrollMode, 'auto')
                    set(obj.hVScrollBar, 'Enable', 'off', 'Visible', 'off');
                end
            else
                if strcmp(obj.ScrollMode, 'auto')
                    set(obj.hVScrollBar, 'Enable', 'on', 'Visible', 'on');
                end
            end
            set(obj.hScrollingPanel, 'Position', sPos);
            setSBPosition(obj, 'both')
        end

        % Set/Get the following properties on the appropriate container.
        function pos = get.Position(obj)
            pos = get(obj.hViewportPanel, 'Position');
        end
        function set.OuterPosition(obj, pos)
        % The OuterPostion extends out from the position. The borderwidth
        % is always in pixels so we do all the adjustments in pixels.
            set(obj.hBorderPanel, 'Position', pos);
            drawnow;
            % The above lines set the postion in the current units and the
            % line below gets the new positoin in pixels.
            pxPos = getpixelposition(obj.hBorderPanel);

            % The position of the viewport panel must be adjusted in by the
            % BorderWidth.
            pxPos = [pxPos(1) + borderAdjust(obj) ...
                     pxPos(2) + borderAdjust(obj) ...
                     pxPos(3) - 2 * borderAdjust(obj) ...
                     pxPos(4) - 2 * borderAdjust(obj)];
            drawnow;
            setpixelposition(obj.hViewportPanel, pxPos);
            obj.setSBPosition('both');
        end
        function pos = get.OuterPosition(obj)
            pos = get(obj.hBorderPanel, 'Position');
        end
        function set.BackgroundColor(obj, color)
            set(obj.hScrollingPanel, 'BackgroundColor', color);
        end
        function color = get.BackgroundColor(obj)
            color = set(obj.hScrollingPanel, 'BackgroundColor');
        end
        function set.Units(obj, units)
            set(obj.hBorderPanel', 'Units', units');
            set(obj.hViewportPanel, 'Units', units);
            set(obj.hScrollingPanel, 'Units', units);
        end
        function units = get.Units(obj)
            units = get(obj.hViewportPanel, 'Units');
        end
        function set.Visible(obj, val)
            set(obj.hViewportPanel, 'Visible', val)
        end
        function val = get.Visible(obj)
            val = get(obj.hViewportPanel, 'Visible');
        end
        function set.ScrollMode(obj, val)
            % Check that the value passed in is a valid value.
            valid = {'auto', 'verticle', 'horizontal', 'both'};
            if any(cellfun(@(x) strcmp(x,val),valid))
                % Since this is a dependent property, we need to save the
                % actual value in the private property.
                obj.privateMode = val;
                switch(val)
                    case 'auto'
                        % If auto mode is turned on, all the right things
                        % happen if we call the set method using the
                        % current value.
                        set(obj, 'ScrollArea', get(obj, 'ScrollArea'));
                    case 'verticle'
                        % Enable the verticle, disable the horizontal.
                        set(obj.hVScrollBar, 'Enable', 'on', 'Visible', 'on');
                        set(obj.hHScrollBar, 'Enable', 'off', 'Visible', 'off');
                        obj.setSBPosition('verticle');
                    case 'horizontal'
                        % Enable the horizontal, disable the verticle.
                        set(obj.hHScrollBar, 'Enable', 'on', 'Visible', 'on');
                        set(obj.hVScrollBar, 'Enable', 'off', 'Visible', 'off');
                        obj.setSBPosition('horizontal');
                    case 'both'
                        % Enable the horizontal and the verticle.
                        set(obj.hVScrollBar, 'Enable', 'on', 'Visible', 'on');
                        set(obj.hHScrollBar, 'Enable', 'on', 'Visible', 'on');
                        obj.setSBPosition('both');
                end

            else
                error('ScrollPanel:setScrollMode:badScrollModeValue',...
                      ['Bad property value ' val ' for ScrollMode.']);
            end
        end
        function val = get.ScrollMode(obj)
            val = obj.privateMode;
        end
        function set.BorderWidth(obj, val)
            set(obj.hBorderPanel, 'BorderWidth', val);
            setBorderPosition(obj);
        end
        function val = get.BorderWidth(obj)
            val = get(obj.hBorderPanel, 'BorderWidth');
        end
        function set.BorderType(obj, val)
            set(obj.hBorderPanel, 'BorderType', val);
            setBorderPosition(obj);
        end
        function val = get.BorderType(obj)
            val = get(obj.hBorderPanel, 'BorderType');
        end
        function set.ForegroundColor(obj, val)
            set(obj.hBorderPanel, 'ForegroundColor', val);
        end
        function val = get.ForegroundColor(obj)
            val = get(obj.hBorderPanel, 'ForegroundColor');
        end
        function set.HighlightColor(obj, val)
            set(obj.hBorderPanel, 'HighlightColor', val);
        end
        function val = get.HighlightColor(obj)
            val = get(obj.hBorderPanel, 'HighlightColor');
        end
        function set.ShadowColor(obj, val)
            set(obj.hBorderPanel, 'ShadowColor', val);
        end
        function val = get.ShadowColor(obj)
            val = get(obj.hBorderPanel, 'ShadowColor');
        end
        function delete(obj)
            if ishghandle(obj.hBorderPanel)
                delete(obj.hBorderPanel);
            end
            if ishghandle(obj.hViewportPanel)
                delete(obj.hViewportPanel);
            end
        end
    end
    methods (Access = protected)
        % Don't want to allow the user to call these.
        function setSBPosition(obj, scrollbar)
            % The scrollbars in in pixel units, so we need to get the
            % main viewport's position in pixels.
            pos = getpixelposition(obj.hViewportPanel);

            % We are doing similiar position calculations for horizontal
            % and verticle scrollbars.  The following just sets up the
            % appropriate variables.
            if strcmp(scrollbar, 'verticle') || strcmp(scrollbar, 'both')
                hScrollBar = obj.hVScrollBar;
                otherhScrollBar = obj.hHScrollBar;
                origin_i = 2;
                length_i = 4;
                scrPos = [1 + pos(3) - obj.scrollBarWidth ...
                          1 ...
                          obj.scrollBarWidth ...
                          pos(length_i)];
                bothPos = [scrPos(1) ...
                           scrPos(2) + obj.scrollBarWidth ...
                           scrPos(3) ...
                           scrPos(4) - obj.scrollBarWidth];
            else
                hScrollBar = obj.hHScrollBar;
                otherhScrollBar = obj.hVScrollBar;
                origin_i = 1;
                length_i = 3;
                scrPos = [1 ...
                          1 ...
                          pos(3)...
                          obj.scrollBarWidth];
                bothPos = [scrPos(1) ...
                           scrPos(2) ...
                           scrPos(3) - obj.scrollBarWidth ...
                           scrPos(4)];
            end

            % Use the private property scrollBarWidth and set the
            % one-based position based on the viewport's area.  The length
            % of the scrollbar is slightly shorter if the other one is
            % visible.
            if strcmp(get(otherhScrollBar, 'Visible'), 'on')
                set(hScrollBar, 'Position', bothPos);
            else
                set(hScrollBar, 'Position', scrPos);
            end
            sPos = get(obj.hScrollingPanel', 'Position');

            % Get the viewport panel's position to calculate the thumbsize
            % and positon of the thumb.
            if strcmp(get(obj.hViewportPanel, 'Units'), 'normalized')
                mPos = [0 0 1 1];
            else
                mPos = get(obj.hViewportPanel, 'Position');
            end

            %Stepsize determines the thumb size.
            step = get(hScrollBar, 'SliderStep');
            step(2) = max(0, mPos(length_i)/(sPos(length_i) - mPos(length_i)));
            set(hScrollBar, 'SliderStep', step);

            if mPos(origin_i) == sPos(origin_i)
                slpos = 0;
            else if mPos(origin_i) + mPos(length_i) == sPos(origin_i) + sPos(length_i)
                slpos = 1;
                else
                    slpos = min([1, (mPos(origin_i) - sPos(origin_i))/(sPos(length_i)-mPos(length_i))]);
                end
            end

            set(hScrollBar, 'Value', slpos);

            if strcmp(scrollbar, 'both')
                setSBPosition(obj, 'horizontal');
            end
        end
        function val = borderAdjust(obj)
            val = get(obj.hBorderPanel, 'BorderWidth');
            switch get(obj.hBorderPanel, 'BorderType')
                case 'etchedin'
                    val = val * 2;
                case 'etchedout'
                    val = val * 2;
                case 'none'
                    val = 0;
                otherwise
            end
        end
        function setBorderPosition(obj)
            pxPos = getpixelposition(obj.hViewportPanel);
            setpixelposition(obj.hBorderPanel, [pxPos(1) - borderAdjust(obj) ...
                                                pxPos(2) - borderAdjust(obj) ...
                                                pxPos(3) + 2*borderAdjust(obj) ...
                                                pxPos(4) + 2*borderAdjust(obj)]);
        end
        function resize(obj, ~, ~)
            % After the viewport position is set, we need to move the
            % scrollbars back to the edges.
            drawnow;
            obj.setSBPosition('both');
            setBorderPosition(obj);
        end
        function scroll(obj, src, ~)
            % Again, normalized coordinates will need to be set manually
            % because it returns those relative to the figure window.
            if strcmp(get(obj.hViewportPanel, 'Units'), 'normalized')
                mPos = [0 0 1 1];
            else
                mPos = get(obj.hViewportPanel, 'Position');
            end

            sPos = get(obj.hScrollingPanel, 'Position');

            % Setup the variables for the appropriate scrollbar.
            if src == obj.hVScrollBar
                hScrollBar = obj.hVScrollBar;
                length_i = 4;
            else
                hScrollBar = obj.hHScrollBar;
                length_i = 3;
            end

            % Get the position of the slider, calcuate the ratio of
            % viewport to ScrollArea and set the new position of the
            % ScrollArea.
            value = get(hScrollBar, 'Value');
            pos = (sPos(length_i) - mPos(length_i))*(-value);
            if strcmp(get(obj.hScrollingPanel, 'Units'), 'pixels')
                pos = pos + 1;
            end
            if src == obj.hVScrollBar
                sPos = [sPos(1) pos sPos(3) sPos(4)];
            else
                sPos = [pos sPos(2) sPos(3) sPos(4)];
            end
            set(obj.hScrollingPanel, 'Position', sPos);
        end
    end
    methods (Hidden = true)
        function [h v] = getSBPosition(obj)
            h = get(obj.hHScrollBar, 'Position');
            v = get(obj.hVScrollBar, 'Position');
        end
    end
end

function newLine = limitLines(smallLine, largeLine)
% Limit a longer line to the endpoints of the smaller line.  In other
% words, the extents of the smaller line must be within those of the larger
% line.
    sStart = smallLine(1);
    sEnd = smallLine(1) + smallLine(2);

    lStart = largeLine(1);
    lEnd = largeLine(1) + largeLine(2);
    lLength = largeLine(2);

    if lStart < sStart && lEnd < sEnd
        newLine(2) = lLength;
        newLine(1) = sEnd - lLength;
    else if lStart > sStart
            newLine(1) = sStart;
            newLine(2) = lLength;
        else
            newLine = largeLine;
        end
    end
end

author: covartech

repo: PRT

save_path: github-repos/MATLAB/covartech-PRT


text:
function D = driving_function_mono_sdm_kx_pw(kx,nk,f,conf)
%DRIVING_FUNCTION_MONO_SDM_KX_PW driving signal for a plane wave in SDM in
%the kx-domain
%
%   Usage: D = driving_function_mono_sdm_kx_pw(kx,nk,f,conf)
%
%   Input parameters:
%       kx          - kx dimension [nx1]
%       nk          - direction of plane wave / m [1x3]
%       f           - frequency of the monochromatic source / Hz
%       conf        - configuration struct (see SFS_config)
%
%   Output parameters:
%       D           - driving function signal [nx1]
%
%   See also: driving_function_mono_sdm_kx, sound_field_mono_sdm_kx

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

%% ===== Checking of input  parameters ==================================
nargmin = 4;
nargmax = 4;
narginchk(nargmin,nargmax);
isargmatrix(kx,nk);
isargpositivescalar(f);
isargstruct(conf);

%% ===== Configuration ==================================================
xref = conf.xref;
c = conf.c;
dimension = conf.dimension;
driving_functions = conf.driving_functions;

%% ===== Computation ====================================================
% Calculate the driving function in time-frequency domain

% Frequency
omega = 2*pi*f;
D = zeros(1,length(kx));

if strcmp('2D',dimension)

    % === 2-Dimensional ==================================================

    % Ensure 2D
    nk = nk(:,1:2);

    switch driving_functions
    case 'default'
        % --- SFS Toolbox ------------------------------------------------
        to_be_implemented;
    otherwise
        error(['%s: %s, this type of driving function is not implemented ', ...
            'for a 2D plane wave.'],upper(mfilename),driving_functions);
    end

elseif strcmp('2.5D',dimension)

    % === 2.5-Dimensional ================================================

    switch driving_functions
    case 'default'
        % --- SFS Toolbox ------------------------------------------------
        % D_2.5D using a plane wave as source model
        %
        %                   e^(-i w/c nky*xrefy)
        % D_2.5D(x0,w) = 4i ----------------------
        %                     (2) /w          \
        %                    H0  | - nky*xrefy |
        %                         \c          /
        %
        % https://sfs.rtfd.io/en/3.2/d_nfchoa/#equation-fd-sdm-plane-25d
        %
        idx = find(kx>=omega/c*nk(:,1),1,'first');
        D(idx) = 4*1i*exp(-1i*omega/c*nk(2).*xref(2)) / ...
            besselh(0,2,omega/c.*nk(2).*xref(2));
        %
    otherwise
        error(['%s: %s, this type of driving function is not implemented ', ...
            'for a 2.5D plane wave.'],upper(mfilename),driving_functions);
    end

elseif strcmp('3D',dimension)

    % === 3-Dimensional ==================================================

    switch driving_functions
    case 'default'
        % --- SFS Toolbox ------------------------------------------------
        to_be_implemented;
    otherwise
        error(['%s: %s, this type of driving function is not implemented ', ...
            'for a 3D plane wave.'],upper(mfilename),driving_functions);
    end

else
    error('%s: the dimension %s is unknown.',upper(mfilename),dimension);
end

author: sfstoolbox

repo: sfs-matlab


text:
function varargout = leon(X)
% Leon funcion
%
%   LEON([x1, x2]) returns the value of the value of the Leon
%   function at the specified points. [x1] and [x2] may be vectors.
%   The search domain is
%
%               -1.2 < x_i < 1.2
%
%   The global minimum is
%
%               f(x1, x2) = f(1, 1) = 0.

% Author: Rody P.S. Oldenhuis
% Delft University of Technology
% E-mail: oldenhuis@dds.nl
% Last edited 20/Jul/2009

    % if no input is given, return dimensions, bounds and minimum
    if (nargin == 0)
        varargout{1} = 2;  % # dims
        varargout{2} = [-1.2, -1.2]; % LB
        varargout{3} = [+1.2, +1.2]; % UB
        varargout{4} = [1,1]; % solution
        varargout{5} = 0; % function value at solution

    % otherwise, output function value
    else

        % keep values inside the search domain
        X(X < -1.2) = inf;      X(X > 1.2) = inf;

        % split input vector X into x1, x2
        if size(X, 1) == 2
            x1 = X(1, :);        x2 = X(2, :);
        else
            x1 = X(:, 1);        x2 = X(:, 2);
        end

        % output function value
        varargout{1} = 100*(x2 - x1.^2).^2 + (1 - x1).^2;
    end

end


text:
function s = delta_function_from_parfile(parName,tr,nFrames)
% s = delta_function_from_parfile(parName,[tr],[nFrames])
%
% Given the name of a parfile, reads in the info
% and produces a matrix s that has as rows frames
% and as columns conditions (stimulus types). Each
% column is a delta function of onsets.
%
% (If a cell-of-strings is provided for parName,
% will load a list of parfiles, adding each run
% as the 3rd dimension.)
%
% 11/04 ras.
if notDefined('tr')
    tr = [];
end

if notDefined('nFrames')
    nFrames = [];
end

s = [];

if iscell(parName)
	% recursively get delta functions for each file, returning a
	% 3D matrix (slices = runs, deals w/ different-length runs)
	onsets = [];  conds = [];  offset = 0;
    for p = 1:length(parName)
		s_sub = delta_function_from_parfile(parName{p}, tr, nFrames);
		if p==1
			s = s_sub;
		elseif size(s, 1)==size(s_sub, 1)
			s(:,:,p) = s_sub;
		elseif size(s, 1) > size(s_sub, 1)
			s(1:size(s_sub, 1),:,p) = s_sub;
		elseif size(s, 1) < size(s_sub, 1)
			s(size(s_sub, 1),end,p-1) = 0;
			s(:,:,p) = s_sub;
		end
	end
	return
else
	[onsets conds] = readParFile(parName);
end

% 'shifting' parfile onsets, e.g. to correct for variations in
% when the scan started, may produce negative onsets, which we
% don't need:
ok = find(onsets>=0);
onsets = onsets(ok);
conds = conds(ok);
if isempty(tr)
    % estimate from parfile
    tr = onsets(2) - onsets(1);
end
whichConds = unique(conds);
nConds = length(whichConds);
if isempty(nFrames)
    nFrames = ceil(onsets(end) ./ tr);
end

% initialize s
s = zeros(nFrames, nConds);

% insert 1s at onset frames
for c = 1:nConds
    trials = onsets(conds==whichConds(c)) / tr;
    s(trials+1,c) = 1;
end

% truncate if it goes over
s = s(1:nFrames,:);

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function f = bilinear_kernel(k, num_input, num_output)
% -------------------------------------------------------------------------
%   Description:
%       create bilinear interpolation kernel for the convt (deconv) layer
%
%   Input:
%       - k             : kernel size k x k
%       - num_input     : number of input channels
%       - num_output    : number of output channels
%
%   Output:
%       - f             : bilinear filter
%
%   Citation:
%       Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution
%       Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang
%       IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017
%
%   Contact:
%       Wei-Sheng Lai
%       wlai24@ucmerced.edu
%       University of California, Merced
% -------------------------------------------------------------------------

    radius = ceil(k / 2);

    if rem(k, 2) == 1
        center = radius;
    else
        center = radius + 0.5;
    end

    C = 1:k;
    f = (ones(1, k) - abs(C - center) ./ radius)' ...
      * (ones(1, k) - abs(C - center) ./ radius);

    f = repmat(f, 1, 1, num_input, num_output);

end

repo: LapSRN


text:
report_this_filefun(mfilename('fullpath'));

% Now lets plot the color-map of the z-value
%
figure

set(gca,'visible','off','FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold',...
    'FontWeight','bold','LineWidth',1.5,...
    'Box','on','SortMethod','childorder')

rect = [0.18,  0.10, 0.7, 0.75];
rect1 = rect;

% set values greater tresh = nan
%
re4 = re3;l = r > tresh; re4(l) = zeros(1,length(find(l)))*nan;

% plot image
%
orient portrait
set(gcf,'PaperPosition', [2. 1 7.0 5.0])

axes('position',rect);hold on
pco1 = pcolor(gx,gy,(re4));
axis([ min(gx) max(gx) min(gy) max(gy)]); axis image; hold on
shading interp;
caxis([0.40 1.00])
if exist('pro', 'var')
    l = pro > 0;
    pro2 = pro;
    pro2(l) = pro2(l)*nan;
    %cs =contour(gx,gy,pro,[ 99 100],'w--');

    % cs =contour(gx,gy,pro,[95 99],'k');
    %[cs, hc] =contour(gx,gy,pro,[ 99 100],'w-');
end % if exist pro
h = jet(64);h = [  h(64:-1:1,:)]; colormap(h)
%end
if fre == 1
    caxis([fix1 fix2])
end

set(gca,'Color',[0.9 0.9 0.9])
%brighten(0.5)
%xlabel('Distance in [km]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)
%ylabel('depth in [km]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)
%set(gca,'XTickLabels',[])
set(gca,'YTick',[ -15 -10 -5 0 ])
set(gca,'YTickLabels',[ 15 10 5 0 ])

if exist('maex', 'var')
    pl = plot(maex,-maey,'*k');
    set(pl,'MarkerSize',6,'LineWidth',2)
end
overlay

set(gca,'visible','on','FontSize',10,'FontWeight','normal',...
    'FontWeight','normal','LineWidth',1.0,...
    'Box','on','TickDir','out')
h1 = gca;hzma = gca;

% Create a colobar
%
%h5 = colorbar('vertical');
%set(h5,'Pos',[0.25 0.25 0.03 0.25],...
%'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m,'TickDir','out')

% Make the figure visible
%

axes(h1)

author: CelsoReyes


text:
classdef GeometricVectorZConstraint < AbstractGeometricVectorConstraint
    %GeometricVectorMagConstraint Summary of this class goes here
    %   Detailed explanation goes here

    properties

    end

    methods
        function obj = GeometricVectorZConstraint(vector, event, lb, ub)
            obj.vector = vector;
            obj.event = event;
            obj.lb = lb;
            obj.ub = ub;

            obj.type = 'VectorZ';

            obj.id = rand();
        end

        function type = getConstraintType(obj)
            type = 'Geometric Vector Z Component';
        end
    end

    methods(Static)
        function constraint = getDefaultConstraint(~, ~)
            constraint = GeometricVectorZConstraint(AbstractGeometricVector.empty(1,0), LaunchVehicleEvent.empty(1,0), 0, 0);
        end
    end
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function c=comp_nonsepdgtreal_quinqux(f,g,a,M)
%COMP_NONSEPDGTREAL_QUINQUX  Compute Non-separable Discrete Gabor transform
%   Usage:  c=comp_nonsepdgtreal_quinqux(f,g,a,M);
%
%   This is a computational subroutine, do not call it directly.

%   AUTHOR : Nicki Holighaus and Peter L. Søndergaard
%   TESTING: TEST_NONSEPDGT
%   REFERENCE: REF_NONSEPDGT

lt=[1 2];

L=size(f,1);
W=size(f,2);
N=L/a;
M2=floor(M/2)+1;

% ----- algorithm starts here, split into sub-lattices ---------------

c=zeros(M,N,W,assert_classname(f,g));

mwin=comp_nonsepwin2multi(g,a,M,[1 2],L);

% simple algorithm: split into sublattices

for ii=0:1
    c(:,ii+1:2:end,:)=comp_dgt(f,mwin(:,ii+1),2*a,M,[0 1],0,0,0);
end;

% Phase factor correction
E = zeros(1,N,assert_classname(f,g));
for win=0:1
    for n=0:N/2-1
        E(win+n*2+1) = exp(-2*pi*i*a*n*rem(win,2)/M);
    end;
end;

c=bsxfun(@times,c(1:M2,:,:),E);

author: ltfat

repo: ltfat

save_path: github-repos/MATLAB/ltfat-ltfat


function price = Price_Exchange_Option_Margrabe_2D( S0_1, S0_2, T, rho, sigma_1, sigma_2, q_1, q_2)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% About: calcuates Price of 2D Exchange option, (S_1(T) - S_2(T)), using Magrabe Formula Under 2D Diffusion
% Author: Justin Lars Kirkby
%
% -----------------
% Params
% -----------------
% S0_1    = initial asset price of first asset, e.g. S0_1 = 100
% S0_2    = initial asset price of second asset, e.g. S0_2 = 100
% T       = time to maturity in years (e.g. T=1)
% rho     = instantaneous correlation between S_1 and S_2
% sigma_1 = volatility of first asset (annualized), e.g. sigma = 0.2
% sigma_2 = volatility of second asset (annualized), e.g. sigma = 0.2
% q_1     = dividend yield of first asset, e.g. q_1 = 0.02
% q_2     = dividend yield of second asset, e.g. q_2 = 0.02
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

sig = sqrt(sigma_1^2 - 2*rho*sigma_1*sigma_2 + sigma_2^2);
d1 = (log(S0_1/S0_2) + 0.5*sig^2*T)/(sig*sqrt(T));
d2 = d1 - sig*sqrt(T);
price = exp(-q_1*T)*S0_1*normcdf(d1) - exp(-q_2*T)*S0_2*normcdf(d2);

end


text:
function f = p02_fun ( option, n, x )

%*****************************************************************************80
%
%% P02_FUN evaluates the integrand for problem 2.
%
%  Discussion:
%
%    The exact value is sqrt(pi).
%
%    Integral ( -oo < x < +oo ) exp(-x*x) dx
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 May 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer OPTION:
%    0, integrand is f(x).
%    1, integrand is exp(-x*x) * f(x);
%    2, integrand is exp(-x*x/2) * f(x);
%
%    Input, integer N, the number of points.
%
%    Input, real X(N), the evaluation points.
%
%    Output, real F(N), the function values.
%
  x = x ( : );
  f = zeros ( n, 1 );

  f(1:n) = 1;

  if ( option == 0 )
    f(1:n) = f(1:n) .* exp ( - x(1:n).^2 );
  elseif ( option == 1 )

  elseif ( option == 2 )
    f(1:n) = f(1:n) .* exp ( - 0.5 * x(1:n).^2 );
  end

  return
end


text:
function count=get_lines_executed_count(obj)
% get a mask indicating which lines have been executed
%
% count=get_lines_executed_count(obj)
%
% Input:
%   obj                 MOcovMFile instance
%
% Output:
%   count               Nx1 numeric vector, with count(k)=c indicating
%                       that the k-th line has been executed k times. Lines
%                       that are marked as non-executable have a value of
%                       zero.

    count=obj.executed_count;
    count(~get_lines_executable(obj))=0;

author: qMRLab

repo: qMRLab

save_path: github-repos/MATLAB/qMRLab-qMRLab


text:
function [v,Energy] = coordlsl1(A,f,lambda,varargin)
%COORDLSL1   Least-squares L1 minimization with coordinate descent
%   u = COORDLSL1(A,f,lambda) solves the minimization problem
%
%     min_u ||u||_1 + lambda ||A*u - f||_2^2
%
%   where A is an MxN matrix and f is a vector of length M.
%
%   COORDLSL1(...,'PARAM1',VALUE1,'PARAM2',VALUE2,...) can be used to
%   specify additional parameters:
%     u0           - Initial value of u (default 0)
%     B            - Precomputed A'*A
%     Tol          - Stopping tolerance: |du| < Tol (default 1e-4)
%     MaxIter      - Maximum iterations (default 1e3)
%     PlotFun      - A function handle with the syntax PlotFun(u) for
%                    plotting intermediate solutions (default [])
%     Display      - If equal to 1, displays convergence information when
%                    solver converges (default 1)
%
%   [u,Energy] = COORDLSL1(...) returns a vector of energy values at each
%   iteration (beginning with the first iteration).
%
%   See also coordl1breg.

% Yingying Li 2009

%%% Default parameters %%%
u0 = zeros(size(A,2),1);
MaxIter = 1e3;
Tol = 1e-4;
PlotFun = [];
B = [];
Display = 1;

%%% Parse inputs %%%
if nargin >= 2
    parseinput(varargin);
end

OutputEnergyFlag = (nargout >= 2);  % Check if Energy is an output

if isempty(B)
    B = A'*A;
end

w = diag(B);
NormalizedFlag = all(w == 1);
v = u0;
C = A'*f;

mu = 1/2/lambda;
temp = C;

if OutputEnergyFlag
    Energy = zeros(MaxIter,1);
end

%%% Main Loop %%%
for j = 1:MaxIter
    if NormalizedFlag
        tilde_v = min(temp + mu, max(0,temp - mu));
        dEnergy = lambda*(v.^2 - tilde_v.^2) + abs(v) - abs(tilde_v) - 2*lambda*temp.*(v-tilde_v);
    else
        tilde_v = min(temp + mu, max(0,temp - mu))./w;
        dEnergy = lambda*(v.^2 - tilde_v.^2).*w + abs(v) - abs(tilde_v) - 2*lambda*temp.*(v-tilde_v);
    end

    [dvchange,i] = max((dEnergy));

    if OutputEnergyFlag
        Energy(j) = norm(A*v-f,2)^2*lambda + sum(abs(v));
    end

    if ~isempty(PlotFun)
        PlotFun(v);
    end

    dv = (v(i)-tilde_v(i));

    if abs(dv) < Tol
        if Display
            fprintf('Converged in %d iterations with |du| = %.4e < %.4e.\n',...
                j,abs(dv),Tol);
        end
        break;
    end

    temp = temp + dv*B(:,i);

    if NormalizedFlag
        temp(i) = temp(i) - dv;
    else
        temp(i) = temp(i) - dv*w(i);
    end

    v(i) = tilde_v(i);
end

if OutputEnergyFlag
    Energy = Energy(1:j);
end

return;

function parseinput(pvlist)
%PARSEINPUT  Parse varargin list of property/value pairs
Property = {'u0','MaxIter','Tol','PlotFun','B','Display'};

for k = 1:2:length(pvlist)-1
    if ~ischar(pvlist{k})
        error('Invalid property');
    end

    i = find(strcmpi(pvlist{k},Property));

    if length(i) ~= 1
        error('Invalid property');
    elseif ischar(pvlist{k+1})
        error('Invalid value');
    else
        assignin('caller',pvlist{k},pvlist{k+1});
    end
end
return;


text:
function [pvec, pstruct] = tapas_hgf_ar1_mab_transp(r, ptrans)
% --------------------------------------------------------------------------------------------------
% Copyright (C) 2012-2013 Christoph Mathys, TNU, UZH & ETHZ
%
% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public
% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version). For further details, see the file
% COPYING or <http://www.gnu.org/licenses/>.

pvec    = NaN(1,length(ptrans));
pstruct = struct;

l = r.c_prc.n_levels;

pvec(1:l)         = ptrans(1:l);                           % mu_0
pstruct.mu_0      = pvec(1:l);
pvec(l+1:2*l)     = exp(ptrans(l+1:2*l));                  % sa_0
pstruct.sa_0      = pvec(l+1:2*l);
pvec(2*l+1:3*l)   = tapas_sgm(ptrans(2*l+1:3*l),1);        % phi
pstruct.phi       = pvec(2*l+1:3*l);
pvec(3*l+1:4*l)   = ptrans(3*l+1:4*l);                     % m
pstruct.m         = pvec(3*l+1:4*l);
pvec(4*l+1:5*l-1) = exp(ptrans(4*l+1:5*l-1));              % ka
pstruct.ka        = pvec(4*l+1:5*l-1);
pvec(5*l:6*l-1)   = ptrans(5*l:6*l-1);                     % om
pstruct.om        = pvec(5*l:6*l-1);
pvec(6*l)         = exp(ptrans(6*l));                      % al
pstruct.al        = pvec(6*l);

return;

author: translationalneuromodeling

repo: tapas


text:
classdef MimMarkerPointManager < CoreBaseClass
    % MimMarkerPointManager. Part of the internal gui for the TD MIM Toolkit.
    %
    %     You should not use this class within your own code. It is intended to
    %     be used internally within the gui of the TD MIM Toolkit.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties (Access = private)
        MarkerLayer
        MarkerPointImage
        BackgroundImageSource
        MarkerDisplayParameters
        ViewerPanel
        Gui
        GuiDataset
        AppDef
        Reporting

        MarkersHaveBeenLoaded = false
        MarkerImageHasUnsavedChanges = false
        MarkerSetInitialSave = false
    end

    events
        SavedMarkerListChanged
    end

    properties (SetObservable, SetAccess = private)
        CurrentMarkersName
    end

    methods
        function obj = MimMarkerPointManager(marker_layer, marker_image_source, marker_display_parameters, background_image_source, viewer_panel, gui, gui_dataset, app_def, reporting)
            obj.MarkerLayer = marker_layer;
            obj.MarkerPointImage = marker_image_source;
            obj.BackgroundImageSource = background_image_source;
            obj.MarkerDisplayParameters = marker_display_parameters;
            obj.ViewerPanel = viewer_panel;
            obj.Gui = gui;
            obj.GuiDataset = gui_dataset;
            obj.AppDef = app_def;
            obj.Reporting = reporting;
            obj.AddEventListener(marker_image_source, 'MarkerImageHasChanged', @obj.MarkerImageChangedCallback);
            obj.AddEventListener(background_image_source, 'NewImage', @obj.BackgroundImageChangedCallback);
            obj.AddEventListener(background_image_source, 'ImageModified', @obj.BackgroundImageChangedCallback);
        end

        function ClearMarkers(obj)
            obj.MarkersHaveBeenLoaded = false;
            obj.CurrentMarkersName = [];
            obj.MarkerPointImage.ClearMarkers();
            obj.ResetImageChangedFlag();
        end

        function AutoSaveMarkers(obj)
            if ~isempty(obj.MarkerLayer) && obj.MarkerImageHasUnsavedChanges && obj.MarkersHaveBeenLoaded
                saved_marker_points = obj.GuiDataset.LoadMarkers(obj.CurrentMarkersName);
                current_marker_points = obj.GetMarkersToSave();
                markers_changed = false;
                if isempty(saved_marker_points)
                    if ~isempty(current_marker_points.MarkerList)
                        markers_changed = true;
                    end
                else
                    if isa(saved_marker_points, 'PTKImage')
                        markers_changed = true;
                    else
                        if ~isequal(saved_marker_points.MarkerList, current_marker_points.MarkerList)
                            markers_changed = true;
                        end
                    end
                end

                if markers_changed

                    % Depending on the software settings, the user can be prompted before saving
                    % changes to the markers
                    if obj.AppDef.ConfirmBeforeSavingMarkers
                        choice = questdlg('Do you want to save the changes you have made to the current markers?', ...
                            'Unsaved changes to markers', 'Delete changes', 'Save', 'Save');
                        switch choice
                            case 'Save'
                                obj.SaveMarkers();
                            case 'Don''t save'
                                obj.SaveMarkersBackup();
                                disp('Abandoned changes have been stored in AbandonedMarkerPoints.mat');
                        end
                    else
                        obj.SaveMarkers();
                    end
                end
            end
        end

        function SaveMarkersManualBackup(obj)
            if obj.GuiDataset.DatasetIsLoaded()
                markers = obj.GetMarkersToSave();
                obj.GuiDataset.SaveMarkers('MarkerPointsLastManualSave', markers);
            end
        end

        function LoadMarkersIfRequired(obj, name)
            if obj.IsLoadMarkersRequired()
                obj.LoadMarkers(name);
            end
        end

        function load_required = IsLoadMarkersRequired(obj)
            load_required = ~obj.MarkersHaveBeenLoaded && (obj.MarkerDisplayParameters.ShowMarkers || obj.ViewerPanel.IsInMarkerMode);
        end

        function LoadMarkers(obj, name)
            obj.AutoSaveMarkers();
            new_marker_list = obj.GuiDataset.LoadMarkers(name);
            if isempty(new_marker_list)
                new_marker_image = GemMarkerPointImage(zeros(0,4));
            else
                new_marker_image = GemMarkerPointImage(new_marker_list.ConvertToMarkerList());
            end
            obj.MarkerPointImage.LoadMarkers(new_marker_image);
            if isempty(new_marker_list)
                obj.SaveMarkers();
            end
            obj.ResetImageChangedFlag();
            obj.MarkersHaveBeenLoaded = true;
            obj.CurrentMarkersName = name;
        end

        function current_markers = GetCurrentMarkerSetName(obj)
            current_markers = obj.CurrentMarkersName;
        end

        function AddMarkerSet(obj, name)
            obj.SaveMarkers();
            obj.LoadMarkers(name);
            obj.SaveMarkers();
            notify(obj, 'SavedMarkerListChanged');
        end

        function DeleteMarkerSet(obj, name)
            obj.GuiDataset.DeleteMarkerSet(name);
            if strcmp(name, obj.GetCurrentMarkerSetName())
                obj.ClearMarkers();
            end
            notify(obj, 'SavedMarkerListChanged');
        end
    end

    methods (Access = private)
        function SaveMarkers(obj)
            if obj.GuiDataset.DatasetIsLoaded()
                if isempty(obj.CurrentMarkersName)
                    if ~isempty(obj.MarkerPointImage.MarkerList)
                        obj.Reporting.Error('MimMarkerPointManager:NoMarkerFilename', 'The markers could not be saved as the marker filename has not been specified. ');
                    end
                else
                    obj.Reporting.ShowProgress('Saving Markers');
                    markers = obj.GetMarkersToSave();
                    obj.GuiDataset.SaveMarkers(obj.CurrentMarkersName, markers);
                    obj.ResetImageChangedFlag();
                    obj.Reporting.CompleteProgress();
                end
            end
        end

        function marker_list_to_save = GetMarkersToSave(obj)
            image_to_save = obj.MarkerPointImage.GetImageToSave(obj.BackgroundImageSource.Image);
            series_uid = obj.GuiDataset.GetUidOfCurrentDataset();
            marker_list_to_save = MimMarkerList(image_to_save, series_uid);
        end

        function SaveMarkersBackup(obj)
            if obj.GuiDataset.DatasetIsLoaded
                obj.Reporting.ShowProgress('Abandoning Markers');
                markers = obj.GetMarkersToSave();
                obj.GuiDataset.SaveMarkers('AbandonedMarkerPoints', markers);
                obj.Reporting.CompleteProgress;
            end
        end

        function BackgroundImageChangedCallback(obj, ~, ~)
            obj.MarkerPointImage.BackgroundImageChanged(obj.BackgroundImageSource.Image);
            obj.MarkerLayer.MarkerImageChanged();
            obj.ResetImageChangedFlag();
        end

        function MarkerImageChangedCallback(obj, ~, ~)
            obj.MarkerImageHasUnsavedChanges = true;
        end

        function ResetImageChangedFlag(obj)
            obj.MarkerImageHasUnsavedChanges = false;
        end
    end
end

author: tomdoel

repo: pulmonarytoolkit


text:
%  Figure 10.6      Feedback Control of Dynamic Systems, 6e
%                        Franklin, Powell, Emami
%
% fig10_06.m is a script to generate Fig. 10.6
% frequency response for the PD design for the satellite
clf;
% parameters for the two-mass spring model
m=[1 .1]; k0=[0 .091] ; d0=[0 .0036]; k1=[0 .4];

% call function
[f,g,h,j]=twomass(m,k0,d0);
nc1=0.25*[2 1];
dc1=[1/40 1];

% convert to state-space
[ac,bc,cc,dc]=tf2ss(nc1, dc1);

% series of controller and plant
[aol,bol,col,dol]= series(ac, bc,cc,dc,f,g,h,j);
[acl]=aol-bol*col;
w=logspace(-1,1);w(26)=1;
[magcl1, phcl1]= bode(aol,bol,col,dol,1,w);
subplot(211) ;
loglog(w,[magcl1, ones(size(magcl1))]);
xlabel('\omega (rad/sec)');
ylabel('Magnitude, |KD_1(s)G(s)|');
title('Fig. 10.6 Frequency response for the satellite PD design')
grid
subplot(212);
semilogx(w, [phcl1, -180*ones(size(phcl1))]); grid
xlabel('\omega (rad/sec)');
ylabel('Phase (deg)');

%Bode grid
bodegrid;


text:
%% PCA feature class
%
% Copyright (c) 2018-present, Mahmoud Afifi
% York University, Canada
% mafifi@eecs.yorku.ca | m.3afifi@gmail.com
%
% This source code is licensed under the license found in the
% LICENSE file in the root directory of this source tree.
% All rights reserved.
%
% Please cite the following work if this program is used:
% Mahmoud Afifi, Brian Price, Scott Cohen, and Michael S. Brown,
% "When color constancy goes wrong: Correcting improperly white-balanced
% images", CVPR 2019.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
classdef PCAFeature
    properties
        weights
        bias
    end
    methods
        function feature = encode(obj,hist)
            feature = (reshape(hist,1,[]) - obj.bias') *obj.weights;
        end
    end
end

author: mahmoudnafifi


text:
function [IDX, maxIdxArray] = Cluster(data, MinPts, epsilon, PtsNumThr, IS_SHOW)
if size(data, 2) ~= 2
    data = data';
end
if size(data, 2) ~= 2
    error('Input for Cluster() is wrong!');
end
IDX = [];
maxIdxArray = [];
if nargin == 4
    IS_SHOW = 0;
end
if size(data, 1) < PtsNumThr   %%%%%% too few points!
    return;
end
[ IDX, isNoise] =DBSCAN(data,epsilon,MinPts);
if IS_SHOW
    figure;
    hold on;
    box on;
    xlabel('X(meter)');
    ylabel('Y(meter)');
    PlotClusterinResult(data, IDX);
    title(['DBSCAN Clustering (\epsilon = ' num2str(epsilon) ', MinPts = ' num2str(MinPts) ')']);
end
ScanData = CalScanData(IDX);
if isempty(ScanData)
    IDX = [];
    maxIdxArray = [];
    return;
end
[maxVal, idxOrder]= max(ScanData(2, :));
if maxVal < PtsNumThr
    return;
end
maxIdxArray = find(IDX == ScanData(1, idxOrder));
end

author: DrGabor

repo: LiDAR

save_path: github-repos/MATLAB/DrGabor-LiDAR


text:
function [U, S, V, info] = truncated_svd(A, p)
% Returns an SVD decomposition of A truncated to rank p.
%
% function [U, S, V, info] = truncated_svd(A, p)
%
% Input: A real matrix A of size mxn and an integer p <= min(m, n).
% Output: An orthonormal matrix U of size mxp, an orthonormal matrix Y of
%         size nxp and a diagonal matrix S of size pxp with nonnegative and
%         decreasing diagonal entries such that USV.' is the best rank p
%         approximation of A according to the Frobenius norm. All real.
%         This function produces an output akin to svds.
%
% The decomposition is obtained by maximizing
%   f(U, V) = .5*norm(U'*A*V, 'fro')^2
% where U, V are orthonormal. Notice that f(U*Q, V*R) = f(U, V) for all
% Q, R orthogonal pxp matrices. Hence, only the column spaces of U and V
% matter and we may perform the optimization over a product of two
% Grassmannian manifolds.
%
% It is easy to show that maximizing f is equivalent to minimizing g with
%   g(U, V) = min_S norm(U*S*V' - A, 'fro')^2,
% which confirms that we are going for a best low-rank approximation of A.
%
% The inner workings of the Grassmann manifold use the built-in svd
% function of Matlab but only for matrices of size mxp and nxp to
% re-orthonormalize them.
%
% Notice that we are actually chasing a best fixed-rank approximation of a
% matrix, which is best obtained by working directly over a manifold of
% fixed-rank matrices. This is simply an example script to demonstrate some
% functionalities of the toolbox.
%
% The code can be modified to accept a function handle for A(x) = A*x
% instead of a matrix A, which is often useful. This would further require
% a function handle At for the transpose of A, such that At(x) = A.'*x.

% This file is part of Manopt and is copyrighted. See the license file.
%
% Main author: Nicolas Boumal, July 5, 2013
% Contributors:
%
% Change log:
%
%   Aug. 23, 2021 (XJ):
%       Added AD to compute the egrad and the ehess

    % Generate some random data to test the function if none is given.
    if ~exist('A', 'var') || isempty(A)
        A = randn(42, 60);
    end
    if ~exist('p', 'var') || isempty(p)
        p = 5;
    end

    % Retrieve the size of the problem and make sure the requested
    % approximation rank is at most the maximum possible rank.
    [m, n] = size(A);
    assert(p <= min(m, n), 'p must be smaller than the smallest dimension of A.');

    % Define the cost and its derivatives on the Grassmann manifold
    tuple.U = grassmannfactory(m, p);
    tuple.V = grassmannfactory(n, p);
    % All of the code will work just as well if we ignore the invariance
    % property of the cost function indicated above and thus place U and V
    % on the Stiefel manifold (orthonormal matrices) instead of the
    % Grassmann manifold. Working on Stiefel is expected to be slower
    % though, partly because de search space is higher dimensional and
    % partly because the optimizers are not isolated.
    % tuple.U = stiefelfactory(m, p);
    % tuple.V = stiefelfactory(n, p);
    M = productmanifold(tuple);

    % Define a problem structure, specifying the manifold M, the cost
    % function and its derivatives. Here, to demonstrate the rapid
    % prototyping capabilities of Manopt, we directly define the Euclidean
    % gradient and the Euclidean Hessian egrad and ehess instead of the
    % Riemannian gradient and Hessian grad and hess. Manopt will take care
    % of the conversion. This automatic conversion is usually not
    % computationally optimal though, because much of the computations
    % involved in obtaining the gradient could be reused to obtain the
    % Hessian. After the prototyping stage, when efficiency becomes
    % important, it makes sense to define grad and hess rather than egrad
    % an ehess, and to use the caching system (the store structure).
    problem.M = M;
    problem.cost  = @cost;
    problem.egrad = @egrad;
    problem.ehess = @ehess;

    % The functions below make many redundant computations. This
    % performance hit can be alleviated by using the caching system.

    % Cost function
    function f = cost(X)
        U = X.U;
        V = X.V;
        f = -.5*norm(U'*A*V, 'fro')^2;
    end
    % Euclidean gradient of the cost function
    function g = egrad(X)
        U = X.U;
        V = X.V;
        AV = A*V;
        AtU = A'*U;
        g.U = -AV*(AV'*U);
        g.V = -AtU*(AtU'*V);
    end
    % Euclidean Hessian of the cost function
    function h = ehess(X, H)
        U = X.U;
        V = X.V;
        Udot = H.U;
        Vdot = H.V;
        AV = A*V;
        AtU = A'*U;
        AVdot = A*Vdot;
        AtUdot = A'*Udot;
        h.U = -(AVdot*AV'*U + AV*AVdot'*U + AV*AV'*Udot);
        h.V = -(AtUdot*AtU'*V + AtU*AtUdot'*V + AtU*AtU'*Vdot);
    end

    % An alternative way to compute the egrad and the ehess is to use
    % automatic differentiation provided in the deep learning toolbox
    % (slower). Notice that the function norm is not supported for AD so
    % far. Replace norm(...,'fro') with the backup function cnormsqfro
    % described in manoptADhelp
    % problem.cost = @cost_AD;
    %    function f = cost_AD(X)
    %        U = X.U;
    %        V = X.V;
    %        f = -.5*cnormsqfro(U'*A*V);
    %    end
    % call manoptAD to prepare AD for the problem structure
    % problem = manoptAD(problem);

    % Execute some checks on the derivatives for early debugging.
    % These things can be commented out of course.
    % checkgradient(problem);
    % pause;
    % checkhessian(problem);
    % pause;

    % Issue a call to a solver. A random initial guess will be chosen and
    % default options are selected. Here, we specify a maximum trust
    % region radius (which in turn induces an initial trust region radius).
    % Note that this is not required: default values are used if we omit
    % this. The diameter of the manifold scales like sqrt(2*p), hence the
    % form of our (empirical) choice.
    options.Delta_bar = 4*sqrt(2*p);
    [X, Xcost, info] = trustregions(problem, [], options); %#ok<ASGLU>
    U = X.U;
    V = X.V;

    % Finish the job by rotating U and V such that the middle matrix S can
    % be diagonal with nonnegative, decreasing entries. This requires a
    % small svd of size pxp.
    Spp = U'*A*V;
    [Upp, Spp, Vpp] = svd(Spp);
    U = U*Upp;
    S = Spp;
    V = V*Vpp;

    % For our information, Manopt can also compute the spectrum of the
    % Riemannian Hessian on the tangent space at (any) X. Computing the
    % spectrum at the solution gives us some idea of the conditioning of
    % the problem. If we were to implement a preconditioner for the
    % Hessian, this would also inform us on its performance.
    %
    % Notice that if the optimization is performed on a product of Stiefel
    % manifolds instead of a product of Grassmannians, the double
    % invariance under the orthogonal group O(p) will appear as twice
    % p*(p-1)/2, thus p*(p-1) zero eigenvalues in the spectrum of the
    % Hessian. This means that the minimizers are not isolated, which
    % typically hinders convergence of second order algorithms.
    if M.dim() < 512
        evs = hessianspectrum(problem, X);
        stairs(sort(evs));
        title(['Eigenvalues of the Hessian of the cost function ' ...
               'at the solution']);
    end

end

author: NicolasBoumal

repo: manopt