text:
function thyme = maze(row,col,pattern)
% usage  thyme = maze(30,45,'c');
% row - number of rows in the maze
% col - number of column in the maze
% pattern - random(r), vertical(v), horizontal(h), checkerboard(c), spiral(s), burst(b)

% Written by Rodney Meyer
% rodney_meyer@yahoo.com
%
% Construct graph system for maze. The graph entities are an id for each
% intersection(id), the physical row(rr) and column(cc) of the
% intersection, membership to a connected region (state), and a link to
% adjacent intersections(ptr_up ptr_down ptr_left ptr_right).
% Prior to "make_pattern" the maze has all of the walls intact and
% there are row*col of unconnected states. After "make_pattern" some of the
% walls are broken down and there is only one connected state for the maze.
% A broken wall(allowed passage) in some direction is signified by a negative
% value of the pointer in that direction. A solid wall(unallowed passage)
% in some direction is signified by a positive value of the pointer in that
% direction. The absolute value of the pointer is the id of the
% intersection in that direction.

rand('state',sum(100*clock))

[cc,rr]=meshgrid(1:col,1:row);
state = reshape([1:row*col],row,col); % state identifies connected regions
id = reshape([1:row*col],row,col); % id identifies intersections of maze

% create pointers to adjacent intersections
ptr_left = zeros(size(id));
ptr_up = zeros(size(id));
ptr_right = zeros(size(id));
ptr_down = zeros(size(id));

ptr_left(:,2:size(id,2)) = id(:,1:size(id,2)-1);
ptr_up(2:size(id,1),:) = id(1:size(id,1)-1,:);
ptr_right(:,1:size(id,2)-1) = id(:,2:size(id,2));
ptr_down(1:size(id,1)-1,:) = id(2:size(id,1),:);

% sort graph entities by id
the_maze = cat(2,reshape(id,row*col,1),reshape(rr,row*col,1),reshape(cc,row*col,1),reshape(state,row*col,1),...
    reshape(ptr_left,row*col,1),reshape(ptr_up,row*col,1),reshape(ptr_right,row*col,1),reshape(ptr_down,row*col,1)  );

the_maze = sortrows(the_maze);

id=the_maze(:,1);
rr=the_maze(:,2);
cc=the_maze(:,3);
state=the_maze(:,4);
ptr_left=the_maze(:,5);
ptr_up=the_maze(:,6);
ptr_right=the_maze(:,7);
ptr_down=the_maze(:,8);
clear the_maze;

% create a random maze
[state, ptr_left, ptr_up, ptr_right, ptr_down]=...
    make_pattern(row,col,pattern,id, rr, cc, state, ptr_left, ptr_up, ptr_right, ptr_down);

% show maze
h=figure('KeyPressFcn',@move_spot,'color','white');
show_maze(row, col, rr, cc, ptr_left, ptr_up, ptr_right, ptr_down,h);

% start play
cursor_pos=[1,1];
current_id=1;
figure(h)
text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color','r');
set(gcf,'Units','normalized');
set(gcf,'position',[0 0 1 .91]);
tic

% keep processing keystrokes until the maze is solved
while ~all(cursor_pos == [col,row])
    waitfor(gcf,'CurrentCharacter')
    set(gcf,'CurrentCharacter','~') % update to another character so repeats are recognized
    % key is updated by move_spot
    switch double(key(1))
        case 108 % left
            if ptr_left(current_id)<0 % check for legal move
                current_id=-ptr_left(current_id);
                text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color',[.8,.8,.8]);
                cursor_pos(1)=cursor_pos(1)-1;
                text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color','r');
            end
        case 114 % right
            if ptr_right(current_id)<0 % check for legal move
                current_id=-ptr_right(current_id);
                text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color',[.8,.8,.8]);
                cursor_pos(1)=cursor_pos(1)+1;
                text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color','r');
            end
        case 117 % up
            if ptr_up(current_id)<0 % check for legal move
                current_id=-ptr_up(current_id);
                text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color',[.8,.8,.8]);
                cursor_pos(2)=cursor_pos(2)-1;
                text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color','r');
            end
        case 100 % down
            if ptr_down(current_id)<0 % check for legal move
                current_id=-ptr_down(current_id);
                text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color',[.8,.8,.8]);
                cursor_pos(2)=cursor_pos(2)+1;
                text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color','r');
            end

        otherwise
    end

end

thyme=toc;
title(cat(2,' Winning Time ',num2str(round(thyme*100)/100),'(sec)'),'FontSize',20)
return

function move_spot(src,evnt)
assignin('caller','key',evnt.Key)
return

function show_maze(row, col, rr, cc, ptr_left, ptr_up, ptr_right, ptr_down,h)
figure(h)
line([.5,col+.5],[.5,.5]) % draw top border
line([.5,col+.5],[row+.5,row+.5]) % draw bottom border
line([.5,.5],[1.5,row+.5]) % draw left border
line([col+.5,col+.5],[.5,row-.5])  % draw right border
for ii=1:length(ptr_right)
    if ptr_right(ii)>0 % right passage blocked
        line([cc(ii)+.5,cc(ii)+.5],[rr(ii)-.5,rr(ii)+.5]);
        hold on
    end
    if ptr_down(ii)>0 % down passage blocked
        line([cc(ii)-.5,cc(ii)+.5],[rr(ii)+.5,rr(ii)+.5]);
        hold on
    end

end
axis equal
axis([.5,col+.5,.5,row+.5])
axis off
set(gca,'YDir','reverse')
return

function [state, ptr_left, ptr_up, ptr_right, ptr_down]=make_pattern(row,col,pattern,id, rr, cc, state, ptr_left, ptr_up, ptr_right, ptr_down)

while max(state)>1 % remove walls until there is one simply connected region
    tid=ceil(col*row*rand(15,1)); % get a set of temporary ID's
    cityblock=cc(tid)+rr(tid); % get distance from the start
    is_linked=(state(tid)==1); % The start state is in region 1 - see if they are linked to the start
    temp = sortrows(cat(2,tid,cityblock,is_linked),[3,2]); % sort id's by start-link and distance
    tid = temp(1,1); % get the id of the closest unlinked intersection

    % The pattern is created by selective random removal of vertical or
    % horizontal walls as a function of position in the maze. I find the
    % checkerboard option the most challenging. Other patterns can be added
    switch upper(pattern)
    case 'C' % checkerboard
        dir = ceil(8*rand);
        nb=3;
        block_size =  min([row,col])/nb;
        while block_size>12
            nb=nb+2;
            block_size =  min([row,col])/nb;
        end
        odd_even = (ceil(rr(tid)/block_size)*ceil(col/block_size) + ceil(cc(tid)/block_size));
        if odd_even/2 == floor(odd_even/2)
            if dir>6
                dir=4;
            end
            if dir>4
                dir=3;
            end
        else
            if dir>6
                dir=2;
            end
            if dir>4
                dir=1;
            end
        end
    case 'B' % burst
        dir = ceil(8*rand);
        if abs((rr(tid)-row/2))<abs((cc(tid)-col/2))
            if dir>6
                dir=4;
            end
            if dir>4
                dir=3;
            end
        else
            if dir>6
                dir=2;
            end
            if dir>4
                dir=1;
            end
        end
    case 'S' %spiral
        dir = ceil(8*rand);
        if abs((rr(tid)-row/2))>abs((cc(tid)-col/2))
            if dir>6
                dir=4;
            end
            if dir>4
                dir=3;
            end
        else
            if dir>6
                dir=2;
            end
            if dir>4
                dir=1;
            end
        end
    case 'V'
        dir = ceil(8*rand);
        if dir>6
            dir=4;
        end
        if dir>4
            dir=3;
        end
    case 'H'
        dir = ceil(8*rand);
        if dir>6
            dir=2;
        end
        if dir>4
            dir=1;
        end
        otherwise % random
        dir = ceil(4*rand);
    end

    % after a candidate for wall removal is found, the candidate must pass
    % two conditions. 1) it is not an external wall  2) the regions on
    % each side of the wall were previously unconnected. If successful the
    % wall is removed, the connected states are updated to the lowest of
    % the two states, the pointers between the connected intersections are
    % now negative.
    switch dir
    case -1

    case 1
        if ptr_left(tid)>0 & state(tid)~=state(ptr_left(tid))
            state( state==state(tid) | state==state(ptr_left(tid)) )=min([state(tid),state(ptr_left(tid))]);
            ptr_right(ptr_left(tid))=-ptr_right(ptr_left(tid));
            ptr_left(tid)=-ptr_left(tid);
        end
    case 2
        if ptr_right(tid)>0 & state(tid)~=state(ptr_right(tid))
            state( state==state(tid) | state==state(ptr_right(tid)) )=min([state(tid),state(ptr_right(tid))]);
            ptr_left(ptr_right(tid))=-ptr_left(ptr_right(tid));
            ptr_right(tid)=-ptr_right(tid);
        end
    case 3
        if ptr_up(tid)>0 & state(tid)~=state(ptr_up(tid))
            state( state==state(tid) | state==state(ptr_up(tid)) )=min([state(tid),state(ptr_up(tid))]);
            ptr_down(ptr_up(tid))=-ptr_down(ptr_up(tid));
            ptr_up(tid)=-ptr_up(tid);
        end
    case 4
        if ptr_down(tid)>0 & state(tid)~=state(ptr_down(tid))
            state( state==state(tid) | state==state(ptr_down(tid)) )=min([state(tid),state(ptr_down(tid))]);
            ptr_up(ptr_down(tid))=-ptr_up(ptr_down(tid));
            ptr_down(tid)=-ptr_down(tid);
        end
    otherwise
        dir
        error('quit')
    end

end
return


text:
function a = iscomplex(X)
a = ~isreal(X);
end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function file= fileutil_getFilelist(spec, varargin)
% FILEUTIL_GETFILELIST - Retrieves a list of header/marker/EEG files.
%
% Synopsis:
%   File= fileutil_getFilelist(SPEC, 'Property, 'Value', ...)
%
% Arguments:
%   SPEC:  CELL|CHAR   list of file names (no extension)
%
% Properties:
%   'Ext': file extension. default: 'eeg'
%   'Folder': base directory to search for files. default: BTB.RawDir
%   'RequireMatch': boolean. This function will throw an error it this
%   property is set to true and no files were found
%
% Returns:
%   FILE: filename corresponding to spec (if found). FILE may also be a cell array of file names.
%
%

%% TODO: should also handle: spec is cell array

global BTB

props = {'Ext',             'eeg',                  'CHAR';
         'Folder',           BTB.RawDir,           '!CHAR';
         'RequireMatch',     0,                     '!BOOL';
         };

if nargin==0,
  file= props; return
end

opt= opt_proplistToStruct(varargin{:});
[opt,isdefault] = opt_setDefaults(opt, props);
opt_checkProplist(opt, props);
misc_checkType(spec,'CHAR');

if isdefault.Ext,
  is= find(spec=='.', 1, 'last');
  if ~isempty(is) && is<length(spec) && is>=length(spec)-4,
    ext= spec(is+1:end);
    if ~ismember('*',ext,'legacy') && ~ismember('/',ext,'legacy'),
      opt.Ext= ext;
    end
  else
    spec= [spec '.' opt.Ext];
  end
else
  spec= [spec '.' opt.Ext];
end

if isdefault.Folder,
  switch(lower(opt.Ext)),
   case {'eeg','vhdr','vmrk'},
    opt.Folder= BTB.RawDir;
   case 'mat',
    opt.Folder= BTB.MatDir;
  end
end

[filepath, dmy]= fileparts(spec);
if ~fileutil_isAbsolutePath(spec),
  spec= [opt.Folder filesep spec];
end

dd= dir(spec);
if isempty(dd),
  if opt.RequireMatch,
    msg= sprintf('no files matching ''%s'' found', spec);
    error(msg);
  end
  file= {};
  return;
end

if length(dd)==1,
  file= strcat(filepath, filesep, dd.name);
else
  file= strcat(filepath, filesep, {dd.name});
end
if ~isdefault.Ext,
  file= strrep(file, ['.' opt.Ext], '');
end

author: bbci


text:
function jac = jacexpfit(p, data)
  n=data;
  m=max(size(p));

  for i=1:n
    jac(i, 1:m)=[exp(-p(2)*i), -p(1)*i*exp(-p(2)*i), 1.0];
  end

author: vigente

repo: gerardus

save_path: github-repos/MATLAB/vigente-gerardus


text:
% Driver script for solving the 1D Poisson equation
Globals1D;

% Polynomial order used for approximation
N =4;

% Read in Mesh
[Nv, VX, K, EToV] = MeshGen1D(0,2*pi,10);

% Initialize solver and construct grid and metric
StartUp1D;

% Set RHS
f = -J.*((invV'*invV)*sin(x));

% Set up operator
[A] = PoissonCstab1D();

% Solve Problem
solvec = A\f(:);
u = reshape(solvec,Np,K);

repo: Aero-matlab


text:
classdef HBox < uix.Box
    %uix.HBox  Horizontal box
    %
    %  b = uix.HBox(p1,v1,p2,v2,...) constructs a horizontal box and sets
    %  parameter p1 to value v1, etc.
    %
    %  A horizontal box lays out contents from left to right.
    %
    %  See also: uix.VBox, uix.Grid, uix.HButtonBox, uix.HBoxFlex

    %  Copyright 2009-2016 The MathWorks, Inc.
    %  $Revision: 1436 $ $Date: 2016-11-17 17:53:29 +0000 (Thu, 17 Nov 2016) $

    properties( Access = public, Dependent, AbortSet )
        Widths % widths of contents, in pixels and/or weights
        MinimumWidths % minimum widths of contents, in pixels
    end

    properties( Access = protected )
        Widths_ = zeros( [0 1] ) % backing for Widths
        MinimumWidths_ = zeros( [0 1] ) % backing for MinimumWidths
    end

    methods

        function obj = HBox( varargin )
            %uix.HBox  Horizontal box constructor
            %
            %  b = uix.HBox() constructs a horizontal box.
            %
            %  b = uix.HBox(p1,v1,p2,v2,...) sets parameter p1 to value v1,
            %  etc.

            % Set properties
            if nargin > 0
                try
                    assert( rem( nargin, 2 ) == 0, 'uix:InvalidArgument', ...
                        'Parameters and values must be provided in pairs.' )
                    set( obj, varargin{:} )
                catch e
                    delete( obj )
                    e.throwAsCaller()
                end
            end

        end % constructor

    end % structors

    methods

        function value = get.Widths( obj )

            value = obj.Widths_;

        end % get.Widths

        function set.Widths( obj, value )

            % For those who can't tell a column from a row...
            if isrow( value )
                value = transpose( value );
            end

            % Check
            assert( isa( value, 'double' ), 'uix:InvalidPropertyValue', ...
                'Property ''Widths'' must be of type double.' )
            assert( all( isreal( value ) ) && ~any( isinf( value ) ) && ...
                ~any( isnan( value ) ), 'uix:InvalidPropertyValue', ...
                'Elements of property ''Widths'' must be real and finite.' )
            assert( isequal( size( value ), size( obj.Contents_ ) ), ...
                'uix:InvalidPropertyValue', ...
                'Size of property ''Widths'' must match size of contents.' )

            % Set
            obj.Widths_ = value;

            % Mark as dirty
            obj.Dirty = true;

        end % set.Widths

        function value = get.MinimumWidths( obj )

            value = obj.MinimumWidths_;

        end % get.MinimumWidths

        function set.MinimumWidths( obj, value )

            % For those who can't tell a column from a row...
            if isrow( value )
                value = transpose( value );
            end

            % Check
            assert( isa( value, 'double' ), 'uix:InvalidPropertyValue', ...
                'Property ''MinimumWidths'' must be of type double.' )
            assert( all( isreal( value ) ) && ~any( isinf( value ) ) && ...
                all( value >= 0 ), 'uix:InvalidPropertyValue', ...
                'Elements of property ''MinimumWidths'' must be non-negative.' )
            assert( isequal( size( value ), size( obj.Widths_ ) ), ...
                'uix:InvalidPropertyValue', ...
                'Size of property ''MinimumWidths'' must match size of contents.' )

            % Set
            obj.MinimumWidths_ = value;

            % Mark as dirty
            obj.Dirty = true;

        end % set.MinimumWidths

    end % accessors

    methods( Access = protected )

        function redraw( obj )
            %redraw  Redraw
            %
            %  c.redraw() redraws the container c.

            % Compute positions
            bounds = hgconvertunits( ancestor( obj, 'figure' ), ...
                [0 0 1 1], 'normalized', 'pixels', obj );
            widths = obj.Widths_;
            minimumWidths = obj.MinimumWidths_;
            padding = obj.Padding_;
            spacing = obj.Spacing_;
            c = numel( widths );
            xSizes = uix.calcPixelSizes( bounds(3), widths, ...
                minimumWidths, padding, spacing );
            xPositions = [cumsum( [0; xSizes(1:c-1,:)] ) + padding + ...
                spacing * transpose( 0:c-1 ) + 1, xSizes];
            yPositions = [padding + 1, max( bounds(4) - 2 * padding, 1 )];
            yPositions = repmat( yPositions, [c 1] );
            positions = [xPositions(:,1), yPositions(:,1), ...
                xPositions(:,2), yPositions(:,2)];

            % Set positions
            children = obj.Contents_;
            for ii = 1:numel( children )
                uix.setPosition( children(ii), positions(ii,:), 'pixels' )
            end

        end % redraw

        function addChild( obj, child )
            %addChild  Add child
            %
            %  c.addChild(d) adds the child d to the container c.

            % Add to sizes
            obj.Widths_(end+1,:) = -1;
            obj.MinimumWidths_(end+1,:) = 1;

            % Call superclass method
            addChild@uix.Box( obj, child )

        end % addChild

        function removeChild( obj, child )
            %removeChild  Remove child
            %
            %  c.removeChild(d) removes the child d from the container c.

            % Remove from sizes
            tf = obj.Contents_ == child;
            obj.Widths_(tf,:) = [];
            obj.MinimumWidths_(tf,:) = [];

            % Call superclass method
            removeChild@uix.Box( obj, child )

        end % removeChild

        function reorder( obj, indices )
            %reorder  Reorder contents
            %
            %  c.reorder(i) reorders the container contents using indices
            %  i, c.Contents = c.Contents(i).

            % Reorder
            obj.Widths_ = obj.Widths_(indices,:);
            obj.MinimumWidths_ = obj.MinimumWidths_(indices,:);

            % Call superclass method
            reorder@uix.Box( obj, indices )

        end % reorder

    end % template methods

end % classdef

author: talmo

repo: leap

save_path: github-repos/MATLAB/talmo-leap


text:
function[]=boxoff
% BOXON  Sets 'box' property to 'off'.
%   __________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2006 J.M. Lilly --- type 'help jlab_license' for details

set(gca,'box','off');

author: jonathanlilly

repo: jLab

save_path: github-repos/MATLAB/jonathanlilly-jLab


text:
function  R = MatrixExp3(so3mat)
% *** CHAPTER 3: RIGID-BODY MOTIONS ***
% Takes a 3x3 so(3) representation of exponential coordinates.
% Returns R in SO(3) that is achieved by rotating about omghat by theta
% from an initial orientation R = I.
% Example Input:
%
% clear; clc;
% so3mat = [[0, -3, 2]; [3, 0, -1]; [-2, 1, 0]];
% R = MatrixExp3(so3mat)
%
% Output:
% R =
%   -0.6949    0.7135    0.0893
%   -0.1920   -0.3038    0.9332
%    0.6930    0.6313    0.3481

omgtheta = so3ToVec(so3mat);
if NearZero(norm(omgtheta))
    R = eye(3);
else
    [omghat, theta] = AxisAng3(omgtheta);
    omgmat = so3mat / theta;
    R = eye(3) + sin(theta) * omgmat + (1 - cos(theta)) * omgmat * omgmat;
end
end

author: ShuoYangRobotics

repo: QuadrupedSim


text:
function r = randomc(varargin)
%RANDOMC      Complex random numbers in M+i*M with M=[min,max], default [-1,+1]
%
% Calling conventions as function  random
%

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

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

  if length(varargin)==0
    r = random(NaN) + sqrt(-1)*random(NaN);
  else
    r = random(NaN, varargin) + sqrt(-1)*random(NaN,varargin);
  end

  if rndold
    setround(rndold)
  end

repo: OpenMAS


text:
function gpcf = gpcf_periodic(varargin)
%GPCF_PERIODIC  Create a periodic covariance function for Gaussian Process
%
%  Description
%    GPCF = GPCF_PERIODIC('PARAM1',VALUE1,'PARAM2,VALUE2,...)
%    creates periodic covariance function structure in which the
%    named parameters have the specified values. Any unspecified
%    parameters are set to default values.
%
%    GPCF = GPCF_PERIODIC(GPCF,'PARAM1',VALUE1,'PARAM2,VALUE2,...)
%    modify a covariance function structure with the named
%    parameters altered with the specified values.
%
%    Periodic covariance function with squared exponential decay
%    part as in Rasmussen & Williams (2006) Gaussian processes for
%    Machine Learning.
%
%    Parameters for periodic covariance function [default]
%      magnSigma2             - magnitude (squared) [0.1]
%      lengthScale            - length scale for each input [10]
%                               This can be either scalar
%                               corresponding isotropic or vector
%                               corresponding ARD
%      period                 - length of the periodic component(s) [1]
%      lengthScale_sexp       - length scale for the squared exponential
%                               component [10] This can be either scalar
%                               corresponding isotropic or vector
%                               corresponding ARD.
%      decay                  - determines whether the squared exponential
%                               decay term is used (1) or not (0).
%                               Not a hyperparameter for the function.
%      magnSigma2_prior       - prior structure for magnSigma2 [prior_logunif]
%      lengthScale_prior      - prior structure for lengthScale [prior_t]
%      lengthScale_sexp_prior - prior structure for lengthScale_sexp
%                               [prior_fixed]
%      period_prior           - prior structure for period [prior_fixed]
%
%    Note! If the prior is 'prior_fixed' then the parameter in
%    question is considered fixed and it is not handled in
%    optimization, grid integration, MCMC etc.
%
%  See also
%    GP_SET, GPCF_*, PRIOR_*

% Copyright (c) 2009-2010 Heikki Peura
% Copyright (c) 2010 Aki Vehtari

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

  ip=inputParser;
  ip.FunctionName = 'GPCF_PERIODIC';
  ip.addOptional('gpcf', [], @isstruct);
  ip.addParamValue('magnSigma2',0.1, @(x) isscalar(x) && x>0);
  ip.addParamValue('lengthScale',10, @(x) isvector(x) && all(x>0));
  ip.addParamValue('period',1, @(x) isscalar(x) && x>0);
  ip.addParamValue('lengthScale_sexp',10, @(x) isvector(x) && all(x>0));
  ip.addParamValue('decay',0, @(x) isscalar(x) && (x==0||x==1));
  ip.addParamValue('magnSigma2_prior',prior_logunif, @(x) isstruct(x) || isempty(x));
  ip.addParamValue('lengthScale_prior',prior_t, @(x) isstruct(x) || isempty(x));
  ip.addParamValue('lengthScale_sexp_prior',[], @(x) isstruct(x) || isempty(x));
  ip.addParamValue('period_prior',[], @(x) isstruct(x) || isempty(x));
  ip.addParamValue('selectedVariables',[], @(x) isempty(x) || ...
                   (isvector(x) && all(x>0)));
  ip.parse(varargin{:});
  gpcf=ip.Results.gpcf;

  if isempty(gpcf)
    init=true;
    gpcf.type = 'gpcf_periodic';
  else
    if ~isfield(gpcf,'type') && ~isequal(gpcf.type,'gpcf_periodic')
      error('First argument does not seem to be a valid covariance function structure')
    end
    init=false;
  end

  if init || ~ismember('magnSigma2',ip.UsingDefaults)
    gpcf.magnSigma2 = ip.Results.magnSigma2;
  end
  if init || ~ismember('lengthScale',ip.UsingDefaults)
    gpcf.lengthScale = ip.Results.lengthScale;
  end
  if init || ~ismember('period',ip.UsingDefaults)
    gpcf.period = ip.Results.period;
  end
  if init || ~ismember('lengthScale_sexp',ip.UsingDefaults)
    gpcf.lengthScale_sexp=ip . Results.lengthScale_sexp;
  end
  if init || ~ismember('decay',ip.UsingDefaults)
    gpcf.decay = ip.Results.decay;
  end
  if init || ~ismember('magnSigma2_prior',ip.UsingDefaults)
    gpcf.p.magnSigma2 = ip.Results.magnSigma2_prior;
  end
  if init || ~ismember('lengthScale_prior',ip.UsingDefaults)
    gpcf.p.lengthScale = ip.Results.lengthScale_prior;
  end
  if init || ~ismember('lengthScale_sexp_prior',ip.UsingDefaults)
    gpcf.p.lengthScale_sexp = ip.Results.lengthScale_sexp_prior;
  end
  if init || ~ismember('period_prior',ip.UsingDefaults)
    gpcf.p.period = ip.Results.period_prior;
  end

  if ~ismember('selectedVariables',ip.UsingDefaults)
    gpcf.selectedVariables = ip.Results.selectedVariables;
  end

  if init
    % Set the function handles to the subfunctions
    gpcf.fh.pak = @gpcf_periodic_pak;
    gpcf.fh.unpak = @gpcf_periodic_unpak;
    gpcf.fh.lp = @gpcf_periodic_lp;
    gpcf.fh.lpg = @gpcf_periodic_lpg;
    gpcf.fh.cfg = @gpcf_periodic_cfg;
    gpcf.fh.ginput = @gpcf_periodic_ginput;
    gpcf.fh.cov = @gpcf_periodic_cov;
    gpcf.fh.covvec = @gpcf_periodic_covvec;
    gpcf.fh.trcov  = @gpcf_periodic_trcov;
    gpcf.fh.trvar  = @gpcf_periodic_trvar;
    gpcf.fh.recappend = @gpcf_periodic_recappend;
  end

end

function [w, s] = gpcf_periodic_pak(gpcf)
%GPCF_PERIODIC_PAK  Combine GP covariance function parameters into
%                   one vector
%
%  Description
%    W = GPCF_PERIODIC_PAK(GPCF) takes a covariance function
%    structure GPCF and combines the covariance function
%    parameters and their hyperparameters into a single row
%    vector W. This is a mandatory subfunction used for example
%    in energy and gradient computations.
%
%       w = [ log(gpcf.magnSigma2)
%             (hyperparameters of gpcf.magnSigma2)
%             log(gpcf.lengthScale(:))
%             (hyperparameters of gpcf.lengthScale)
%             log(gpcf.lengthScale_sexp)
%             (hyperparameters of gpcf.lengthScale_sexp)
%             log(gpcf.period)
%             (hyperparameters of gpcf.period)]'
%
%  See also
%    GPCF_PERIODIC_UNPAK

  if isfield(gpcf,'metric')
    error('Periodic covariance function not compatible with metrics.');
  else
    i1=0;i2=1;
    w = []; s = {};

    if ~isempty(gpcf.p.magnSigma2)
      w = [w log(gpcf.magnSigma2)];
      s = [s; 'log(periodic.magnSigma2)'];

      % Hyperparameters of magnSigma2
      [wh sh] = gpcf.p.magnSigma2.fh.pak(gpcf.p.magnSigma2);
      w = [w wh];
      s = [s; sh];
    end

    if ~isempty(gpcf.p.lengthScale)
      w = [w log(gpcf.lengthScale)];
      s = [s; 'log(periodic.lengthScale)'];

      % Hyperparameters of lengthScale
      [wh  sh] = gpcf.p.lengthScale.fh.pak(gpcf.p.lengthScale);
      w = [w wh];
      s = [s; sh];
    end

    if ~isempty(gpcf.p.lengthScale_sexp)  && gpcf.decay == 1
      w = [w log(gpcf.lengthScale_sexp)];
      s = [s; 'log(periodic.lengthScale_sexp)'];

      % Hyperparameters of lengthScale_sexp
      [wh sh] = gpcf.p.lengthScale_sexp.fh.pak(gpcf.p.lengthScale_sexp);
      w = [w wh];
      s = [s; sh];
    end

    if ~isempty(gpcf.p.period)
      w = [w log(gpcf.period)];
      s = [s; 'log(periodic.period)'];

      % Hyperparameters of period
      [wh sh] = gpcf.p.period.fh.pak(gpcf.p.period);
      w = [w wh];
      s = [s; sh];
    end
  end
end

function [gpcf, w] = gpcf_periodic_unpak(gpcf, w)
%GPCF_PERIODIC_UNPAK  Sets the covariance function parameters into
%                     the structure
%
%  Description
%    [GPCF, W] = GPCF_PERIODIC_UNPAK(GPCF, W) takes a covariance
%    function structure GPCF and a hyper-parameter vector W, and
%    returns a covariance function structure identical to the
%    input, except that the covariance hyper-parameters have been
%    set to the values in W. Deletes the values set to GPCF from
%    W and returns the modified W. This is a mandatory subfunction
%    used for example in energy and gradient computations.
%
%    Assignment is inverse of
%       w = [ log(gpcf.magnSigma2)
%             (hyperparameters of gpcf.magnSigma2)
%             log(gpcf.lengthScale(:))
%             (hyperparameters of gpcf.lengthScale)
%             log(gpcf.lengthScale_sexp)
%             (hyperparameters of gpcf.lengthScale_sexp)
%             log(gpcf.period)
%             (hyperparameters of gpcf.period)]'
%
%  See also
%    GPCF_PERIODIC_PAK

  if isfield(gpcf,'metric')
    error('Covariance function not compatible with metrics');
  else
    gpp=gpcf.p;
    if ~isempty(gpp.magnSigma2)
      i1=1;
      gpcf.magnSigma2 = exp(w(i1));
      w = w(i1+1:end);
    end
    if ~isempty(gpp.lengthScale)
      i2=length(gpcf.lengthScale);
      i1=1;
      gpcf.lengthScale = exp(w(i1:i2));
      w = w(i2+1:end);
    end
    if ~isempty(gpp.lengthScale_sexp) && gpcf.decay == 1
      i2=length(gpcf.lengthScale_sexp);
      i1=1;
      gpcf.lengthScale_sexp = exp(w(i1:i2));
      w = w(i2+1:end);
    end
    if ~isempty(gpp.period)
      i2=length(gpcf.period);
      i1=1;
      gpcf.period = exp(w(i1:i2));
      w = w(i2+1:end);
    end
    % hyperparameters
    if ~isempty(gpp.magnSigma2)
      [p, w] = gpcf.p.magnSigma2.fh.unpak(gpcf.p.magnSigma2, w);
      gpcf.p.magnSigma2 = p;
    end
    if ~isempty(gpp.lengthScale)
      [p, w] = gpcf.p.lengthScale.fh.unpak(gpcf.p.lengthScale, w);
      gpcf.p.lengthScale = p;
    end
    if ~isempty(gpp.lengthScale_sexp)
      [p, w] = gpcf.p.lengthScale_sexp.fh.unpak(gpcf.p.lengthScale_sexp, w);
      gpcf.p.lengthScale_sexp = p;
    end
    if ~isempty(gpp.period)
      [p, w] = gpcf.p.period.fh.unpak(gpcf.p.period, w);
      gpcf.p.period = p;
    end

  end
end

function lp = gpcf_periodic_lp(gpcf)
%GPCF_PERIODIC_LP  Evaluate the log prior of covariance function parameters
%
%  Description
%    LP = GPCF_PERIODIC_LP(GPCF) takes a covariance function
%    structure GPCF and returns log(p(th)), where th collects the
%    parameters. This is a mandatory subfunction used for example
%    in energy computations.
%
%    Also the log prior of the hyperparameters of the covariance
%    function parameters is added to E if hyperprior is
%    defined.
%
%  See also
%    GPCF_PERIODIC_PAK, GPCF_PERIODIC_UNPAK, GPCF_PERIODIC_LPG, GP_E

  lp = 0;
  gpp=gpcf.p;

  if isfield(gpcf,'metric')
    error('Covariance function not compatible with metrics');
  else
    % Evaluate the prior contribution to the error. The parameters that
    % are sampled are from space W = log(w) where w is all the "real" samples.
    % On the other hand errors are evaluated in the W-space so we need take
    % into account also the  Jacobian of transformation W -> w = exp(W).
    % See Gelman et.al., 2004, Bayesian data Analysis, second edition, p24.

    if ~isempty(gpcf.p.magnSigma2)
      lp = gpp.magnSigma2.fh.lp(gpcf.magnSigma2, gpp.magnSigma2) +log(gpcf.magnSigma2);
    end
    if ~isempty(gpp.lengthScale)
      lp = lp +gpp.lengthScale.fh.lp(gpcf.lengthScale, gpp.lengthScale) +sum(log(gpcf.lengthScale));
    end

    if ~isempty(gpp.lengthScale_sexp) && gpcf.decay == 1
      lp = lp +gpp.lengthScale_sexp.fh.lp(gpcf.lengthScale_sexp, gpp.lengthScale_sexp) +sum(log(gpcf.lengthScale_sexp));
    end
    if ~isempty(gpcf.p.period)
      lp = gpp.period.fh.lp(gpcf.period, gpp.period) +sum(log(gpcf.period));
    end
  end

end

function lpg = gpcf_periodic_lpg(gpcf)
%GPCF_PERIODIC_LPG  Evaluate gradient of the log prior with respect
%               to the parameters.
%
%  Description
%    LPG = GPCF_PERIODIC_LPG(GPCF) takes a covariance function
%    structure GPCF and returns LPG = d log (p(th))/dth, where th
%    is the vector of parameters. This is a mandatory subfunction
%    used for example in gradient computations.
%
%  See also
%    GPCF_PERIODIC_PAK, GPCF_PERIODIC_UNPAK, GPCF_PERIODIC_LP, GP_G

  lpg = [];
  gpp=gpcf.p;
  if isfield(gpcf,'metric')
    error('Covariance function not compatible with metrics');
  end
  if ~isempty(gpcf.p.magnSigma2)
    lpgs = gpp.magnSigma2.fh.lpg(gpcf.magnSigma2, gpp.magnSigma2);
    lpg = [lpg lpgs(1).*gpcf.magnSigma2+1 lpgs(2:end)];
  end
  if ~isempty(gpcf.p.lengthScale)
    lll = length(gpcf.lengthScale);
    lpgs = gpp.lengthScale.fh.lpg(gpcf.lengthScale, gpp.lengthScale);
    lpg = [lpg lpgs(1:lll).*gpcf.lengthScale+1 lpgs(lll+1:end)];
  end
  if gpcf.decay == 1 && ~isempty(gpcf.p.lengthScale_sexp)
    lll = length(gpcf.lengthScale_sexp);
    lpgs = gpp.lengthScale_sexp.fh.lpg(gpcf.lengthScale_sexp, gpp.lengthScale_sexp);
    lpg = [lpg lpgs(1:lll).*gpcf.lengthScale_sexp+1 lpgs(lll+1:end)];
  end
  if ~isempty(gpcf.p.period)
    lpgs = gpp.period.fh.lpg(gpcf.period, gpp.period);
    lpg = [lpg lpgs(1).*gpcf.period+1 lpgs(2:end)];
  end
end

function DKff = gpcf_periodic_cfg(gpcf, x, x2, mask, i1)
%GPCF_PERIODIC_CFG  Evaluate gradient of covariance function
%                   with respect to the parameters
%
%  Description
%    DKff = GPCF_PERIODIC_CFG(GPCF, X) takes a covariance
%    function structure GPCF, a matrix X of input vectors and
%    returns DKff, the gradients of covariance matrix Kff =
%    k(X,X) with respect to th (cell array with matrix elements).
%    This is a mandatory subfunction used in gradient computations.
%
%    DKff = GPCF_PERIODIC_CFG(GPCF, X, X2) takes a covariance
%    function structure GPCF, a matrix X of input vectors and
%    returns DKff, the gradients of covariance matrix Kff =
%    k(X,X2) with respect to th (cell array with matrix
%    elements). This subfunction is needed when using sparse
%    approximations (e.g. FIC).
%
%    DKff = GPCF_PERIODIC_CFG(GPCF, X, [], MASK) takes a
%    covariance function structure GPCF, a matrix X of input
%    vectors and returns DKff, the diagonal of gradients of
%    covariance matrix Kff = k(X,X2) with respect to th (cell
%    array with matrix elements). This subfunction is needed
%    when using sparse approximations (e.g. FIC).
%
%    DKff = GPCF_PERIODIC_CFG(GPCF, X, X2, [], i) takes a covariance
%    function structure GPCF, a matrix X of input vectors and
%    returns DKff, the gradients of covariance matrix Kff =
%    k(X,X2), or k(X,X) if X2 is empty, with respect to ith
%    hyperparameter. This subfunction is needed when using memory
%    save option in gp_set.
%
%  See also
%    GPCF_PERIODIC_PAK, GPCF_PERIODIC_UNPAK, GPCF_PERIODIC_LP, GP_G

  gpp=gpcf.p;

  i2=1;
  gp_period=gpcf.period;
  DKff={};
  gprior=[];

  if nargin==5
    % Use memory save option
    savememory=1;
    if i1==0
      % Return number of hyperparameters
      i=0;
      if ~isempty(gpcf.p.magnSigma2)
        i=1;
      end
      if ~isempty(gpcf.p.lengthScale)
        i=i+length(gpcf.lengthScale);
      end
      if gpcf.decay==1 && ~isempty(gpcf.p.lengthScale_sexp)
        i=i+length(gpcf.lengthScale_sexp);
      end
      if ~isempty(gpcf.p.period)
        i=i+length(gpcf.lengthScale);
      end
      DKff=i;
      return
    end
  else
    savememory=0;
  end

  % Evaluate: DKff{1} = d Kff / d magnSigma2
  %           DKff{2} = d Kff / d lengthScale
  % NOTE! Here we have already taken into account that the parameters are transformed
  % through log() and thus dK/dlog(p) = p * dK/dp

  % evaluate the gradient for training covariance
  if nargin == 2 || (isempty(x2) && isempty(mask))
    Cdm = gpcf_periodic_trcov(gpcf, x);

    ii1=0;
    if ~isempty(gpcf.p.magnSigma2) && (~savememory || all(i1==1));
        ii1=1;
        DKff{ii1} = Cdm;
    end

    if isfield(gpcf,'metric')
      error('Covariance function not compatible with metrics');
    else
      if isfield(gpcf,'selectedVariables')
        x = x(:,gpcf.selectedVariables);
      end
      [n, m] =size(x);
      if ~savememory
        i1=1:m;
      else
        if i1==1
          DKff=DKff{1};
          return
        else
          i1=i1-1;
        end
      end

      if ~isempty(gpcf.p.lengthScale) && (~savememory || all(i1 <= length(gpcf.lengthScale)))
        % loop over all the lengthScales
        if length(gpcf.lengthScale) == 1
          % In the case of isotropic PERIODIC
          s = 2./gpcf.lengthScale.^2;
          dist = 0;
          for i=1:m
            D = sin(pi.*bsxfun(@minus,x(:,i),x(:,i)')./gp_period);
            dist = dist + 2.*D.^2;
          end
          D = Cdm.*s.*dist;

          ii1 = ii1+1;
          DKff{ii1} = D;
        else
          % In the case ARD is used
          for i=i1
            s = 2./gpcf.lengthScale(i).^2;
            dist = sin(pi.*bsxfun(@minus,x(:,i),x(:,i)')./gp_period);
            D = Cdm.*s.*2.*dist.^2;

            ii1 = ii1+1;
            DKff{ii1} = D;
          end
        end
      end
      if savememory
        if length(DKff) == 1
          DKff=DKff{1};
          return
        end
        i1=i1-length(gpcf.lengthScale);
      end
      if gpcf.decay == 1
        if ~isempty(gpcf.p.lengthScale_sexp) && (~savememory || all(i1 <= length(gpcf.lengthScale_sexp)))
          if length(gpcf.lengthScale_sexp) == 1
            % In the case of isotropic PERIODIC
            s = 1./gpcf.lengthScale_sexp.^2;
            dist = 0;
            for i=1:m
              D = bsxfun(@minus,x(:,i),x(:,i)');
              dist = dist + D.^2;
            end
            D = Cdm.*s.*dist;

            ii1 = ii1+1;
            DKff{ii1} = D;
          else
            % In the case ARD is used
            for i=i1
              s = 1./gpcf.lengthScale_sexp(i).^2;
              dist = bsxfun(@minus,x(:,i),x(:,i)');
              D = Cdm.*s.*dist.^2;

              ii1 = ii1+1;
              DKff{ii1} = D;
            end
          end
        end
      end
      if savememory
        if length(DKff) == 1
          DKff=DKff{1};
          return
        end
        i1=i1-length(gpcf.lengthScale_sexp);
      end

      if ~isempty(gpcf.p.period)
        % Evaluate help matrix for calculations of derivatives
        % with respect to the period
        if length(gpcf.lengthScale) == 1
          % In the case of an isotropic PERIODIC
          s = repmat(1./gpcf.lengthScale.^2, 1, m);

          dist = 0;
          for i=1:m
            dist = dist + 2.*pi./gp_period.*sin(2.*pi.*bsxfun(@minus,x(:,i),x(:,i)')./gp_period).*bsxfun(@minus,x(:,i),x(:,i)').*s(i);
          end
          D = Cdm.*dist;
          ii1=ii1+1;
          DKff{ii1} = D;
        else
          % In the case ARD is used
          for i=i1
            s = 1./gpcf.lengthScale(i).^2;        % set the length
            dist = 2.*pi./gp_period.*sin(2.*pi.*bsxfun(@minus,x(:,i),x(:,i)')./gp_period).*bsxfun(@minus,x(:,i),x(:,i)');
            D = Cdm.*s.*dist;

            ii1=ii1+1;
            DKff{ii1} = D;
          end
        end
      end

    end
    % Evaluate the gradient of non-symmetric covariance (e.g. K_fu)
  elseif nargin == 3 || isempty(mask)
    if size(x,2) ~= size(x2,2)
      error('gpcf_periodic -> _ghyper: The number of columns in x and x2 has to be the same. ')
    end

    K = gpcf.fh.cov(gpcf, x, x2);
    ii1=0;
    if ~isempty(gpcf.p.magnSigma2) && (~savememory || all(i1==1))
        ii1=1;
        DKff{ii1} = K;
    end

    if isfield(gpcf,'metric')
      error('Covariance function not compatible with metrics');
    else
      if isfield(gpcf,'selectedVariables')
        x = x(:,gpcf.selectedVariables);
        x2 = x2(:,gpcf.selectedVariables);
      end
      [n, m] =size(x);
      if ~savememory
        i1=1:m;
      else
        if i1==1
          DKff=DKff{1};
          return
        end
        i1=i1-1;
      end
      % Evaluate help matrix for calculations of derivatives with respect to the lengthScale
      if ~isempty(gpcf.p.lengthScale) && (~savememory || all(i1 <= length(gpcf.lengthScale)))
        if length(gpcf.lengthScale) == 1
          % In the case of an isotropic PERIODIC
          s = 1./gpcf.lengthScale.^2;
          dist = 0; dist2 = 0;
          for i=1:m
            dist = dist + 2.*sin(pi.*bsxfun(@minus,x(:,i),x2(:,i)')./gp_period).^2;
          end
          DK_l = 2.*s.*K.*dist;

          ii1=ii1+1;
          DKff{ii1} = DK_l;
        else
          % In the case ARD is used
          for i=i1
            s = 1./gpcf.lengthScale(i).^2;        % set the length
            dist = 2.*sin(pi.*bsxfun(@minus,x(:,i),x2(:,i)')./gp_period);
            DK_l = 2.*s.*K.*dist.^2;

            ii1=ii1+1;
            DKff{ii1} = DK_l;
          end
        end
      end
      if savememory
        if length(DKff) == 1
          DKff=DKff{1};
          return
        end
        i1=i1-length(gpcf.lengthScale);
      end

      if gpcf.decay == 1 && (~savememory || all(i1 <= length(gpcf.lengthScale_sexp)))
        % Evaluate help matrix for calculations of derivatives with
        % respect to the lengthScale_sexp
        if length(gpcf.lengthScale_sexp) == 1
          % In the case of an isotropic PERIODIC
          s = 1./gpcf.lengthScale_sexp.^2;
          dist = 0; dist2 = 0;
          for i=1:m
            dist = dist + bsxfun(@minus,x(:,i),x2(:,i)').^2;
          end
          DK_l = s.*K.*dist;

          ii1=ii1+1;
          DKff{ii1} = DK_l;
        else
          % In the case ARD is used
          for i=i1
            s = 1./gpcf.lengthScale_sexp(i).^2;        % set the length
            dist = bsxfun(@minus,x(:,i),x2(:,i)');
            DK_l = s.*K.*dist.^2;

            ii1=ii1+1;
            DKff{ii1} = DK_l;
          end
        end
      end
      if savememory
        if length(DKff) == 1
          DKff=DKff{1};
          return
        end
        i1=i1-length(gpcf.lengthScale_sexp);
      end

      if ~isempty(gpcf.p.period)
        % Evaluate help matrix for calculations of derivatives
        % with respect to the period
        if length(gpcf.lengthScale) == 1
          % In the case of an isotropic PERIODIC
          s = repmat(1./gpcf.lengthScale.^2, 1, m);
          dist = 0; dist2 = 0;
          for i=1:m
            dist = dist + 2.*pi./gp_period.*sin(2.*pi.*bsxfun(@minus,x(:,i),x2(:,i)')./gp_period).*bsxfun(@minus,x(:,i),x2(:,i)').*s(i);
          end
          DK_l = K.*dist;

          ii1=ii1+1;
          DKff{ii1} = DK_l;
        else
          % In the case ARD is used
          for i=i1
            s = 1./gpcf.lengthScale(i).^2;        % set the length
            dist = 2.*pi./gp_period.*sin(2.*pi.*bsxfun(@minus,x(:,i),x2(:,i)')./gp_period).*bsxfun(@minus,x(:,i),x2(:,i)');
            DK_l = s.*K.*dist;

            ii1=ii1+1;
            DKff{ii1} = DK_l;
          end
        end
      end
    end
    % Evaluate: DKff{1}    = d mask(Kff,I) / d magnSigma2
    %           DKff{2...} = d mask(Kff,I) / d lengthScale etc.
  elseif nargin == 4 || nargin == 5
    [n, m] =size(x);
    if isfield(gpcf,'metric')
      error('Covariance function not compatible with metrics');
    else
        ii1=0;
        if ~isempty(gpcf.p.magnSigma2) && (~savememory || all(i1==1))
            ii1=1;
            DKff{ii1} = gpcf.fh.trvar(gpcf, x);   % d mask(Kff,I) / d magnSigma2
        end
      for i2=1:length(gpcf.lengthScale)
        ii1 = ii1+1;
        DKff{ii1}  = 0;                          % d mask(Kff,I) / d lengthScale
      end
      if gpcf.decay == 1
        for i2=1:length(gpcf.lengthScale_sexp)
          ii1 = ii1+1;
          DKff{ii1}  = 0;                      % d mask(Kff,I) / d lengthScale_sexp
        end
      end
      if ~isempty(gpcf.p.period)
        ii1 = ii1+1;                             % d mask(Kff,I) / d period
        DKff{ii1}  = 0;
      end
    end
  end
  if savememory
    DKff=DKff{1};
  end
end

function DKff = gpcf_periodic_ginput(gpcf, x, x2, i1)
%GPCF_PERIODIC_GINPUT  Evaluate gradient of covariance function with
%                      respect to x
%
%  Description
%    DKff = GPCF_PERIODIC_GINPUT(GPCF, X) takes a covariance
%    function structure GPCF, a matrix X of input vectors and
%    returns DKff, the gradients of covariance matrix Kff =
%    k(X,X) with respect to X (cell array with matrix elements).
%    This subfunction is needed when computing gradients with
%    respect to inducing inputs in sparse approximations.
%
%    DKff = GPCF_PERIODIC_GINPUT(GPCF, X, X2) takes a covariance
%    function structure GPCF, a matrix X of input vectors and
%    returns DKff, the gradients of covariance matrix Kff =
%    k(X,X2) with respect to X (cell array with matrix elements).
%    This subfunction is needed when computing gradients with
%    respect to inducing inputs in sparse approximations.
%
%    DKff = GPCF_PERIODIC_GINPUT(GPCF, X, X2, i) takes a covariance
%    function structure GPCF, a matrix X of input vectors and
%    returns DKff, the gradients of covariance matrix Kff =
%    k(X,X2), or k(X,X) if X2 is empty, with respect to ith
%    covariate in X. This subfunction is needed when using memory
%    save option in gp_set.
%
%  See also
%    GPCF_PERIODIC_PAK, GPCF_PERIODIC_UNPAK, GPCF_PERIODIC_LP, GP_G

  [n, m] =size(x);
  gp_period=gpcf.period;
  ii1 = 0;
  if length(gpcf.lengthScale) == 1
    % In the case of an isotropic PERIODIC
    s = repmat(1./gpcf.lengthScale.^2, 1, m);
    %gp_period = repmat(1./gp_period, 1, m);
  else
    s = 1./gpcf.lengthScale.^2;
  end
  if gpcf.decay == 1
    if length(gpcf.lengthScale_sexp) == 1
      % In the case of an isotropic PERIODIC
      s_sexp = repmat(1./gpcf.lengthScale_sexp.^2, 1, m);
    else
      s_sexp = 1./gpcf.lengthScale_sexp.^2;
    end
  end
  if nargin<4
    i1=1:m;
  else
    % Use memory save option
    if i1==0
      % Return number of covariates
      if isfield(gpcf,'selectedVariables')
        DKff=length(gpcf.selectedVariables);
      else
        DKff=m;
      end
      return
    end
  end

  if nargin == 2 || isempty(x2)
    K = gpcf.fh.trcov(gpcf, x);
    if isfield(gpcf,'metric')
      error('Covariance function not compatible with metrics');
    else
      for i=i1
        for j = 1:n
          DK = zeros(size(K));
          DK(j,:) = -s(i).*2.*pi./gp_period.*sin(2.*pi.*bsxfun(@minus,x(j,i),x(:,i)')./gp_period);
          if gpcf.decay == 1
            DK(j,:) = DK(j,:)-s_sexp(i).*bsxfun(@minus,x(j,i),x(:,i)');
          end
          DK = DK + DK';

          DK = DK.*K;      % dist2 = dist2 + dist2' - diag(diag(dist2));

          ii1 = ii1 + 1;
          DKff{ii1} = DK;
        end
      end
    end

  elseif nargin == 3
    K = gpcf.fh.cov(gpcf, x, x2);

    if isfield(gpcf,'metric')
      error('Covariance function not compatible with metrics');
    else
      ii1 = 0;
      for i=i1
        for j = 1:n
          DK= zeros(size(K));
          if gpcf.decay == 1
            DK(j,:) = -s(i).*2.*pi./gp_period.*sin(2.*pi.*bsxfun(@minus,x(j,i),x2(:,i)')./gp_period)-s_sexp(i).*bsxfun(@minus,x(j,i),x2(:,i)');
          else
            DK(j,:) = -s(i).*2.*pi./gp_period.*sin(2.*pi.*bsxfun(@minus,x(j,i),x2(:,i)')./gp_period);
          end
          DK = DK.*K;

          ii1 = ii1 + 1;
          DKff{ii1} = DK;
        end
      end
    end
  end
end

function C = gpcf_periodic_cov(gpcf, x1, x2)
%GP_PERIODIC_COV  Evaluate covariance matrix between two input vectors
%
%  Description
%    C = GP_PERIODIC_COV(GP, TX, X) takes in covariance function
%    of a Gaussian process GP and two matrixes TX and X that
%    contain input vectors to GP. Returns covariance matrix C.
%    Every element ij of C contains covariance between inputs i
%    in TX and j in X. This is a mandatory subfunction used for
%    example in prediction and energy computations.
%
%  See also
%    GPCF_PERIODIC_TRCOV, GPCF_PERIODIC_TRVAR, GP_COV, GP_TRCOV

  if isempty(x2)
    x2=x1;
  end
%   [n1,m1]=size(x1);
%   [n2,m2]=size(x2);
  gp_period=gpcf.period;

  if size(x1,2)~=size(x2,2)
    error('the number of columns of X1 and X2 has to be same')
  end

  if isfield(gpcf,'metric')
    error('Covariance function not compatible with metrics');
  else
    if isfield(gpcf,'selectedVariables')
      x1 = x1(:,gpcf.selectedVariables);
      x2 = x2(:,gpcf.selectedVariables);
    end
    [n1,m1]=size(x1);
    [n2,m2]=size(x2);

    C=zeros(n1,n2);
    ma2 = gpcf.magnSigma2;

    % Evaluate the covariance
    if ~isempty(gpcf.lengthScale)
      s = 1./gpcf.lengthScale.^2;
      if gpcf.decay == 1
        s_sexp = 1./gpcf.lengthScale_sexp.^2;
      end
      if m1==1 && m2==1
        dd = bsxfun(@minus,x1,x2');
        dist=2.*sin(pi.*dd./gp_period).^2.*s;
        if gpcf.decay == 1
          dist = dist + dd.^2.*s_sexp./2;
        end
      else
        % If ARD is not used make s a vector of
        % equal elements
        if size(s)==1
          s = repmat(s,1,m1);
        end
        if gpcf.decay == 1
          if size(s_sexp)==1
            s_sexp = repmat(s_sexp,1,m1);
          end
        end

        dist=zeros(n1,n2);
        for j=1:m1
          dd = bsxfun(@minus,x1(:,j),x2(:,j)');
          dist = dist + 2.*sin(pi.*dd./gp_period).^2.*s(:,j);
          if gpcf.decay == 1
            dist = dist +dd.^2.*s_sexp(:,j)./2;
          end
        end
      end
      dist(dist<eps) = 0;
      C = ma2.*exp(-dist);
    end

  end
end

function C = gpcf_periodic_trcov(gpcf, x)
%GP_PERIODIC_TRCOV  Evaluate training covariance matrix of inputs
%
%  Description
%    C = GP_PERIODIC_TRCOV(GP, TX) takes in covariance function
%    of a Gaussian process GP and matrix TX that contains
%    training input vectors. Returns covariance matrix C. Every
%    element ij of C contains covariance between inputs i and j
%    in TX. This is a mandatory subfunction used for example in
%    prediction and energy computations.
%
%  See also
%    GPCF_PERIODIC_COV, GPCF_PERIODIC_TRVAR, GP_COV, GP_TRCOV

  if isfield(gpcf,'metric')
    error('Covariance function not compatible with metrics');
  else

    % Try to use the C-implementation
    C=trcov(gpcf, x);
    %     C = NaN;
    if isnan(C)
      % If there wasn't C-implementation do here
      if isfield(gpcf,'selectedVariables')
        x = x(:,gpcf.selectedVariables);
      end
      [n, m] =size(x);
      gp_period=gpcf.period;

      s = 1./(gpcf.lengthScale);
      s2 = s.^2;
      if size(s)==1
        s2 = repmat(s2,1,m);
        gp_period = repmat(gp_period,1,m);
      end
      if gpcf.decay == 1
        s_sexp = 1./(gpcf.lengthScale_sexp);
        s_sexp2 = s_sexp.^2;
        if size(s_sexp)==1
          s_sexp2 = repmat(s_sexp2,1,m);
        end
      end

      ma = gpcf.magnSigma2;

      C = zeros(n,n);
      for ii1=1:n-1
        d = zeros(n-ii1,1);
        col_ind = ii1+1:n;
        for ii2=1:m
          d = d+2.*s2(ii2).*sin(pi.*(x(col_ind,ii2)-x(ii1,ii2))./gp_period(ii2)).^2;
          if gpcf.decay == 1
            d=d+s_sexp2(ii2)./2.*(x(col_ind,ii2)-x(ii1,ii2)).^2;
          end
        end
        C(col_ind,ii1) = d;

      end
      C(C<eps) = 0;
      C = C+C';
      C = ma.*exp(-C);
    end
  end
end

function C = gpcf_periodic_trvar(gpcf, x)
%GP_PERIODIC_TRVAR  Evaluate training variance vector
%
%  Description
%    C = GP_PERIODIC_TRVAR(GPCF, TX) takes in covariance function
%    of a Gaussian process GPCF and matrix TX that contains
%    training inputs. Returns variance vector C. Every
%    element i of C contains variance of input i in TX. This is a
%    mandatory subfunction used for example in prediction and
%    energy computations.
%
%  See also
%    GPCF_PERIODIC_COV, GP_COV, GP_TRCOV

  [n, m] =size(x);

  C = ones(n,1)*gpcf.magnSigma2;
  C(C<eps)=0;
end

function reccf = gpcf_periodic_recappend(reccf, ri, gpcf)
%RECAPPEND Record append
%
%  Description
%    RECCF = GPCF_PERIODIC_RECAPPEND(RECCF, RI, GPCF) takes a
%    covariance function record structure RECCF, record index RI
%    and covariance function structure GPCF with the current MCMC
%    samples of the parameters. Returns RECCF which contains all
%    the old samples and the current samples from GPCF. This
%    subfunction is needed when using MCMC sampling (gp_mc).
%
%  See also
%    GP_MC and GP_MC -> RECAPPEND

  if nargin == 2
    % Initialize the record
    reccf.type = 'gpcf_periodic';

    % Initialize parameters
    reccf.lengthScale= [];
    reccf.magnSigma2 = [];
    reccf.lengthScale_sexp = [];
    reccf.period = [];

    % Set the function handles
    reccf.fh.pak = @gpcf_periodic_pak;
    reccf.fh.unpak = @gpcf_periodic_unpak;
    reccf.fh.e = @gpcf_periodic_lp;
    reccf.fh.lpg = @gpcf_periodic_lpg;
    reccf.fh.cfg = @gpcf_periodic_cfg;
    reccf.fh.cov = @gpcf_periodic_cov;
    reccf.fh.trcov  = @gpcf_periodic_trcov;
    reccf.fh.trvar  = @gpcf_periodic_trvar;
    reccf.fh.recappend = @gpcf_periodic_recappend;
    reccf.p=[];
    reccf.p.lengthScale=[];
    reccf.p.magnSigma2=[];
    if ri.decay == 1
      reccf.p.lengthScale_sexp=[];
      if ~isempty(ri.p.lengthScale_sexp)
        reccf.p.lengthScale_sexp = ri.p.lengthScale_sexp;
      end
    end

    reccf.p.period=[];
    if ~isempty(ri.p.period)
      reccf.p.period= ri.p.period;
    end
    if isfield(ri.p,'lengthScale') && ~isempty(ri.p.lengthScale)
      reccf.p.lengthScale = ri.p.lengthScale;
    end
    if ~isempty(ri.p.magnSigma2)
      reccf.p.magnSigma2 = ri.p.magnSigma2;
    end
  else
    % Append to the record

    gpp = gpcf.p;

    % record lengthScale
    reccf.lengthScale(ri,:)=gpcf.lengthScale;
    if isfield(gpp,'lengthScale') && ~isempty(gpp.lengthScale)
      reccf.p.lengthScale = gpp.lengthScale.fh.recappend(reccf.p.lengthScale, ri, gpcf.p.lengthScale);
    end

    % record magnSigma2
    reccf.magnSigma2(ri,:)=gpcf.magnSigma2;
    if isfield(gpp,'magnSigma2') && ~isempty(gpp.magnSigma2)
      reccf.p.magnSigma2 = gpp.magnSigma2.fh.recappend(reccf.p.magnSigma2, ri, gpcf.p.magnSigma2);
    end

    % record lengthScale_sexp
    if ~isempty(gpcf.lengthScale_sexp) && gpcf.decay == 1
      reccf.lengthScale_sexp(ri,:)=gpcf.lengthScale_sexp;
      if isfield(gpp,'lengthScale_sexp') && ~isempty(gpp.lengthScale_sexp)
        reccf.p.lengthScale_sexp = gpp.lengthScale_sexp.fh.recappend(reccf.p.lengthScale_sexp, ri, gpcf.p.lengthScale_sexp);
      end
    end

    % record period
    reccf.period(ri,:)=gpcf.period;
    if isfield(gpp,'period') && ~isempty(gpp.period)
      reccf.p.period = gpp.period.fh.recappend(reccf.p.period, ri, gpcf.p.period);
    end

    % record decay
    if ~isempty(gpcf.decay)
      reccf.decay(ri,:)=gpcf.decay;
    end

  end
end


text:
function p = predict(theta, X)
%PREDICT Predict whether the label is 0 or 1 using learned logistic
%regression parameters theta
%   p = PREDICT(theta, X) computes the predictions for X using a
%   threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)

m = size(X, 1); % Number of training examples

% You need to return the following variables correctly
p = zeros(m, 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned logistic regression parameters.
%               You should set p to a vector of 0's and 1's
%

h_theta = sigmoid(X*theta);
p = ceil(2*h_theta)-1;

% =========================================================================

end

author: zlotus


text:
function view = makeGrayVolButtons(view)
%
% view = makeGrayVolButtons(view)
%
% Installs push buttons that choose gray mode vs. volume mode for
% in the Volume view.
%
% djh, 8/98
% Ress, 6/03: Added buttons for 3D rendering.

width = .1;
height = .05;
left = .01;

% Switch-to-volume button:
bot = 0.50;
callbackStr = ...
    [view.name,'=switch2Vol(',view.name,'); ',...
	view.name,'=refreshScreen(',view.name,');'];
view.ui.grayVolButtons(2) = ...
    uicontrol('Style','radiobutton',...
    'String','Volume',...
    'Units','normalized',...
    'BackgroundColor',get(gcf,'Color'),...
    'Position',[left,bot,width,height],...
    'Callback', callbackStr);
% Switch-to-gray button
bot = 0.45;
callbackStr = ...
    [view.name,'=switch2Gray(',view.name,'); ',...
	view.name,'=refreshScreen(',view.name,');'];
view.ui.grayVolButtons(1) = ...
    uicontrol('Style','radiobutton',...
    'String','Gray',...
    'BackgroundColor',get(gcf,'Color'),...
    'Units','normalized',...
    'Position',[left,bot,width,height],...
    'Callback', callbackStr);
% Initially, select button volume view:
selectButton(view.ui.grayVolButtons, 1);

% Now add selector for 3D model
% Label
% width = 0.19;
% left = 0.001;
% bot = 0.30;
% view.ui.gray3dButtons(2) = uicontrol( ...
%     'Style', 'text', ...
%     'Units', 'normalized', ...
%     'String', '3D Model:', ...
%     'Position', [left, bot, width, height], ...
%     'HorizontalAlignment', 'left',...
%     'BackgroundColor', get(view.ui.windowHandle,'Color'));
% bot = 0.25;
%
% % 3d model selector
% callbackStr = [view.name,'.meshNum3d = get(gcbo,''Value'');' view.name,'=Refresh3D(', view.name, ');'];
% view.ui.gray3dButtons(1) = uicontrol( ...
%     'Style', 'popupmenu',...
%     'String', {'none'},...
%     'Value', 1, ...
%     'Units', 'normalized',...
%     'Position', [left, bot, width, height],...
%     'Callback', callbackStr,...
%     'TooltipString','Load and build 3d meshes from 3D mesh submenu in Window menu.');

return;

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function x = unique(x)
%UNIQUE (overloaded)

if min(x.dim(1),x.dim(2))~=1
    error('UNIQUE currently only supported for vectors')
end

base = x.basis;
vars = x.lmi_variables;
[new_base,i,j] = unique(base,'rows');

x.basis = new_base;
if x.dim(2)==1
    x.dim(1) = size(new_base,1);
else
    x.dim(2) = size(new_base,1);
end
% Reset info about conic terms
x.conicinfo = [0 0];

author: zarathustr

repo: LibQPEP

save_path: github-repos/MATLAB/zarathustr-LibQPEP


text:
function [vValues] = bruteforceloglikecgr(time_as)
    % bruteforceloglike Calculates by a constrained grid search
    %
    % [pv, cv, kv] = bruteforceloglike(time_as);
    % vValues = [pvalue, cvalue, kvalue];
    % --------------------------------------------
    % the parameters of the modified Omori formula
    % using the log likelihood function by Ogata
    %
    % Input parameters:
    %   time_as     Delay time [days]
    %
    % Output parameters:
    %   pv          p value
    %   cv          c value
    %   kv          k value
    %
    % Samuel Neukomme
    % July 31, 2002

    options = optimset('Display','none','MaxFunEvals',400,'TolFun',1e-04,'MaxIter',500);
    vStartValues = [1.1 0.5 200];

    [vValues, ~] = fmincon(@bruteloglike, vStartValues, [], [], [], [],...
        [0.2 0.01 10], [2.7 3 5000], [], options, time_as);

author: CelsoReyes


text:
function file_delete ( file_name )

%*****************************************************************************80
%
%% FILE_DELETE deletes a named file if it exists.
%
%  Discussion:
%
%    You might want to call this routine to get rid of any old copy
%    of a file, before trying to open a new copy with the OPEN argument:
%      status = 'new'.
%
%    It's not always safe to open a file with " STATUS = 'UNKNOWN' ".
%    For instance, on the SGI, the most recent version of the FORTRAN
%    compiler seems to go crazy when I open an unformatted direct
%    access file this way.  It creates an enormous file (of somewhat
%    random size).  The problem goes away if I delete any old copy
%    using this routine, and then open a fresh copy with
%    " STATUS = 'NEW' ".  It's a scary world.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 November 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string FILE_NAME, the name of the file.
%

%
%  Does the file exist?
%
  if ( ~file_exist ( file_name ) )
    return
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, 'FILE_DELETE:\n' );
  fprintf ( 1, '  Deleting old version of "%s".\n', file_name );

  delete ( file_name );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
% Fifteen Game for MATLAB
% (c) 2010 Mihir Shah

function varargout = Fifteen(varargin)
% FIFTEEN M-file for Fifteen.fig
%      FIFTEEN, by itself, creates a new FIFTEEN or raises the existing
%      singleton*.
%
%      H = FIFTEEN returns the handle to a new FIFTEEN or the handle to
%      the existing singleton*.
%
%      FIFTEEN('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in FIFTEEN.M with the given input arguments.
%
%      FIFTEEN('Property','Value',...) creates a new FIFTEEN or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Fifteen_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Fifteen_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help Fifteen

% Last Modified by GUIDE v2.5 06-Jul-2010 16:20:52

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

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

% --- Executes just before Fifteen is made visible.
function Fifteen_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to Fifteen (see VARARGIN)

% Choose default command line output for Fifteen
handles.output = hObject;
guidata(hObject, handles);
clc;
clear all;
global x;
x = zeros(4);
i=1;
while i<16 && i>0
    m = randi([1,4]);
    n = randi([1,4]);
    if x(m,n) == 0
        x(m,n) = i;
        i = i + 1;
    end
end
display(x);
global counter;
counter = 0;
tic
% Update handles structure

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

% Get default command line output from handles structure
set(handles.p_counter,'String','0');
set(handles.p_clock,'String','0');
varargout{1} = handles.output;

function a = access()
global x;
a = x;

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

global p;
p = 1;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
% if ~bcolor(1,2)
%     stra = get(handles.p11,'String');
%     strb = get(handles.p12,'String');
%     temp = stra;
%     stra = strb;
%     strb = temp;
%     set(handles.p11,'String',stra);
%     set(handles.p12,'String',strb);
%     set(handles.p11,'BackgroundColor','black');
%     bcolor(1,1) = 0;
%     bcolor(1,2) = 1;
%     set(handles.p12,'BackgroundColor','white');
% end
guidata(hObject, handles);

% --- Executes on button press in p12.
function p12_Callback(hObject, eventdata, handles)
global p;
p = 2;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes on button press in p13.
function p13_Callback(hObject, eventdata, handles)
global p;
p = 3;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes on button press in p14.
function p14_Callback(hObject, eventdata, handles)
global p;
p = 4;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes on button press in p21.
function p21_Callback(hObject, eventdata, handles)
global p;
p = 5;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes on button press in p22.
function p22_Callback(hObject, eventdata, handles)
global p;
p = 6;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes on button press in p23.
function p23_Callback(hObject, eventdata, handles)
global p;
p = 7;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes on button press in p24.
function p24_Callback(hObject, eventdata, handles)
global p;
p = 8;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes on button press in p31.
function p31_Callback(hObject, eventdata, handles)
global p;
p = 9;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes on button press in p32.
function p32_Callback(hObject, eventdata, handles)
global p;
p = 10;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes on button press in p33.
function p33_Callback(hObject, eventdata, handles)
global p;
p = 11;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes on button press in p34.
function p34_Callback(hObject, eventdata, handles)
global p;
p = 12;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes on button press in p41.
function p41_Callback(hObject, eventdata, handles)
global p;
p = 13;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes on button press in p42.
function p42_Callback(hObject, eventdata, handles)
global p;
p = 14;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes on button press in p43.
function p43_Callback(hObject, eventdata, handles)
global p;
p = 15;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes on button press in p44.
function p44_Callback(hObject, eventdata, handles)
global p;
p = 16;
p_setter_Callback(hObject, eventdata, handles)
p_slide_Callback(hObject, eventdata, handles)
p_win_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes on button press in p_new.
function p_new_Callback(hObject, eventdata, handles)

Fifteen;
x = access();
global bcolor;
bcolor = zeros(4);
p_initial_Callback(hObject, eventdata, handles)
guidata(hObject,handles);

% --- Executes on button press in p_initial.
function p_initial_Callback(hObject, eventdata, handles)

x = access();
% set(handles.p_counter,'String','0');
for m=1:1:4
    for n=1:1:4
        s = ['set(handles.p' int2str(m) int2str(n) ',''BackgroundColor'',''white'')'];
        eval(s);
        if x(m,n) ~= 0
            s = ['set(handles.p' int2str(m) int2str(n) ',''String'',x(' int2str(m) ',' int2str(n) '))'];
            eval(s);
        else
            s = ['set(handles.p' int2str(m) int2str(n) ',''String'',x(' int2str(m) ',' int2str(n) '))'];
            eval(s);
            s = ['set(handles.p' int2str(m) int2str(n) ',''BackgroundColor'',''black'')'];
            eval(s);
        end
    end
end
guidata(hObject,handles);

% --- Executes on button press in p_slide.
function p_slide_Callback(hObject, eventdata, handles)
global bcolor;
global row;
global col;
global row_p;
global col_p;
global counter;
for m=1:1:4
    for n=1:1:4
        s = ['get(handles.p' int2str(m) int2str(n) ',''BackgroundColor'');'];
        z = eval(s);
        bcolor(m,n) = z(1);
        if bcolor(m,n) == 0
            row = m;
            col = n;
        end
    end
end
guidata(hObject,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if limit(row_p,col_p-1) && ~bcolor(row_p,col_p-1)
%     stra = get(handles.p11,'String');
    s1 = ['get(handles.p' int2str(row_p) int2str(col_p) ',''String'');'];
    stra = eval(s1);
%     strb = get(handles.p12,'String');
    s2 = ['get(handles.p' int2str(row_p) int2str(col_p-1) ',''String'');'];
    strb = eval(s2);
    temp = stra;
    stra = strb;
    strb = temp;
%     set(handles.p11,'String',stra);
    s3 = ['set(handles.p' int2str(row_p) int2str(col_p) ',''String'',' stra ');'];
    eval(s3);
%     set(handles.p12,'String',strb);
    s4 = ['set(handles.p' int2str(row_p) int2str(col_p-1) ',''String'',' strb ');'];
    eval(s4);
%     bcolor(1,1) = 0;
%     bcolor(1,2) = 1;
    bcolor(row_p,col_p) = 0;
    bcolor(row_p,col_p-1) = 1;
%    set(handles.p11,'BackgroundColor','black');
    s5 = ['set(handles.p' int2str(row_p) int2str(col_p) ',''BackgroundColor'',''black'');'];
    eval(s5);
%     set(handles.p12,'BackgroundColor','white');
    s6 = ['set(handles.p' int2str(row_p) int2str(col_p-1) ',''BackgroundColor'',''white'')'];
    eval(s6);
    counter = counter + 1;
    set(handles.p_counter,'String',counter);
end

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

if limit(row_p,col_p+1) && ~bcolor(row_p,col_p+1)
    s1 = ['get(handles.p' int2str(row_p) int2str(col_p) ',''String'');'];
    stra = eval(s1);
    s2 = ['get(handles.p' int2str(row_p) int2str(col_p+1) ',''String'');'];
    strb = eval(s2);
    temp = stra;
    stra = strb;
    strb = temp;
    s3 = ['set(handles.p' int2str(row_p) int2str(col_p) ',''String'',' stra ');'];
    eval(s3);
    s4 = ['set(handles.p' int2str(row_p) int2str(col_p+1) ',''String'',' strb ');'];
    eval(s4);
    bcolor(row_p,col_p) = 0;
    bcolor(row_p,col_p+1) = 1;
    s5 = ['set(handles.p' int2str(row_p) int2str(col_p) ',''BackgroundColor'',''black'');'];
    eval(s5);
    s6 = ['set(handles.p' int2str(row_p) int2str(col_p+1) ',''BackgroundColor'',''white'')'];
    eval(s6);
    counter = counter + 1;
    set(handles.p_counter,'String',counter);
end

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

if limit(row_p-1,col_p) && ~bcolor(row_p-1,col_p)
    s1 = ['get(handles.p' int2str(row_p) int2str(col_p) ',''String'');'];
    stra = eval(s1);
    s2 = ['get(handles.p' int2str(row_p-1) int2str(col_p) ',''String'');'];
    strb = eval(s2);
    temp = stra;
    stra = strb;
    strb = temp;
    s3 = ['set(handles.p' int2str(row_p) int2str(col_p) ',''String'',' stra ');'];
    eval(s3);
    s4 = ['set(handles.p' int2str(row_p-1) int2str(col_p) ',''String'',' strb ');'];
    eval(s4);
    bcolor(row_p,col_p) = 0;
    bcolor(row_p-1,col_p) = 1;
    s5 = ['set(handles.p' int2str(row_p) int2str(col_p) ',''BackgroundColor'',''black'');'];
    eval(s5);
    s6 = ['set(handles.p' int2str(row_p-1) int2str(col_p) ',''BackgroundColor'',''white'')'];
    eval(s6);
    counter = counter + 1;
    set(handles.p_counter,'String',counter);
end

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

if limit(row_p+1,col_p) && ~bcolor(row_p+1,col_p)
    s1 = ['get(handles.p' int2str(row_p) int2str(col_p) ',''String'');'];
    stra = eval(s1);
    s2 = ['get(handles.p' int2str(row_p+1) int2str(col_p) ',''String'');'];
    strb = eval(s2);
    temp = stra;
    stra = strb;
    strb = temp;
    s3 = ['set(handles.p' int2str(row_p) int2str(col_p) ',''String'',' stra ');'];
    eval(s3);
    s4 = ['set(handles.p' int2str(row_p+1) int2str(col_p) ',''String'',' strb ');'];
    eval(s4);
    bcolor(row_p,col_p) = 0;
    bcolor(row_p+1,col_p) = 1;
    s5 = ['set(handles.p' int2str(row_p) int2str(col_p) ',''BackgroundColor'',''black'');'];
    eval(s5);
    s6 = ['set(handles.p' int2str(row_p+1) int2str(col_p) ',''BackgroundColor'',''white'')'];
    eval(s6);
    counter = counter + 1;
    set(handles.p_counter,'String',counter);
end
guidata(hObject,handles);

function z = limit(row,col)

z1 = 0;
z2 = 0;
if row>0
    if row<5
        z1 = 1;
    end
end
if col>0
    if col<5
        z2 = 1;
    end
end
z = z1 && z2;

% --- Executes on button press in p_setter.
function p_setter_Callback(hObject, eventdata, handles)
global row_p;
global col_p;
global p;
switch p
    case 1
            row_p = 1;
            col_p = 1;
    case 2
            row_p = 1;
            col_p = 2;
    case 3
            row_p = 1;
            col_p = 3;
    case 4
            row_p = 1;
            col_p = 4;
    case 5
            row_p = 2;
            col_p = 1;
    case 6
            row_p = 2;
            col_p = 2;
    case 7
            row_p = 2;
            col_p = 3;
    case 8
            row_p = 2;
            col_p = 4;
    case 9
            row_p = 3;
            col_p = 1;
    case 10
            row_p = 3;
            col_p = 2;
    case 11
            row_p = 3;
            col_p = 3;
    case 12
            row_p = 3;
            col_p = 4;
    case 13
            row_p = 4;
            col_p = 1;
    case 14
            row_p = 4;
            col_p = 2;
    case 15
            row_p = 4;
            col_p = 3;
    case 16
            row_p = 4;
            col_p = 4;
end
guidata(hObject,handles);

% --- Executes on button press in p_win.
function p_win_Callback(hObject, eventdata, handles)
p = zeros(4);
for m=1:1:4
    for n=1:1:4
        s = ['get(handles.p' int2str(m) int2str(n) ',''String'');'];
        p(m,n) = str2double(eval(s));
    end
end
count = 0;
if p(1,1) == 1
    flag = 1;
    count = count + 1;
else flag = 0;
end

if p(1,2) == 2
    flag = 1;
    count = count + 1;
else flag = 0;
end

if p(1,3) == 3
    flag = 1;
    count = count + 1;
else flag = 0;
end

if p(1,4) == 4
    flag = 1;
    count = count + 1;
else flag = 0;
end

if p(2,1) == 5
    flag = 1;
    count = count + 1;
else flag = 0;
end

if p(2,2) == 6
    flag = 1;
    count = count + 1;
else flag = 0;
end

if p(2,3) == 7
    flag = 1;
    count = count + 1;
else flag = 0;
end

if p(2,4) == 8
    flag = 1;
    count = count + 1;
else flag = 0;
end

if p(3,1) == 9
    flag = 1;
    count = count + 1;
else flag = 0;
end

if p(3,2) == 10
    flag = 1;
    count = count + 1;
else flag = 0;
end

if p(3,3) == 11
    flag = 1;
    count = count + 1;
else flag = 0;
end

if p(3,4) == 12
    flag = 1;
    count = count + 1;
else flag = 0;
end

if p(4,1) == 13
    flag = 1;
    count = count + 1;
else flag = 0;
end

if p(4,2) == 14
    flag = 1;
    count = count + 1;
else flag = 0;
end

if p(4,3) == 15
    flag = 1;
    count = count + 1;
else flag = 0;
end

if p(4,4) == 0
    flag = 1;
    count = count + 1;
else flag = 0;
end

time = int2str(round(toc));
set(handles.p_clock,'String',time);
if flag == 1 && count == 16
    msgbox('Congratulations you have won !!!','Fifteen','help');
end
guidata(hObject,handles);

author: Sable

repo: mcbench-benchmarks


text:
%kMenuButton 'MenuButton Object Menuform'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros MenuButton.pane file
%
% Parameters:
% String: label 'Label ', default: ' ': 'label for menubutton'
%
% Example: kMenuButton( {'label',' '})
%
% Khoros helpfile follows below:
%
% .begin tagged
%
% .item "The Menubutton GUI Object"
% The Khoros menubutton object is used on Khoros graphical user interfaces
% whenever a pulldown menu is needed;  clicking on the menubutton will display
% the pulldown menu.
%
% .item "Label"
% The (optional) text that is displayed by the menubutton object.  A menubutton
% object will a pixmap to the right of the label.  This pixmap indicates that it
% is a menubutton, and whether clicking on it will display a pulldown menu
% (indicated by an arrow that points down) or a walking menu (indicated by
% an arrow that points to the right).
%
% .item "Font"
% The font in which the label for the menubutton will appear.
%
% .item "Foreground Color"
% The color in which the text for the label will appear.
%
% .item "Background Color"
% The color in which the background of the menubutton will appear.
% .end tagged

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

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

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
%RGBINT2HEX Convert RGB integer into hexadecimal colour
%   HEX = RGBINT2HEX(INT) given an RGB integer, convert it into a
%   hexadecimal string.
%
%   This is a helper function which you can use when manually creating your
%   own MATLAB colour schemes. It is the inverse of COLOR2JAVARGBINT.
%
%   See also COLOR2JAVARGBINT.

% Copyright (c) 2015-2016,  Scott C. Lowe <scott.code.lowe@gmail.com>
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * 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 OWNER 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 hex = RGBint2hex(int)

% Make a Java colour object
jc = java.awt.Color(int);
% Convert R,G,B into hexadecimal
hex = sprintf('%02s', ...
    dec2hex(jc.getRed), dec2hex(jc.getGreen), dec2hex(jc.getBlue));

end

author: scottclowe

repo: matlab-schemer


text:
function [D] = wishart_kl (arg1,arg2,arg3,arg4)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   [D] = wishart_kl (B_q,B_p,alpha_q,alpha_p)
%
%   computes the divergence
%                /
%      D(q||p) = | q(x)*log(q(x)/p(x)) dx
%               /
%   between two k-dimensional Wishart propability density for C  given
%   scale matrix B and shape parameter alpha
%
%            alpha
%         |B|              alpha-(k+1)/2
%   p(x)= ------------- |C|              exp (-tr(BC))
%         Gamma (alpha)
%              k
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin == 4
    B_q = arg1; B_p = arg2; alpha_q = arg3; alpha_p = arg4;
elseif nargin == 2
    B_q = arg1.Gam_rate; alpha_q = arg1.Gam_shape;
    B_p = arg2.Gam_rate; alpha_p = arg2.Gam_shape;
else
    error('Incorrect number of input arguments');
end

if size(B_q)~=size(B_p)
  error('Distributions must have equal dimensions');
end

K=size(B_p,1);

try
    Lq = -logdet(B_q,'chol');
    Lp = -logdet(B_p,'chol');
catch
    disp('One of the two covariance matrices (or both) is not positive definite')
    disp('Check for NaNs in the time series. Also, are there enough time points?')
    error('Error computing the inverse of the covariance matrix.')
end

lZq = log(2) * (alpha_q*K/2)  - Lq * (-alpha_q/2) + K*(K-1)/4 * log(pi);
lZp = log(2) * (alpha_p*K/2)  - Lp * (-alpha_p/2) + K*(K-1)/4 * log(pi);

Lq = Lq + K * log(2);
Lp = Lp + K * log(2);

for k = 1:K
    lZq = lZq + gammaln(alpha_q/2+0.5-0.5*k);
    lZp = lZp + gammaln(alpha_p/2+0.5-0.5*k);
    Lq = Lq + psi(alpha_q/2+0.5-0.5*k);
    Lp = Lp + psi(alpha_p/2+0.5-0.5*k);
end

D = (alpha_q/2-0.5-0.5*K)*Lq - (alpha_p/2-0.5-0.5*K)*Lp ...
    - alpha_q * K / 2 + alpha_q * trace(B_p / B_q) / 2 + lZp - lZq;

return;

author: OHBA-analysis

repo: HMM-MAR


text:
function [ x, seed ] = hyperball01_sample ( m, n, seed )

%*****************************************************************************80
%
%% HYPERBALL01_SAMPLE uniformly samples the unit hyperball.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    05 January 2014
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Russell Cheng,
%    Random Variate Generation,
%    in Handbook of Simulation,
%    edited by Jerry Banks,
%    Wiley, 1998, pages 168.
%
%    Reuven Rubinstein,
%    Monte Carlo Optimization, Simulation, and Sensitivity
%    of Queueing Networks,
%    Krieger, 1992,
%    ISBN: 0894647644,
%    LC: QA298.R79.
%
%  Parameters:
%
%    Input, integer M, the spatial dimension.
%
%    Input, integer N, the number of points.
%
%    Input/output, integer SEED, a seed for the random
%    number generator.
%
%    Output, real X(M,N), the points.
%
  x = randn ( m, n );
  norm = ones ( 1, m ) * ( x.^2 );
  norm = sqrt ( norm );
  for i = 1 : m
    x(i,1:n) = x(i,1:n) ./ norm(1:n);
  end

  for j = 1 : n
    r = rand ( 1, 1 );
    x(1:m,j) = r ^ ( 1.0 / m ) * x(1:m,j);
  end

  return
end


text:
function newval = e2i_data(mpc, val, ordering, dim)
%E2I_DATA   Converts data from external to internal indexing.
%
%   VAL = E2I_DATA(MPC, VAL, ORDERING)
%   VAL = E2I_DATA(MPC, VAL, ORDERING, DIM)
%
%   When given a case struct that has already been converted to
%   internal indexing, this function can be used to convert other data
%   structures as well by passing in 2 or 3 extra parameters in
%   addition to the case struct. If the value passed in the 2nd
%   argument is a column vector or cell array, it will be converted
%   according to the ORDERING specified by the 3rd argument (described
%   below). If VAL is an n-dimensional matrix or cell array, then the
%   optional 4th argument (DIM, default = 1) can be used to specify
%   which dimension to reorder. The return value in this case is the
%   value passed in, converted to internal indexing.
%
%   The 3rd argument, ORDERING, is used to indicate whether the data
%   corresponds to bus-, gen- or branch-ordered data. It can be one
%   of the following three strings: 'bus', 'gen' or 'branch'. For
%   data structures with multiple blocks of data, ordered by bus,
%   gen or branch, they can be converted with a single call by
%   specifying ORDERING as a cell array of strings.
%
%   Any extra elements, rows, columns, etc. beyond those indicated
%   in ORDERING, are not disturbed.
%
%   Examples:
%       A_int = e2i_data(mpc, A_ext, {'bus','bus','gen','gen'}, 2);
%
%       Converts an A matrix for user-supplied OPF constraints from
%       external to internal ordering, where the columns of the A
%       matrix correspond to bus voltage angles, then voltage
%       magnitudes, then generator real power injections and finally
%       generator reactive power injections.
%
%       gencost_int = e2i_data(mpc, gencost_ext, {'gen','gen'}, 1);
%
%       Converts a GENCOST matrix that has both real and reactive power
%       costs (in rows 1--ng and ng+1--2*ng, respectively).
%
%   See also I2E_DATA, E2I_FIELD, EXT2INT.

%   MATPOWER
%   Copyright (c) 2009-2016, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

if ~isfield(mpc, 'order')
    error('e2i_data: mpc does not have the ''order'' field required to convert from external to internal numbering.');
end
o = mpc.order;
if o.state ~= 'i'
    error('e2i_data: mpc does not have internal ordering data available, call ext2int first');
end
if nargin < 4
    dim = 1;
end
if ischar(ordering)         %% single set
    if strcmp(ordering, 'gen')
        idx = o.(ordering).status.on(o.(ordering).i2e);
    else
        idx = o.(ordering).status.on;
    end
    newval = get_reorder(val, idx, dim);
else                        %% multiple sets
    b = 0;  %% base
    for k = 1:length(ordering)
        n = size(o.ext.(ordering{k}), 1);
        v = get_reorder(val, b+(1:n), dim);
        new_v{k} = e2i_data(mpc, v, ordering{k}, dim);
        b = b + n;
    end
    n = size(val, dim);
    if n > b                %% the rest
        v = get_reorder(val, b+1:n, dim);
        new_v{length(new_v)+1} = v;
    end
    newval = cat(dim, new_v{:});
end

author: MATPOWER

repo: matpower

save_path: github-repos/MATLAB/MATPOWER-matpower


text:
function geometry_test027 ( )

%*****************************************************************************80
%
%% TEST027 tests ELLIPSE_POINTS_ARC_2D.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  n = 13;
  dim_num = 2;

  center(1:dim_num) = [ 5.0, -2.0 ];
  r1 = 3.0;
  r2 = 1.0;
  psi = pi / 6.0;
  theta1 = pi / 2.0;
  theta2 = 2.0 * pi;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST027\n' );
  fprintf ( 1, '  ELLIPSE_POINTS_ARC_2D returns points on an\n' );
  fprintf ( 1,'     elliptical arc.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  The ellipse has center %f  %f\n', center(1:dim_num) );
  fprintf ( 1, '  radii R1 = %f, R2 = %f\n', r1, r2 );
  fprintf ( 1, '  and angle PSI = %f\n', psi );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  The arc extends from THETA1 = %f\n', theta1 );
  fprintf ( 1, '  to THETA2 = %f\n', theta2 );

  p = ellipse_points_arc_2d ( center, r1, r2, psi, theta1, theta2, n );

  r8mat_transpose_print ( dim_num, n, p, '  Sample points:' );

  return
end


text:
function r8mat_plot ( m, n, a, title )

%*****************************************************************************80
%
%% R8MAT_PLOT "plots" an R8MAT.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 September 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the number of rows in A.
%
%    Input, integer N, the number of columns in A.
%
%    Input, real A(M,N), the matrix.
%
%    Input, string TITLE, a title.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '%s\n', title );

  for jlo = 1 : 70 : n

    jhi = min ( jlo + 70-1, n );
    fprintf ( 1, '\n' );
    fprintf ( 1, '          ' );
    for j = jlo : jhi
      fprintf ( 1, '%d', mod ( j, 10 ) );
    end
    fprintf ( 1, '\n' );
    fprintf ( 1, '\n' );

    for i = 1 : m
      fprintf ( 1, '%6d    ', i );
      for j = jlo : jhi
        fprintf ( 1, '%c', r8mat_plot_symbol ( a(i,j) ) );
      end
      fprintf ( 1, '\n' );
    end
  end

  return
end


text:
classdef DotProduct < dagnn.ElementWise

    properties (Transient)
        numInputs
    end

    methods
        function outputs = forward(obj, inputs, params)
            obj.numInputs = numel(inputs) ;
            outputs{1} = inputs{1} ;
            for k = 2:obj.numInputs
                outputs{1} = outputs{1} .* inputs{k} ;
            end
        end

        function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)
            for k = 1:obj.numInputs
                derInputs{k} = derOutputs{1} ;
                for ko = 1:obj.numInputs
                    if ko ~= k
                        derInputs{k} = derInputs{k} .* inputs{ko};
                    end
                end
            end
            derParams = {} ;
        end

        function outputSizes = getOutputSizes(obj, inputSizes)
            outputSizes{1} = inputSizes{1} ;
            for k = 2:numel(inputSizes)
                if all(~isnan(inputSizes{k})) && all(~isnan(outputSizes{1}))
                    if ~isequal(inputSizes{k}, outputSizes{1})
                        warning('DotProduct layer: the dimensions of the input variables is not the same.') ;
                    end
                end
            end
        end

        function rfs = getReceptiveFields(obj)
            numInputs = numel(obj.net.layers(obj.layerIndex).inputs) ;
            rfs.size = [1 1] ;
            rfs.stride = [1 1] ;
            rfs.offset = [1 1] ;
            rfs = repmat(rfs, numInputs, 1) ;
        end

        function obj = DotProduct(varargin)
            obj.load(varargin) ;
        end
    end
end

author: aimerykong


text:
function varargout = hikmeans(varargin)
% VL_HIKMEANS  Hierachical integer K-means
%   [TREE,ASGN] = VL_HIKMEANS(DATA,K,NLEAVES) applies recursive integer
%   K-menas to cluster the data DATA, returing a structure TREE
%   representing the clusters and a vector ASGN with the data to
%   cluster assignments. The depth of the recursive partition is
%   computed so that at least NLEAVES are generated.
%
%   VL_HIKMEANS() is built on top of VL_IKMEANS() and requires the data to
%   be of class UINT8.
%
%   TREE is a structure representing the hierarchical clusters.  Each
%   node of the tree is also a structure with fields:
%
%   DEPTH::
%     Depth of the tree (only at the root node)
%
%   CENTERS::
%     K cluster centers
%
%   SUB::
%     Array of K node structures representing subtrees
%     (this field is missing at leaves).
%
%   ASGN is a matrix with one column per datum and height equal to the
%   depth of the tree. Each column encodes the branch of the tree that
%   correspond to each datum.
%
%   Example::
%     ASGN(:,7) = [1 5 3] means that the tree as depth equal to 3 and
%     that the datum X(:,7) corresponds to the branch
%     ROOT->SUB(1)->SUB(5)->SUB(3).
%
%   See also: VL_HIKMEANSPUSH(), VL_HIKMEANSHIST(), VL_IKMEANS(), VL_HELP().
[varargout{1:nargout}] = vl_hikmeans(varargin{:});

author: jianxiongxiao

repo: ProfXkit