text:
classdef TestGeneralTwoRankSequentialLaminate < handle

    properties (Access = private)
      fractionVolume
      directions
      lamParams
      stiffTensor
      weakTensor
      Rank2Ch
      SeqLamCh
    end

    methods (Access = public)

        function obj = TestGeneralTwoRankSequentialLaminate()
            obj.init()
            obj.computeTwoRankSequentialLaminate()
            obj.computeGeneralTwoRankSequentialLaminate()
        end

        function hasPassed = hasPassed(obj)
            RankTwoCh  = obj.Rank2Ch;
            SqCh = obj.SeqLamCh.getValue();
            hasPassed = norm(RankTwoCh - SqCh)/norm(SqCh) > 1e-6;
        end

    end

    methods (Access = private)

        function init(obj)
            obj.fractionVolume = 0.8000;
            obj.lamParams = [1 0];
            obj.loadLaminateDirections()
            obj.createStiffAndWeakTensors()
        end

        function loadLaminateDirections(obj)
            d1 = [rand(1) rand(1)  0];
            d2 = [1     3     0];
            obj.directions{1} = obj.createDirection(d1);
            obj.directions{2} = obj.createDirection(d2);
        end

        function createStiffAndWeakTensors(obj)
            epsilon = 1.0000e-03;
            E1  = 1;
            nu1 = 1/3;
            E0  = epsilon*E1;
            nu0 = 1/3;
            obj.stiffTensor = IsotropicConstitutiveTensor(E1,nu1);
            obj.weakTensor  = IsotropicConstitutiveTensor(E0,nu0);
        end

        function computeTwoRankSequentialLaminate(obj)
            mi    = obj.lamParams;
            dir   = obj.directions;
            theta = obj.fractionVolume;
            C1    = obj.stiffTensor.getValue();
            C0    = obj.weakTensor.getValue();
            mu    = obj.stiffTensor.getMu();
            lambda2D = obj.stiffTensor.getLambda2D();
            homogenizer = RankTwoLaminateHomogenizer(C1,C0,dir,mi,theta,lambda2D,mu);
            obj.Rank2Ch = homogenizer.getTensor;
        end

        function computeGeneralTwoRankSequentialLaminate(obj)
            C0       = obj.weakTensor;
            C1       = obj.stiffTensor;
            mi       = obj.lamParams;
            dir      = obj.directions;
            Theta    = obj.fractionVolume;
            SeqHomog      = VoigtPlaneStressHomogHomogenizer(C0,C1,dir,mi,Theta);
            obj.SeqLamCh  = SeqHomog.getPlaneStressHomogenizedTensor();
        end

    end

    methods (Access = private, Static)

        function dir = createDirection(d)
            dir = Vector3D;
            dir.setValue(d);
            dir.normalize();
        end

    end

end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function obj = startfd(org)
    % This is the starting code for the fractal dimension, which manages the different codes.
    % Francesco Pacchiani 1/2000
    %
    %
    % disp('fractal/codes/startfd.m');
    %
    %
    % turned into function by Celso G Reyes 2017

    ZG=ZmapGlobal.Data; % used by get_zmap_globals
    switch (org)

        case 1 	% Call from TIMEPLOT, FDSPHERE, DORAND

            range = 1;
            radm = [];
            rasm = [];
            obj=fractal()
            obj.fdparain(obj.gobut);

        case 2	% Call from FDPARAIN

            dtokm = 1;
            pdc3;

        case 3	% Call from TIMEPLOT
            %
            % Default values
            %
            numran = 1000;				% # of points in random catalog
            distr = 1;
            stdx = 0.5;
            stdy = 0.5;
            stdz = 1;
            long1 = min(obj.catalog.Longitude);
            long2 = max(obj.catalog.Longitude);
            lati1 = min(obj.catalog.Latitude);
            lati2 = max(obj.catalog.Latitude);
            dept1 = min(abs(obj.catalog.Depth));
            dept2 = max(abs(obj.catalog.Depth));

            obj.E = obj.catalog;
            obj.randomcat();

        case 4	% Call from TIMEPLOT

            nev = 600;
            inc = 100;
            fdtimin;

        case 5  % Call from VIEW_DV

            range = 1;
            radm = [];
            rasm = [];
            crclparain;

    end

end

author: CelsoReyes


text:
classdef (Abstract) Rx  < adi.common.RxTx & matlab.system.mixin.SampleTime
    % Rx: Common shared functions between receiver classes
    properties(Constant, Hidden, Logical)
        %EnableCyclicBuffers Enable Cyclic Buffers
        %   Not used for RX
        EnableCyclicBuffers = false;
    end

    methods (Hidden, Access = protected)

        function sts = getSampleTimeImpl(obj)
            sts = createSampleTime(obj,'Type','Discrete',...
                'SampleTime',obj.SamplesPerFrame/obj.SamplingRate);
        end

    end

    methods (Access=protected)

        function numOut = getNumOutputsImpl(~)
            numOut = 2;
        end

        function names = getOutputNamesImpl(~)
            % Return output port names for System block
            names = {'data','valid'};
        end

        function sizes = getOutputSizeImpl(obj)
            % Return size for each output port
            sizes = {[obj.SamplesPerFrame,obj.channelCount],[1,1]};
        end

        function types = getOutputDataTypeImpl(~)
            % Return data type for each output port
            types = ["int16","logical"];
        end

        function complexities = isOutputComplexImpl(obj)
            % Return true for each output port with complex data
            complexities = {obj.ComplexData,false};
        end

        function fixed = isOutputFixedSizeImpl(~)
            % Return true for each output port with fixed size
            fixed = {true,true};
        end
    end

    methods (Hidden, Access = protected)

        function [data,valid] = stepImpl(obj)
            % [data,valid] = rx() returns data received from the radio
            % hardware associated with the receiver System object, rx.
            % The output 'valid' indicates whether the object has received
            % data from the radio hardware. The first valid data frame can
            % contain transient values, resulting in packets containing
            % undefined data.
            %
            % The output 'data' will be an [NxM] vector where N is
            % 'SamplesPerFrame' and M is the number of elements in
            % 'EnabledChannels'. 'data' will be complex if the devices
            % assumes complex data operations.

            % Get the data
            if obj.ComplexData
                kd = 1;
                ce = length(obj.EnabledChannels);
                [dataRAW, valid] = getData(obj);
                data = complex(zeros(obj.SamplesPerFrame,ce));
                for k = 1:ce
                    data(:,k) = complex(dataRAW(kd,:),dataRAW(kd+1,:)).';
                    kd = kd + 2;
                end
            else
                [data, valid] = getData(obj);
                data = data.';
            end

        end

    end

end

author: analogdevicesinc


text:
function y = obliq(t)

% function to compute mean obliquity of the ecliptic in arcseconds
% capitaine et al. (2003), astronomy and astrophysics 412, 567-586,
% expression from eq. (39) with obliquity at j2000.0 taken from
% eq. (37) or table 8

% input

%  t = tdb julian centuries

% output

%  y = mean obliquity of the ecliptic in arcseconds

% ported from NOVAS 3.0

%%%%%%%%%%%%%%%%%%%%%%%

y = (((( - 0.0000000434d0 * t ...
    - 0.000000576d0) * t ...
    + 0.00200340d0) * t ...
    - 0.0001831d0) * t ...
    - 46.836769d0) * t + 84381.406d0;

author: goGPS-Project


text:
function [X, info] = IRirn(A, b, varargin)
% IRirn Least squares solver with 1-norm penalization term
%
% options  = IRirn('defaults')
% [X,info] = IRirn(A,b)
% [X,info] = IRirn(A,b,K)
% [X,info] = IRirn(A,b,options)
% [X,info] = IRirn(A,b,K,options)
%
% Iteratively reweighted norm algorithm for computing a 1-norm penalized
% solution.
%
% IRirn is a simplified driver for IRrestart, which uses an inner-outer
% iteration scheme. Semi-convergent or hybrid iterative solvers are used
% in the inner iterations, using one of the iterative methods in IRtools
% (e.g., IRhybrid_lsqr). In the case of IRirn, the 1-norm penalization
% is updated at each outer iteration.
%
% The regularization parameter and number of inner iterations influence
% the behavior and convergence of the outer iterations.
%
% With 'defaults' as input returns the default options.  Otherwise outputs
% the iterates specified in K, using max(K) as MaxIter, and using all other
% default options.  With options as input: uses the user-specified options
% and all the other default options.
%
% Inputs:
%  A : either (a) a full or sparse matrix
%             (b) a matrix object that performs the matrix*vector operation
%             (c) user-defined function handle
%  b : right-hand side vector
%  K : (optional) integer vector that specifies which (total) iterates are
%      returned in X; the maximum number of iterations is assumed to be max(K)
%      [ positive integer | vector of positive components ]
%  options : structure with the following fields (optional)
%      x0            - initial guess for the iterations; default = zero vector
%                      [ array | {'none'} ]
%      MaxIterIn     - maximum number of inner iterations
%      MaxIterOut    - maximum number of outer iterations
%      x_true        - true solution; allows us to returns error norms with
%                      respect to x_true at each iteration
%                      [ array | {'none'} ]
%      RegParam      - a value or a method to find the regularization used
%                      in the inner iterations:
%                      [ non-negative scalar | {'gcv'} | 'discrep' ]
%                      This also determines which stopping rule is used for
%                      the inner iterations.
%                      If 'gcv' is chosen, the inner iteration is stopped
%                        when the GCV function minimum stabilizes or increases
%                        within a certain window of iterations (see 'stopGCV',
%                        'FlatTol' and 'MinTol').
%                      If 'discrep' is chosen, and NoiseLevel is provided,
%                        then the discrepancy principle is used as stopping
%                        criterion (see 'NoiseLevel' and 'eta').
%      stopGCV       - stopping criterion for the inner iterations when
%                      GCV is used
%                      [ GCVvalues | {'resflat'} ]
%      FlatTol       - tolerance for detecting flatness (stabilization)
%                      in the GCV function as a stopping criterion for the
%                      inner iterations
%                      [ {10^-6} | non-negative scalar ]
%      MinTol        - window of iterations: if the GCV minimum continues
%                      to increase over this window, then the inner
%                      iterations are stopped
%                      [ {3} | positive integer ]
%      RegMatrix     - priorconditioner for the inner iterations
%                      [ {'identity'} | square nonsingular matrix |
%                        function handle ]
%      NoiseLevel    - norm of noise in rhs divided by norm of rhs (must be
%                      assigned if RegParam is 'discrep')
%                      [ {'none'} | nonnegative scalar ]
%      eta           - safety factor for the discrepancy principle
%                      [ {1.01} | scalar greater than (and close to) 1 ]
%      RegParam0     - first regularization parameter, used only on the
%                      very first iteration (needed if RegParam is 'discrep')
%                      [ {1} | positive scalar ]
%      stopOut       - stopping criterion for the outer iterations;
%                      [ {'xstab'} | 'Lxstab' | 'regPstab' ]
%      inSolver      - solver to be employed during the inner iterations
%                      [ 'gmres' | {'lsqr'} | 'fgmres' | 'cgls']
%      adaptConstr   - approximate constraint or regularization to be
%                      incorporated
%                      [ {'sp'} | 'spnn' | 'none' ]
%      nonnegativity - may be used to also impose nonnegativity
%                      (similarly to 'spnn')
%                      [ 'on' | {'off'} ]
%      IterBar       - shows the progress of the outer iterations
%                      [ {'on'} | 'off' ]
%      NoStopIn      - specifies whether the inner iterations should
%                      proceed after a stopping criterion has been satisfied
%                      [ 'on' | {'off'} ]
%      NoStopOut     - specifies whether the outer iterations should
%                      proceed after a stopping criterion has been satisfied
%                      [ 'on' | {'off'} ]
%      verbosity     - switch on or off the "verbosity" of the function
%                      [ {'on'} | 'off' ]
% Note: the options structure can be created using the function IRset.
%
% Outputs:
%   X : computed solutions, stored column-wise (at the iterations listed in K)
%   info: structure with the following fields:
%      its          - number of the last computed iteration
%      saved_iterations - iteration numbers of iterates stored in X
%      StopFlag_in  - string that describes the inner stopping condition:
%                       * Stopping criterion of the inner iterations is
%                         never satisfied
%                       * Stopping criterion is satisfied at least once
%                         during the inner iterations
%      StopFlag_out - string that describes the outer stopping condition;
%                     depending on the inputs it can be one of the following:
%                       * Outer stopping criterion is never satisfied
%                       * Diagonal weighting matrix is numerically zero
%                       * Solution stabilizes
%                       * Transformed solution stabilizes
%                       * Tegularization parameter stabilizes
%      Rnrm     - relative residual norms at each iteration
%      Xnrm     - solution norms at each iteration
%      Enrm     - relative error norms (requires x_true) at each iteration
%      Xout     - approximate solutions at the end of each inner cycle,
%                 stored column-wise
%      itsInOut - 3-column matrix whose the columns store
%                   1. outer iteration count
%                   2. inner iteration count (i.e., for each cycle)
%                   3. total iteration count
%      StopReg  - struct containing information about the solution that
%                 satisfies the stopping criterion.  Fields:
%                   It   : iteration where the stopping criterion is satisfied
%                   X    : solution satisfying the stopping criterion
%                   Enrm : the corresponding relative error (requires x_true)
%      BestReg  - struct containing information about the solution that
%                 minimizes Enrm (requires x_true). Fields:
%                   It   : iteration where the minimum is attained
%                   X    : best solution
%                   Enrm : best relative error
%
% See also: IRell1, IRhtv, IRhybrid_fgmres, IRrestart, IRget, IRset

% Silvia Gazzola, University of Bath
% Per Christian Hansen, Technical University of Denmark
% James G. Nagy, Emory University
% April, 2018.

% This file is part of the IR Tools package and is distributed under the
% 3-Clause BSD License. A separate license file should be provided as part
% of the package.

% Set default values for options.
defaultopt = struct('x0', 'none', 'MaxIterIn', 30 , 'MaxIterOut', 20 , ...
    'RegParam', 'gcv', 'stopGCV', 'resflat', ...
    'resflatTol', 0.05, 'GCVflatTol', 10^-6, 'GCVminTol', 3,...
    'x_true', 'none', 'IterBar', 'on', 'NoStop', 'off', 'NoStopIn', 'off',...
    'NoStopOut', 'off', 'stopOut', 'xstab', 'stabOut', 1e-6, 'thr0', 1e-10, ...
    'NoiseLevel', 'none', 'eta', 1.01, 'RegParam0', 1, 'inSolver', 'lsqr', ...
    'adaptConstr', 'sp', 'nonnegativity', 'off', 'verbosity', 'off',...
    'SparsityTrans', 'none', 'wname', 'db1', 'wlevels', 2, 'warmrestart', 'on');

% If input is 'defaults,' return the default options in X.
if nargin==1 && nargout <= 1 && isequal(A,'defaults')
    X = defaultopt;
    return;
end

% Check for acceptable number of optional input arguments.
switch length(varargin)
    case 0
        K = []; options = [];
    case 1
        if isa(varargin{1}, 'double')
            K = varargin{1}; options = [];
        else
            K = []; options = varargin{1};
        end
    case 2
        if isa(varargin{1}, 'double')
            K = varargin{1}; options = varargin{2};
        else
            K = varargin{2}; options = varargin{1};
        end
    otherwise
        error('Too many input parameters')
end

if isempty(options)
    options = defaultopt;
end

options = IRset(defaultopt, options);
nn       = IRget(options, 'nonnegativity', [], 'fast');
inSolver = IRget(options, 'inSolver',      [], 'fast');

if strcmp(nn, 'on')
    nn = 1;
    options.adaptConstr = 'spnn';
else
    nn = 0;
end

if strcmp(inSolver, 'fgmres') && ~nn
    warning(['With options.inSolver = ''fgmres'' and options.nonnegativity = ''off'' ',...
        'it is more appropriate to use IRhybrid_fgmeres than to use IRirn.'])
end

% Call IRrestart with the specified options.
% Note that nonnegativity is specified via options.adaptConstr.
options = rmfield(options, 'nonnegativity');
[X, info] = IRrestart(A, b, K, options);

repo: IRtools


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

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

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

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

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

ubarp = repmat(ubarp',n_x,1);
vbarp = repmat(vbarp',n_x,1);

switch i

case 0

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

case 1 % logsigmau

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

case 2 % logthetau

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

case 3 % logsigmav

K=0;

case 4 % logthetav

K=0;

case 5 % a1

K=(-1).*dt.*exp(1).^(logsigmau+(-2).*logthetau+(-1/2).*exp(1).^((-1).* ...
  logthetau).*(x+(-1).*xp).^2).*((-1).*exp(1).^logthetau+(x+(-1).*xp).^2); ...

case 6 % a2

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

otherwise

        K = zeros(n_x, n_xp);
end

if K == 0

    K = zeros(n_x, n_xp);

end

end

author: maziarraissi

repo: HPM

save_path: github-repos/MATLAB/maziarraissi-HPM


text:
% Chapter 4: Convex optimization problems
%
%  chebyshev_center_2D.m       - Section 4.3.1: Compute and display the Chebyshev center of a 2D polyhedron
%  chebyshev_center.m          - Section 4.3.1: Compute the Chebyshev center of a polyhedron
%  cantilever_beam_rec.m       - Section 4.5.4: Design of a cantilever beam: recursive formulation (GP)
%  frob_norm_diag_scaling.m    - Section 4.5.4: Frobenius norm diagonal scaling (GP)
%  min_spec_rad_ppl_dynamics.m - Section 4.5.4: Minimum spectral radius via Peron-Frobenius theory (GP)
%  fastest_mixing_MC.m         - Section 4.6.3: Find the fastest mixing Markov chain on a graph
%  ex_4_27.m                   - Exercise 4.27: Matrix fractional minimization using second-order cone programming
%  cantilever_beam.m           - Exercise 4.31: Design of a cantilever beam (GP)
%  ex_4_38.m                   - Exercise 4.38(b): Linear matrix inequalities with one variable
%  ex_4_3.m                    - Exercise 4.3: Solve a simple QP with inequality constraints
%  max_det_psd_completion.m    - Exercise 4.47: Maximum determinant PSD matrix completion
%  channel_capacity.m          - Exercise 4.57: Capacity of a communication channel
%  ex_4_5.m                    - Exercise 4.5: Show the equivalence of 3 convex problem formations
%  logopt_investment.m         - Exercise 4.60: Log-optimal investment strategy
%  cantilever_beam_plot.m      - Plots a cantilever beam as a 3D figure.
help Contents

author: cvxr

repo: CVX

save_path: github-repos/MATLAB/cvxr-CVX


text:
% DEMO
%
% Demonstrate the use of the Support Vector Machine toolbox to distinguish
% examples of Versicolour from Setosa and Virginica varieties of Iris, given
% petal width an length attributes.  The data is taken from the well known
% Iris benchmark [1], available from the UCI Repository of Machine Learning
% Databases (http://www.ics.uci.edu/~mlearn/MLRepository.html).
%
% [1] R. A. Fisher,
%     "The use of multiple measurements in taxonomic problems",
%     Annual Eugenics, 7(2), pp 179-188, 1936.

%
% File        : demo.m
%
% Date        : Saturday 16th September 2000
%
% Author      : Dr Gavin C. Cawley
%
% Description : Test harness for object oriented implementation of Vapnik's
%               linear support vector machine (SVM) [1].
%
% References  : [1] V.N. Vapnik,
%                   "The Nature of Statistical Learning Theory",
%                   Springer-Verlag, New York, ISBN 0-387-94559-8,
%                   1995.
%
% History     : 16/08/1999 - v1.00
%               13/09/2000 - v1.01 minor changes to comments etc
%               13/09/2000 - v1.02 updated to use gateway method svc/train
%               16/09/2000 - v1.10 added xi-alpha estimate of l-o-o error
%               24/11/2000 - v1.11 minor bug-fix for loading iris data under
%                                  all operating systems.
%
% Copyright   : (c) Dr Gavin C. Cawley, November 2000.
%
%    This program is free software; you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation; either version 2 of the License, or
%    (at your option) any later version.
%
%    This program is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with this program; if not, write to the Free Software
%    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%

% start from a clean slate

clf;

clear classes all;

% load some data

fprintf(1,'loading training data...\n');

iris = load('data/iris.txt');

x = iris(:,3:4);
y = 2*(iris(:,5) == 2)-1;

% define useful constants

l = size(x,1);

% display data

fprintf(1,'displaying data...\n');

plot(x(find(y==1),1)',x(find(y==1),2)','bs',x(find(y==-1),1)',x(find(y==-1),2)','go')
axis(axis + [-0.1 +0.1 -0.1 +0.1])
legend('class one','class two',0);
drawnow;

% create tutor

fprintf(1,'creating tutor...\n');

kernel = rbf(0.5);
C      = 1.0;
tutor  = smosvctutor;

% train support vector machine

fprintf(1,'training support vector machine...\n');

net = train(svc, tutor, x, y, C, kernel);

net = fixduplicates(net, x, y);

net2 = strip(net);

% display support vectors

fprintf(1,'displaying support vectors...\n');

sv = getsv(net2);

hold on
plot(sv(:,1)',sv(:,2)','k+');
legend('class one','class two','support vector',0);
hold off

fprintf(1, 'there are %d support vectors\n', getnsv(net2));

% compute correctness

fprintf(1,'correctness = %4.1f%%\n', 100*sum(sign(fwd(net2,x))==y)/l);

% display decision boundary

fprintf(1,'displaying decision boundary...\n');

a     = axis;
[X,Y] = meshgrid(a(1):0.05:a(2),a(3):0.05:a(4));
X2    = [reshape(X,prod(size(X)),1) reshape(Y,prod(size(X)),1)];
z     = fwd(net2,X2);
z     = reshape(z,size(X));

hold on
contour(X,Y,z,[+1 +1],'b');
contour(X,Y,z,[+0 +0],'r');
contour(X,Y,z,[-1 -1],'g');
legend('class one','class two','support vector','class one margin','decision boundary','class two margin',0);
hold off

% highlight estimated leave-one-out errors

e = xialpha(net);

i = find(e);

fprintf(1,'l-o-o correctness >= %4.1f%%\n', 100*correctness(e));

hold on
plot(x(i,1)', x(i,2)', 'rx');
legend('class one','class two','support vector','class one margin','decision boundary','class two margin','l-o-o error',0);
hold off

% all done

fprintf(1,'bye bye...\n');

% bye bye...

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function [D,val] = spm_eeg_inv_check(varargin)
% Checks that the EEG/MEG .mat file structure is loaded properly and that
% the particular inversion of interest has been specified
%
% FORMAT [D,val] = spm_eeg_inv_check(D,[val])
% Input:
% S              - data structure or its filename
% val            - model of interest (usually 1)
% Output:
% D              - data structure
% val            - model of interest D.val
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Jeremie Mattout, Karl Friston
% $Id: spm_eeg_inv_check.m 2861 2009-03-11 18:41:03Z guillaume $

% Check - prompt for file if necessary
%--------------------------------------------------------------------------
if nargin == 0
    [D, sts] = spm_select(1, 'mat', 'Select EEG/MEG mat file');
    if ~sts, D = []; val = 0; return; end
else
    D = varargin{1};
end

D = spm_eeg_load(D);

% Check for inversion
%--------------------------------------------------------------------------
if ~isfield(D,'inv')
    val = 0;
    return
end

% Set val = 1 if only one model
%--------------------------------------------------------------------------
if length(D.inv) == 1
    val   = 1;
    D.val = val;
    return
end

% Check - val
%--------------------------------------------------------------------------
try
    val        = varargin{2};
catch
    try
        val    = D.val;
    catch
        prompt = sprintf('which model (1 to %i)',length(D.inv));
        val    = inputdlg(prompt,'Source reconstruction',1,{'1'});
        val    = eval(val{1});
    end
end
D.val = val;

author: spm


text:
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
theta = linspace(-pi, pi, 75);
[Q2,Q3] = meshgrid(theta, theta);
for i=1:numcols(Q2),
	for j=1:numcols(Q3);
		g = p560.gravload([0 Q2(i,j) Q3(i,j) 0 0 0]);
		g2(i,j) = g(2);
		g3(i,j) = g(3);
	end
end
surfl(Q2, Q3, g2); surfl(Q2, Q3, g3);

author: petercorke

repo: robotics-toolbox-matlab


text:
function [sys,x0,str,ts]=NLSEF_fhan(t,x,u,flag,r,h1)

if flag==0
    sys = [0;0;1;2;0;0;1];
    x0 = [];
    str = [ ];
    ts = [0 0];

elseif flag==3
    sys=-fhan(u(1),u(2),r,h1);

else
    sys=[];
end

author: TianfaYao

repo: ADRC

save_path: github-repos/MATLAB/TianfaYao-ADRC


text:
function tetrahedron_unit_quad_test ( degree_max )

%*****************************************************************************80
%
%% TETRAHEDRON_UNIT_QUAD_TEST tests the rules for the unit tetrahedron.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 August 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer DEGREE_MAX, the maximum total degree of the
%    monomials to check.
%
  dim_num = 3;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TETRAHEDRON_UNIT_QUAD_TEST\n' );
  fprintf ( 1, '  For the unit tetrahedron,\n' );
  fprintf ( 1, '  we approximate monomial integrals with:\n' );
  fprintf ( 1, '  TETRAHEDRON_UNIT_O01,\n' );
  fprintf ( 1, '  TETRAHEDRON_UNIT_O04,\n' );
  fprintf ( 1, '  TETRAHEDRON_UNIT_O08,\n' );
  fprintf ( 1, '  TETRAHEDRON_UNIT_O08b,\n' );
  fprintf ( 1, '  TETRAHEDRON_UNIT_O14,\n' );
  fprintf ( 1, '  TETRAHEDRON_UNIT_O14b,\n' );
  fprintf ( 1, '  TETRAHEDRON_UNIT_O15,\n' );
  fprintf ( 1, '  TETRAHEDRON_UNIT_O15b,\n' );
  fprintf ( 1, '  TETRAHEDRON_UNIT_O24,\n' );

  expon = [];
  more = 0;
  h = 0;
  t = 0;

  while ( 1 )

    [ expon, more, h, t ] = subcomp_next ( degree_max, dim_num, expon, more, h, t );

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Monomial exponents: ' );
    for ( dim = 1 : dim_num )
      fprintf ( 1, '  %2d', expon(dim) );
    end
    fprintf ( 1, '\n' );
    fprintf ( 1, '\n' );

    order = 1;
    [ w, xyz ] = tetrahedron_unit_o01 ( );
    v = monomial_value ( dim_num, order, expon, xyz );
    quad = tetrahedron_unit_volume ( ) *  w' * v;
    fprintf ( 1, '  %6d  %14f\n', order, quad );

    order = 4;
    [ w, xyz ] = tetrahedron_unit_o04 ( );
    v = monomial_value ( dim_num, order, expon, xyz );
    quad = tetrahedron_unit_volume ( ) *  w' * v;
    fprintf ( 1, '  %6d  %14f\n', order, quad );

    order = 8;
    [ w, xyz ] = tetrahedron_unit_o08 ( );
    v = monomial_value ( dim_num, order, expon, xyz );
    quad = tetrahedron_unit_volume ( ) *  w' * v;
    fprintf ( 1, '  %6d  %14f\n', order, quad );

    order = 8;
    [ w, xyz ] = tetrahedron_unit_o08b ( );
    v = monomial_value ( dim_num, order, expon, xyz );
    quad = tetrahedron_unit_volume ( ) *  w' * v;
    fprintf ( 1, '  %6d  %14f\n', order, quad );

    order = 14;
    [ w, xyz ] = tetrahedron_unit_o14 ( );
    v = monomial_value ( dim_num, order, expon, xyz );
    quad = tetrahedron_unit_volume ( ) *  w' * v;
    fprintf ( 1, '  %6d  %14f\n', order, quad );

    order = 14;
    [ w, xyz ] = tetrahedron_unit_o14b ( );
    v = monomial_value ( dim_num, order, expon, xyz );
    quad = tetrahedron_unit_volume ( ) *  w' * v;
    fprintf ( 1, '  %6d  %14f\n', order, quad );

    order = 15;
    [ w, xyz ] = tetrahedron_unit_o15 ( );
    v = monomial_value ( dim_num, order, expon, xyz );
    quad = tetrahedron_unit_volume ( ) *  w' * v;
    fprintf ( 1, '  %6d  %14f\n', order, quad );

    order = 15;
    [ w, xyz ] = tetrahedron_unit_o15b ( );
    v = monomial_value ( dim_num, order, expon, xyz );
    quad = tetrahedron_unit_volume ( ) *  w' * v;
    fprintf ( 1, '  %6d  %14f\n', order, quad );

    order = 24;
    [ w, xyz ] = tetrahedron_unit_o24 ( );
    v = monomial_value ( dim_num, order, expon, xyz );
    quad = tetrahedron_unit_volume ( ) *  w' * v;
    fprintf ( 1, '  %6d  %14f\n', order, quad );

    fprintf ( 1, '\n' );
    quad = tetrahedron_unit_monomial ( expon );
    fprintf ( 1, '   Exact  %14f\n', quad );

    if ( ~more )
      break;
    end

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
%% SOBOL_TEST01 tests EXOR.
%
fprintf ( 1, '\n' );
fprintf ( 1, 'SOBOL_TEST01\n' );
fprintf ( 1, '  EXOR returns the exclusive OR of two integers.\n' );

fprintf ( 1, '\n' );
fprintf ( 1, '     I     J     EXOR(I,J)\n' );
fprintf ( 1, '\n' );

seed = get_seed ( 0 );

for ( test = 1 : 10 )

  [ i, seed ] = i_random ( 0, 100, seed );
  [ j, seed ] = i_random ( 0, 100, seed );
  k = exor ( i, j );

  fprintf ( 1, '%6d %6d %6d\n', i, j, k );

end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function value = csign2 ( z1, z2 )

%*****************************************************************************80
%
%% CSIGN2 is a complex transfer-of-sign function.
%
%  Discussion:
%
%    The L2 norm is used.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 April 2006
%
%  Author:
%
%    MATLAB version by John Burkardt
%
%  Parameters:
%
%    Input, complex Z1, Z2, the arguments.
%
%    Output, complex VALUE,  a complex value, with the magnitude of
%    Z1, and the argument of Z2.
%
  if ( cabs2 ( z2 ) == 0.0 )
    value = 0.0;
  else
    value = cabs2 ( z1 ) * ( z2 / cabs2 ( z2 ) );
  end

  return
end


text:
classdef SOP_F23 < PROBLEM
% <single> <real> <expensive/none>
% Shekel's family

%------------------------------- Reference --------------------------------
% X. Yao, Y. Liu, and G. Lin, Evolutionary programming made faster, IEEE
% Transactions on Evolutionary Computation, 1999, 3(2): 82-102.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    methods
        %% Default settings of the problem
        function Setting(obj)
            obj.M = 1;
            obj.D = 4;
            obj.lower    = zeros(1,obj.D);
            obj.upper    = zeros(1,obj.D) + 10;
            obj.encoding = ones(1,obj.D);
        end
        %% Calculate objective values
        function PopObj = CalObj(obj,PopDec)
            a = [4 4 4 4;1 1 1 1;8 8 8 8;6 6 6 6;3 7 3 7;2 9 2 9;5 5 3 3;8 1 8 1;6 2 6 2;7 3.6 7 3.6];
            c = [0.1;0.2;0.2;0.4;0.4;0.6;0.3;0.7;0.5;0.5];
            PopObj = zeros(size(PopDec,1),1);
            for i = 1 : size(PopDec,1)
                PopObj(i) = -sum(1./(sum((repmat(PopDec(i,:),10,1)-a).^2,2)+c));
            end
        end
        %% Generate the minimum objective value
        function R = GetOptimum(obj,N)
            R = -10.54;
        end
    end
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
%% Copyright (C) 2014, 2016-2019, 2022 Colin B. Macdonald
%%
%% This file is part of OctSymPy.
%%
%% OctSymPy is free software; you can redistribute it and/or modify
%% it under the terms of the GNU General Public License as published
%% by the Free Software Foundation; either version 3 of the License,
%% or (at your option) any later version.
%%
%% This software is distributed in the hope that it will be useful,
%% but WITHOUT ANY WARRANTY; without even the implied warranty
%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
%% the GNU General Public License for more details.
%%
%% You should have received a copy of the GNU General Public
%% License along with this software; see the file COPYING.
%% If not, see <http://www.gnu.org/licenses/>.

%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @deftypemethod  @@sym {@var{e} =} factor (@var{n})
%% @deftypemethodx @@sym {[@var{p}, @var{m}] =} factor (@var{n})
%% @deftypemethodx @@sym {@var{g} =} factor (@var{f})
%% @deftypemethodx @@sym {@var{g} =} factor (@var{f}, @var{x})
%% @deftypemethodx @@sym {@var{g} =} factor (@var{f}, @var{x}, @var{y}, @dots{})
%% Factor a symbolic polynomial or integer.
%%
%% A symbolic integer @var{n} can be factored:
%% @example
%% @group
%% e = factor(sym(28152))
%%   @result{} e = (sym)
%%         1  3   1  2
%%       17 ⋅2 ⋅23 ⋅3
%% @end group
%% @end example
%%
%% However, if you want to do anything other than just look at the result,
%% you probably want:
%% @example
%% @group
%% [p, m] = factor(sym(28152))
%%   @result{} p = (sym) [2  3  17  23]  (1×4 matrix)
%%   @result{} m = (sym) [3  2  1  1]  (1×4 matrix)
%% prod(p.^m)
%%   @result{} (sym) 28152
%% @end group
%% @end example
%%
%% An example of factoring a polynomial:
%% @example
%% @group
%% syms x
%% factor(x^2 + 7*x + 12)
%%   @result{} (sym) (x + 3)⋅(x + 4)
%% @end group
%% @end example
%%
%% When the expression @var{f} depends on multiple variables,
%% the second argument @var{x} effects what is factored:
%% @example
%% @group
%% syms x y
%% f = expand((x+3)*(x+4)*(y+5)*(y+6));
%% factor(f)
%%   @result{} (sym) (x + 3)⋅(x + 4)⋅(y + 5)⋅(y + 6)
%% factor(f, x, y)
%%   @result{} (sym) (x + 3)⋅(x + 4)⋅(y + 5)⋅(y + 6)
%% factor(f, x)
%%   @result{} (sym)
%%                       ⎛ 2            ⎞
%%       (x + 3)⋅(x + 4)⋅⎝y  + 11⋅y + 30⎠
%% factor(f, y)
%%   @result{} (sym)
%%                       ⎛ 2           ⎞
%%       (y + 5)⋅(y + 6)⋅⎝x  + 7⋅x + 12⎠
%% @end group
%% @end example
%%
%% Passing input @var{x} can be useful if your expression @var{f} might
%% be a constant and you wish to avoid factoring it as an integer:
%% @example
%% @group
%% f = sym(42);    % i.e., a degree-zero polynomial
%% factor(f)       % no, don't want this
%%   @result{} (sym)
%%        1  1  1
%%       2 ⋅3 ⋅7
%% factor(f, x)
%%   @result{} (sym) 42
%% @end group
%% @end example
%%
%% @seealso{@@sym/expand}
%% @end deftypemethod

function [p, m] = factor(f, varargin)

  f = sym(f);
  for i = 1:length(varargin)
    varargin{i} = sym(varargin{i});
  end

  if ((nargin > 1) || (~isempty (findsymbols (f))))
    %% have symbols, do polynomial factorization

    if (nargout > 1)
      print_usage ();
    end

    p = pycall_sympy__ ('return factor(*_ins, deep=True)', f, varargin{:});

  else
    %% no symbols: we are doing integer factorization

    if (~isscalar(f))
      error ('factor: integer prime factoring is only supported for scalar input')
    end

    if (nargout <= 1)
      % this is rather fragile, as noted in docs
      p = pycall_sympy__ ('return factorint(_ins[0], visual=True),', f);
    else
      cmd = { 'd = factorint(_ins[0], visual=False)'
              'num = len(d.keys())'
              'sk = sorted(d.keys())'
              'p = sp.Matrix(1, num, sk)'
              'm = sp.Matrix(1, num, lambda i,j: d[sk[j]])'
              'return (p, m)' };
      [p, m] = pycall_sympy__ (cmd, f);
    end

  end
end

%!test
%! % n = 152862;
%! % [p,m] = factor(n);  % only works on Octave, no Matlab as of 2014a
%! n = 330;  % so we use an output without repeated factors
%! p = factor(n); m = ones(size(p));
%! [ps,ms] = factor(sym(n));
%! assert (isequal (p, ps))
%! assert (isequal (m, ms))

%!test
%! n = sym(2)^4*13;
%! [p,m] = factor(n);
%! assert (isequal (p, [2 13]))
%! assert (isequal (m, [4 1]))

%!test syms x
%! assert( logical (factor(x^2 + 6*x + 5) == (x+5)*(x+1)))

%!test
%! syms x
%! f = [ x^4/2 + 5*x^3/12 - x^2/3     x^2 - 1      10];
%! g = [ x^2*(2*x - 1)*(3*x + 4)/12   (x+1)*(x-1)  10];
%! assert (isequal (factor(f), g))

%!test
%! % "fragile form" works
%! A = factor(sym(124));
%! B = strtrim(disp(A, 'flat'));
%! assert (strcmp (B, '2**2*31**1'))

%!error [p, m] = factor(sym('x'));
%!error [p, m] = factor(sym(42), sym('x'));

%!test
%! % if polynomial happens to be a constant, don't attempt integer
%! % factorization if a variable is specified
%! f = sym(42);
%! q = factor(f, sym('x'));
%! assert (isequal (f, q));

repo: octsympy


text:
function [xL,xR] = click_stereo(NUMBER_OF_POINTS,IL,IR,R,T,fc_right,cc_right,kc_right,alpha_c_right,fc_left,cc_left,kc_left,alpha_c_left);

figure(1);
image(IL);

figure(2);
image(IR);

[ny,nx] = size(IL);

xL = [];
xR = [];

for kk = 1:NUMBER_OF_POINTS,

    figure(1);
    hold on;
    x = ginput(1);
    plot(x(1),x(2),'g.');
    hold off;
    x = x'-1;

    xL = [xL x];

    [epipole] = compute_epipole(x,R,T,fc_right,cc_right,kc_right,alpha_c_right,fc_left,cc_left,kc_left,alpha_c_left);

    figure(2);
    hold on;
    h = plot(epipole(1,:)+1,epipole(2,:)+1,'r.','markersize',1);
    hold off;

    x2 = ginput(1);
    x2 = x2' - 1;

    NN = size(epipole,2);
    d = sum((epipole - repmat(x2,1,NN)).^2);
    [junk,indmin] = min(d);

    x2 = epipole(:,indmin);

    xR = [xR x2];

    delete(h);

    figure(2);
    hold on;
    plot(x2(1)+1,x2(2)+1,'g.');
    drawnow;
    hold off;

end;

repo: ekfmonoslam


text:
clear all; close all;
figure(1)
% underdetermined
n=20; m=100
A=rand(n,m); b=rand(n,1);

cvx_begin;
variable x2(m)
minimize( norm(x2,2) );
subject to
A*x2 == b;
cvx_end;

cvx_begin;
variable x1(m)
minimize( norm(x1,1) );
subject to
A*x1 == b;
cvx_end;

subplot(3,1,1), bar(x2,'FaceColor',[.6 .6 .6],'EdgeColor','k')
subplot(3,1,2), bar(x1,'FaceColor',[.6 .6 .6],'EdgeColor','k')
subplot(3,2,5), hist(x2,40)
subplot(3,2,6), hist(x1,40)

subplot(3,1,1), axis([0 100 -.2 .2]), subplot(3,1,2), axis([0 100 -.4 .4])
subplot(3,2,5), axis([-.15 .15 0 82]), set(gca,'Ytick',[0 40 80],'Xtick',[-0.1 0 0.1])
h = findobj(gca,'Type','patch'); h.FaceColor = [0.6 0.6 0.6]; h.EdgeColor = 'k';
subplot(3,2,6), axis([-.15 .15 0 82]), set(gca,'Ytick',[0 40 80],'Xtick',[-0.1 0 0.1])
h = findobj(gca,'Type','patch'); h.FaceColor = [0.6 0.6 0.6]; h.EdgeColor = 'k';

%%
clear A
clear b
clear x
figure(2)

% overdetermined
n=500; m=100;
A=rand(n,m);
b=rand(n,1);
xdag=pinv(A)*b;

lam=[0 0.1 0.5];
for j=1:3

    cvx_begin;
    variable x(m)
    minimize( norm(A*x-b,2) + lam(j)*norm(x,1) );
    cvx_end;

    subplot(4,1,j),bar(x,'FaceColor',[.6 .6 .6],'EdgeColor','k')
    subplot(4,3,9+j), hist(x,20)
end

for j=1:3

    subplot(4,1,j), axis([0 100 -.15 .15])
    subplot(4,3,9+j), axis([-.15 .15 0 80]), set(gca,'Ytick',[0 40 80])
    h = findobj(gca,'Type','patch');
    h.FaceColor = [0.6 0.6 0.6];
    h.EdgeColor = 'k';
end

%%
% matrix overdetermined system

clear A
clear b
clear x
figure(3)

% overdetermined
n=300; m=60; p=20;
A=rand(n,m); b=rand(n,p);

lam=[0 0.1];
for j=1:2
    cvx_begin;
    variable x(m,p)
    minimize(norm(A*x-b,2) + lam(j)*norm(x,1));
    cvx_end;
    subplot(2,1,j), pcolor(x.'), colormap(hot), colorbar
end

%%
subplot(2,1,1), set(gca,'Fontsize',[15],'Xtick',[1 20 40 60],'Ytick',[1 10 20])
subplot(2,1,2), set(gca,'Fontsize',[15],'Xtick',[1 20 40 60],'Ytick',[1 10 20])

author: dynamicslab


text:
function newPrevPermute = addDimPrevPermute(prevPermute, dimLabel, dimNumber)
    newPrevPermute = prevPermute;

    for iDim = 1:size(prevPermute, 2)
        dimensionNumber = prevPermute{1, iDim};
        if(dimensionNumber >= dimNumber)
            newPrevPermute{1, iDim} = dimensionNumber + 1;
        end
    end
    newIndex = size(prevPermute, 2) + 1;
    newPrevPermute{1, newIndex} = dimNumber;
    newPrevPermute{2, newIndex} = dimLabel;
end

author: CIC-methods

repo: FID-A

save_path: github-repos/MATLAB/CIC-methods-FID-A


text:
% Performs fast detrended fluctuation analysis on a nonstationary input signal to
% obtain an estimate for the scaling exponent.
%
% Useage:
% [alpha, intervals, flucts] = fastdfa(x)
% [alpha, intervals, flucts] = fastdfa(x, intervals)
% Inputs
%    x          - input signal: must be a column vector
% Optional inputs
%    intervals  - List of sample interval widths at each scale
%                 (If not specified, then a binary subdivision is constructed)
%
% Outputs:
%    alpha      - Estimated scaling exponent
%    intervals  - List of sample interval widths at each scale
%    flucts     - List of fluctuation amplitudes at each scale
%
% (c) 2006 Max Little. If you use this code, please cite:
% M. Little, P. McSharry, I. Moroz, S. Roberts (2006),
% Nonlinear, biophysically-informed speech pathology detection
% in Proceedings of ICASSP 2006, IEEE Publishers: Toulouse, France.
%

function [alpha, intervals, flucts] = ML_fastdfa(x, varargin)

[xpts, ypts] = ML_fastdfa_core(x, varargin{:});

% Sort the intervals, and produce a log-log straight line fit
datapts   = sortrows([xpts, ypts],1);
intervals = datapts(:,1);
flucts    = datapts(:,2);

coeffs    = polyfit(log10(xpts), log10(ypts), 1);
alpha     = coeffs(1);

end

author: benfulcher

repo: hctsa

save_path: github-repos/MATLAB/benfulcher-hctsa


text:
function PopDec=rGA(fhandle,Problem)
% real-parameter genetic algorithm to find minimal objective value

%--------------------------------------------------------------------------
% This function is written by Youwei He (email: 1554748356@qq.com)

% the number of design variables
D = Problem.D;
% population size of GA
GAPopulationSize = 10*D;
% Generation of GA
GAGeneration = 100;
obj_max=Inf;
% the first GA generation, randomly generated
Offspring = repmat(Problem.upper-Problem.lower,GAPopulationSize,1).*...
            UniformPoint(GAPopulationSize,D,'Latin')+repmat(Problem.lower,GAPopulationSize,1);
% the GA process for optimizing the objective function
for gen = 1 :  GAGeneration
    obj_Offspring = feval(fhandle, Offspring);
    [~,index] = sort(obj_Offspring,'ascend');
    if obj_Offspring(index(1)) < obj_max
        Best = Offspring(index(1),:);
        obj_max   = obj_Offspring(index(1));
    end
    Parent    = Offspring(index(1:ceil(GAPopulationSize/2)),:);
    Offspring = [OperatorGA(Problem,Parent(TournamentSelection(2,size(Parent,1), ...
        obj_Offspring(index(1:ceil(GAPopulationSize/2)))),:));OperatorGA(Problem,Parent,{0.9,2,1/D,20})];
end
PopDec = Best;
end


text:
function isgn = r8vec_compare ( n, a1, a2 )

%*****************************************************************************80
%
%% R8VEC_COMPARE compares two R8VEC's.
%
%  Discussion:
%
%    The lexicographic ordering is used.
%
%  Example:
%
%    Input:
%
%      A1 = ( 2.0, 6.0, 2.0 )
%      A2 = ( 2.0, 8.0, 12.0 )
%
%    Output:
%
%      ISGN = -1
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 April 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of entries in the vectors.
%
%    Input, real A1(N), A2(N), the vectors to be compared.
%
%    Output, integer ISGN, the results of the comparison:
%    -1, A1 < A2,
%     0, A1 = A2,
%    +1, A1 > A2.
%
  isgn = 0;

  k = 1;

  while ( k <= n )

    if ( a1(k) < a2(k) )
      isgn = -1;
      return
    elseif ( a2(k) < a1(k) )
      isgn = +1;
      return
    end

    k = k + 1;

  end

  return
end


text:
function [LL,lls]=normloglik(x,mu,sigma2)
% Log-likelihood for the normal distribution
%
% USAGE:
%   [LL,LLS]=normloglik(X,MU,SIGMA2)
%
% INPUTS:
%   X      - Normal random variables, either scalar or column vector
%   MU     - Mean of X, either scalar or size(x)
%   SIGMA2 - Variance of X, either scalar or size(x)
%
% OUTPUTS:
%   LL    - Log-likelihood evaluated at X
%   LLS   - Vector of log-likelihoods corresponding to X
%
% COMMENTS:
%
% REFERENCES:
%   [1] Cassella and Berger (1990) 'Statistical Interence'
%
% See also NORMCDF, NORMINV, NORMRND, NORMPDF

% Copyright: Kevin Sheppard
% kevin.sheppard@economics.ox.ac.uk
% Revision: 1    Date: 9/1/2005

[T,K]=size(x);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Input Checking
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if K~=1
    error('x must be a column vector');
end

if nargin==1
    sigma2=ones(T,K);
elseif nargin==2
    %Check mu's conformability
    if length(mu)~=1 && ~all(size(mu)==[T K])
        error('mu must be either a scalar or the same size as X');
    end
    x=x-mu;
    sigma2=ones(T,K);
elseif nargin==3
    if length(mu)~=1 && ~all(size(mu)==[T K])
        error('mu must be either a scalar or the same size as X');
    end
    if any(sigma2<=0)
        error('sigma2 must contain only positive elements')
    end
    if length(sigma2)==1
        sigma2=sigma2*ones(T,K);
    elseif size(sigma2,1)~=T || size(sigma2,2)~=1
        error('sigma2 must be a scalar or a vector with the same dimensions as x');
    end
    x=x-mu;
else
    error('Only 1 to 3 inputs supported');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Input Checking
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargout>1
%Compute the individual log likelihoods if needed
    lls = -0.5*(log(2*pi) + log(sigma2) + x.^2./sigma2);
    % Use these to comput the LL
    LL = sum(lls);
else
    %Compute the log likelihood
    LL  =  -0.5 * (sum(log(sigma2)) + sum((x.^2)./sigma2)  +  T*log(2*pi));
end

author: bashtage

repo: mfe-toolbox


text:
% SP_TO_VTK: Export to VTK format for plotting.
%
%  sp_to_vtk (u, space, geometry, npts, filename, fieldname, [options], [lambda_lame, mu_lame])
%  sp_to_vtk (u, space, geometry, pts, filename, fieldname, [options], [lambda_lame, mu_lame])
%
% INPUT:
%
%     u:           vector of dof weights
%     space:       object representing the space of discrete functions (see sp_scalar)
%     geometry:    geometry structure (see geo_load)
%     npts:        number of points along each parametric direction where to evaluate
%     pts:         cell array with the coordinates along each parametric direction of the points where to evaluate
%     filename:    name of the output file.
%     fieldnames:  how to name the saved variables in the vtk file
%     options:     cell array with the fields to plot
%                   accepted options are 'value' (default), 'gradient',
%                   and for vectors also 'curl', 'divergence', 'stress'
%     lambda_lame: function handle to the first Lame coefficient (only needed to compute 'stress')
%     mu_lame:     function handle for the second Lame coefficient (only needed to compute 'stress')
%
% OUTPUT:
%
%    none
%
% Copyright (C) 2009, 2010 Carlo de Falco
% Copyright (C) 2011, 2012, 2015 Rafael Vazquez
%
%    This program is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.

%    This program is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with this program.  If not, see <http://www.gnu.org/licenses/>.

function sp_to_vtk (u, space, geometry, npts, filename, fieldname, varargin)

  [eu, F] = sp_eval (u, space, geometry, npts, varargin{:});

  msh_to_vtk (F, eu, filename, fieldname);

end

author: rafavzqz

repo: geopdes

save_path: github-repos/MATLAB/rafavzqz-geopdes


text:
function ierror = edge_check ( n_node, n_edge, t )

%*****************************************************************************80
%
%% EDGE_CHECK checks a graph stored by edges.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 January 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer  N_NODE, the number of nodes in the graph.
%    N_NODE must be positive.
%
%    Input, integer N_EDGE, the number of edges in the graph.
%    N_EDGE must be positive.
%
%    Input, integer T(2,N_EDGE), describes the edges of the tree
%    as pairs of nodes.
%
%    Output, integer IERROR, error flag.
%    -1, N_NODE is not positive.
%    -2, N_EDGE is not positive.
%    0, no error.
%    I, edge T(1,I), T(2,I) is illegal.
%
  ierror = 0;

  if ( n_node < 1 )
    ierror = -1;
    return
  end

  if ( n_edge < 1 )
    ierror = -2;
    return
  end
%
%  Every edge must join two legal nodes.
%
  for i = 1 : 2
    for j = 1 : n_edge
      if ( t(i,j) < 1 || n_node < t(i,j) )
        ierror = i;
        return
      end
    end
  end
%
%  Every edge must join distinct nodes.
%
  for j = 1 : n_edge
    if ( t(1,j) == t(2,j) )
      ierror = i;
      return
    end
  end
%
%  Every edge must be distinct.
%
  for j = 1 : n_edge - 1
    for j2 = j + 1 : n_edge
      if ( t(1,j) == t(1,j2) && t(2,j) == t(2,j2) )
        ierror = j2;
        return
      elseif ( t(1,j) == t(2,j2) && t(2,j) == t(1,j2) )
        ierror = j2;
        return
      end
    end
  end

  return
end


text:
%--- help for update_estimated_parameter_names ---
%
%  INTERNAL FUNCTION
%
%

author: jmaih


text:
function [prob,sol,fmin] = qp_prob(varargin)
%QP_PROB  Return an OPTI QP
%
%   prob = qp_prob(no) return a pre-built optiprob of a saved QP.
%
%   [prob,sol,fmin] = qp_prob(no) returns the optimum solution and
%   function eval at the optimum
%
%   no = qp_prob() returns the number of problems available for testing.

%   (C) 2011 Jonathan Currie (IPL)

%Check if just returning no problems
if(nargin < 1)
    prob = 3; sol = []; fmin = [];
    return;
else
    no = varargin{1};
end

%Big switch yard
switch(no)
    case 1
        H = eye(3);
        f = -[2 3 1]';
        A = [1 1 1;3 -2 -3; 1 -3 2];
        b = [1;1;1];
        prob = optiprob('H',H,'f',f,'ineq',A,b);
        sol = [1/3;4/3;-2/3];
        fmin = -2.83333333301227;

    case 2
        H = [1 -1; -1 2];
        f = -[2 6]';
        A = [1 1; -1 2; 2 1];
        b = [2; 2; 3];
        lb = [0;0];
        prob = optiprob('H',H,'f',f,'ineq',A,b,'lb',lb);
        sol = [1/3;4/3];
        fmin = -8.22222220552525;

    case 3
        H = [1 -1; -1 2];
        f = -[2 6]';
        A = [1 1; -1 2; 2 1];
        b = [2; 2; 3];
        Aeq = [1 1.5];
        beq = 2;
        lb = [0;0];
        ub = [10;10];
        prob = optiprob('H',H,'f',f,'ineq',A,b,'eq',Aeq,beq,'bounds',lb,ub);
        sol = [0.34482763667623;1.10344824221585];
        fmin = -6.41379310344827;

    otherwise
        error('Problem not available or not implemented yet');
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
% SoundcardSpectralAnalyser/stop - Stop SoundcardSpectralAnalyser processing
%===============================================================================
function this = stop(this)

    if (~isempty(this.audio_recorder))
        stop(this.audio_recorder);
    end
end

author: Sable

repo: mcbench-benchmarks