function f = fast_specific_rhs(x,y,nel)
%zero_rhs   zero RHS forcing function
%   f = specific_rhs(x,y,nel)
%   input
%          x          x coordinate vector
%          y          y coordinate vector
%          nel        number of elements
%   IFISS function: DJS; 28 February 2005.
% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage
f=zeros(nel,1);
return


function candoit = canGetHessian(problem)
% Checks whether the Hessian can be computed for a problem structure.
%
% function candoit = canGetHessian(problem)
%
% Returns true if the Hessian of the cost function can be computed given
% the problem description, false otherwise.
%
% See also: canGetCost canGetDirectionalDerivative canGetGradient

% This file is part of Manopt: www.manopt.org.
% Original author: Nicolas Boumal, Dec. 30, 2012.
% Contributors:
% Change log:

    candoit = isfield(problem, 'hess') || ...
              (isfield(problem, 'ehess') && canGetEuclideanGradient(problem));

    if ~candoit && ...
           (isfield(problem, 'ehess') && ~canGetEuclideanGradient(problem))
        warning('manopt:canGetHessian', ...
               ['If the Hessian is supplied as a Euclidean Hessian (ehess), ' ...
                'then the Euclidean gradient must also be supplied (egrad).']);
    end

end


function [ s, varargout ] = size( x, dim )

%   Disciplined convex/geometric programming information for SIZE:
%       SIZE imposes no convexity restrictions on its first argument.
%       The second argument, if supplied, must be a positive integer.

s = x.size_;
if nargin > 1,
    if nargout > 1,
        cvx_throw( 'Too many output arguments.' );
    elseif ~isnumeric( dim ) || length( dim ) ~= 1 || dim <= 0 || dim ~= floor( dim ),
        cvx_throw( 'Dimension argument must be a positive integer scalar.' );
    elseif dim > length( s ),
        s = 1;
    else
        s = s(dim);
    end
elseif nargout > 1,
    no = nargout;
    s( end + 1 : no ) = 1;
    s( no ) = prod( s( no : end ) );
    for k = 2 : no,
        varargout{k-1} = s(k); %#ok
    end
    s = s(1);
end

% Copyright 2005-2014 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function [st] = getTimeStr()
    c = clock();
    MM = num2str(c(2) + 100); MM = MM(2:end);
    dd = num2str(c(3) + 100); dd = dd(2:end);
    hh = num2str(c(4) + 100); hh = hh(2:end);
    mm = num2str(c(5) + 100); mm = mm(2:end);
    ss = num2str(round(c(6)) + 100); ss = ss(2:end);

    st = strcat(MM,dd, '_', hh, mm, ss);
    fprintf('Time now: %s/%s/%4d - %s:%s:%s\n', MM, dd, c(1), hh, mm, ss);
    % if nargin == 2

end


%% SPARSE_POOL uses the MATLABPOOL command to run the SPARSE_FUN function.
%
%  Discussion:
%
%    Output printed by the function appears directly on the screen.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 May 2012
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SPARSE_POOL\n' );
  fprintf ( 1, '  Call SPARSE_FUN to create a sparse matrix in parallel.\n' );

  matlabpool ( 'open', 'local', 4 )

  tic
  A_sparse = sparse_fun ( );
  toc

  matlabpool ( 'close' )
%
%  Display the pattern of the sparse matrix.
%
  spy ( A_sparse );


function [ t_stop, y_stop ] = p33_stop ( neqn )

%*****************************************************************************80
%
%% P33_STOP returns the stopping point for problem p33.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NEQN, the number of equations.
%
%    Output, real T_STOP, Y_STOP(NEQN), the final data.
%
  y_stop = zeros ( neqn, 1 );

  t_stop = 20.0;
  y_stop = [ ...
    0.756245; ...
    2.67294 ];

  return
end


function varn = detVarNames(svar)
%Determine variable names, in order, index free
%e.g. [ h1, h2, m1, m2, m3] becomes {h [1 2]; m [3 4 5]}

%Initialize
varn = []; k = 1;
%Search each var
for i = 1:length(svar)
    str = char(svar(i)); found = 0;
    for j = 1:length(str)
        if(uint8(str(j)) < 65 || uint8(str(j)) > 126)
            found = 1;
            break; %found a number, assume end of name
        end
    end
    %If we found it, remove number (last index found)
    if(found)
        nvar = str(1:j-1); %New variable name
    else
        nvar = str;
    end
    %See where to place it
    if(isempty(varn))
        varn = {nvar i};
        k = k + 1;
    elseif(strcmp(varn{k-1,1},nvar)) %same as old one
        varn{k-1,2} = [varn{k-1,2} i]; %#ok<AGROW>
    else %new one
        varn = [varn; {nvar} i]; %#ok<AGROW>
        k = k + 1;
    end
end


function [output1, output2] = functionTemplate(model, arg1, optArg1, optArg2, optArg3)
% (Description of the function) Template for a main utility function for
% the COBRA toolbox. Allow passing COBRA-toolbox-wide parameters (e.g., feasTol, optTol, printLevel)
% and solver-specific parameter structure (e.g., struct('lpmethod', 1) for Cplex, struct('Presolve', 1) for Gurobi)
% to the function and other functions called by the function.
%
% USAGE:
%     (positional argument inputs)
%     [output1, output2] = functionTemplate(model, arg1, optArg1, optArg2, optArg3, solverParams)
%     (positional + name/value argument inputs)
%     [output1, output2] = functionTemplate(model, arg1, 'name', value, ..., solverParams)
%     (parameter structure input)
%     [output1, output2] = functionTemplate(model, ..., paramStruct)
%
% INPUT(S):
% (must be inputted as positional arguments)
%     model:               COBRA model
%     arg1:                argument 1
%
% OPTIONAL INPUT(S):
% (can be inputted as positional arguments, or name/value arguments, or a single parameter structure)
%     optArg1:            optional argument 1
%     optArg2:            optional argument 2
%     optArg3:            optional argument 3
%     ...
%
% OUTPUT(S):
%     output1:            output argument 1
%     output2:            output argument 2
%
% EXAMPLE:
%
% NOTE:
%
% Author(s):
%

% optional arguments that can be inputted as positional arguments,
% name/value arguments, or parameter structure, in the same order as
% specified in USAGE
optArgin =      {'optArg1', 'optArg2', 'optArg3'};
% defaultValues for the optional arguments above
defaultValues = {1,         'test',    {'test'}};
% validators for the optional arguments above, i.e., the inputs when passed
% to the validators must return true
validator = {...
    @(x) isscalar(x) & isnumeric(x) & x >= 0, ... % optArg1 (must be non-negative numbers)
    @ischar, ...                                  % optArg2 (must be character)
    @(x) true, ...                                % optArg3 (accept anything)
    };

% types of optimization problems to be solved in this function and the
% functions called by this function
problemTypes = {'LP', 'QP'};

% provide the optional argument name for the solver-specific parameter
% structure (to be passed to solvers like Cplex, Gurobi in e.g., solveCobraLP)
% This is intended for backward compatibility only and NOT RECOMMENDED TO USE
% because as a convention among cobra functions, solver-specific parameter
% structure can be inputted without keyword
keyForSolverParams = '';

% treat empty inputs ([]) for positional arguments as using default values or not.
% For example, if emptyForDefault = true, functionTemplate(model, [], 'test')
% takes arg1 as the default value 1. But if emptyForDefault = false, this
% returns error since '[]' does not pass the validator @(x) isscalar(x) & isnumeric(x) & x >= 0
emptyForDefault = true;

% run the input parser to get (1) function arguments, (2) cobra parameters
% and (3) solver-specific parameters
[funParams, cobraParams, solverVarargin] = parseCobraVarargin(varargin, ...
    optArgin, defaultValues, validator, problemTypes, keyForSolverParams, emptyForDefault);

% get all the optional function arguments
[optArg1, optArg2, optArg3] = deal(funParams{:});

%%%%% Do what you want to do with the function. For example, construct
%%%%% optimization problems and solve

LPproblem = struct();
[LPproblem.A, LPproblem.b, LPproblem.c, LPproblem.lb, LPproblem.ub, ...
    LPproblem.osense, LPproblem.csense] = deal(speye(2), [1; 1], [1; 0], ...
    [0; 0], [1; 1], -1, 'LL');

% pass the solver-specific parameters to optimization problem
% make sure to use {:}
solLP = solveCobraLP(LPproblem, solverVarargin.LP{:});
LPproblem.F = speye(2);
solQP = solveCobraQP(LPproblem, solverVarargin.QP{:});

% use the cobra parameters (e.g., manually check feasibility)
if ~(checkSolFeas(solLP) <= cobraParams.LP.feasTol)
    [output1, output2] = deal(0);
else
    [output1, output2] = deal(1);
end

help functionTemplate

end


% Special wrapper to regular plot
% Works on regularly sampled data
% When there is a gap of data, it insert a nan value
% to avoid linear interpolation of the data
%
% INPUT
%   t           column array of epochs
%   data        columns of data (could be a matrix)
%   varagin     add other useful parameters of the plot
%
% SYNTAX
%   Core_Utils.plotSep(t, data, varagin);
%
% SEE ALSO
%   plot

%--------------------------------------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0 beta 5
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  Written by:       Andrea Gatti
%  Contributors:     ...
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%    This program is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    This program is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------

function lh = plotSep(t, data, varargin)
    if not(isempty(data))
        if isa(t, 'handle')
            ax = t;
            t = data;
            data = varargin{1};
            varargin = varargin{2:end};
        else
            ax = gca;
        end
        try
            if numel(t) ~= numel(data) && numel(t) ~= size(data, 1)
                % this means that there is only one data parameter and no time
                varargin = [{data} varargin];
                data = t;
                if size(data, 1) == 1
                    % I want the data to be columnwise
                    data = data';
                end
                t = 1 : size(data, 1);
            else
                if size(data, 1) == 1
                    % I want the data to be columnwise
                    data = data';
                end
            end
        catch
            % probably data is undefined
            data = t;
            if size(data, 1) == 1
                % I want the data to be columnwise
                data = data';
            end
            t = (1 : size(data, 1))';
        end
        for c = 1 : size(data, 2)
            if numel(data) == numel(t)
                [t_col, data_col] = insertNan4Plots(t(:,c), data(:,c));
            else
                [t_col, data_col] = insertNan4Plots(t, data(:,c));
            end
            if isempty(varargin)
                lh = plot(ax, t_col, data_col);
            else
                lh = plot(ax, t_col, data_col, varargin{:});
            end
            hold on;
        end
    end
end

function [t, data_set] = insertNan4Plots(t, data_set)
    % Insert a Nan in a regularly sampled dataset to make
    % plots interrupt continuous lines
    %
    % INPUT
    %   t      epoch of the data [matrix of column arrays]
    %   data   epoch of the data [matrix of column arrays]
    %
    % SYNTAX
    %   [t, data] = Core_Utils.insertNan4Plots(t, data)

    t = t(:);
    if size(t, 1) ~= size(data_set, 1)
        % data should be a column array
        data_set = data_set';
    end
    n_set = size(data_set, 2);
    dt = diff(t);
    rate = median(dt);
    id_in = find(dt > 1.5 * rate);
    for x = numel(id_in) : -1 : 1
        t = [t(1 : id_in(x)); (t(id_in(x)) + 1.5 * rate); t((id_in(x)+1) : end)];
        data_set = [data_set(1 : id_in(x), :); nan(1, n_set); data_set((id_in(x)+1) : end, :)];
    end
end


function [scan3dd] = elec_load_scan_3ddasc(filename)

% elec_load_scan_3ddasc - read ascii export of Neuroscan 3DD file
%
% Load an ascii electrode file and return
% the electrode labels and coordinates.  This
% function can read and return Cartesian (x,y,z)
% and/or spherical (theta,phi,r) coordinates.
%
% [scan3dd] = elec_load_scan_3ddasc(filename)
%
% where:
%
% file = '<path><filename>' with row format '%s %d %f %f %f'
%
% The file format is that of NeuroScan 3Dspace ascii
% export files.  Each row of the file comprises an electrode label,
% an electrode type code (see below), and the x,y,z coordinates (cm).
% Each field is separated by spaces.  For example,
%
% Fz    69  Xcm Ycm Zcm
%
% Example result:
%
% scan3dd =
%
%      label: {1x128 cell}
%          x: [128x1 double]
%          y: [128x1 double]
%          z: [128x1 double]
%        hsp: [1617x3 double]
%     nasion: [-0.0333 9.0341 0]
%        lpa: [-6.9128 0 0]
%        rpa: [6.9128 0 0]
%     origin: [0 0 0]
%        ref: [0 9.9341 0]
%
% All coordinates are in centimeters; +X is right, +Y is anterior
% and +Z is superior.
%
% Notes:
%
% i) Type is defined as follows (from Neuroscan 3Dspace ascii export):
%
%           Electrode               Type
%           ---------               ----
%           Nasion                   110 (or 78)
%           Left                     108 (or 76)
%           Right                    114 (or 82)
%           electrodes                69
%           Centroid (origin)         99 (or 67; eg <0,0,0>)
%           Ref                      120 (or 88)
%           Scalp Points (hsp)        32
%
%

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

% Licence:  GNU GPL, no express or implied warranties
% History:  08/1999, Darren.Weber_at_radiology.ucsf.edu
%           08/2003, Darren.Weber_at_radiology.ucsf.edu
%                    complete rewrite, replacing elec_load.m
%                    new version of 3Dspace exports different type numbers ;-)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

ver = '$Revision: 1.1 $';
fprintf('\nELEC_LOAD_SCAN_3DDASC [v %s]\n',ver(11:15));

tic;

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

fprintf('...loading electrodes from:\n\t%s\n', file);

scan3dd = read_3dd(file);

fprintf('...loaded %d electrodes\n', size(scan3dd.x,1));

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

return

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function scan3dd = read_3dd(file),

scan3dd.label = [];
scan3dd.x = [];
scan3dd.y = [];
scan3dd.z = [];
scan3dd.hsp = [];

fid = fopen(file);
if fid < 0,
  msg = sprintf('cannot open file: %s\n',file);
  error(msg);
end

% 3DD ascii files contain position information for
% fiducial, sensor, and head shape fields.

% First get the fiducial points by reading the whole file
% (clumsy, but exhaustive search for field indicators).

% Fiducial points are required for MRI registration. They are
% the nasion, left and right preauricular points, eg:

%      Nasion	78	-0.033340	9.034104	0.000000
%      Left	76	-6.912818	-0.000000	0.000000
%      Right	82	6.912818	0.000000	-0.000000

fprintf('...searching for fiducials...');

n = 0;
while n < 5,
  tmp = fgetl(fid);
  if tmp < 0, break; end

  tmp = lower(tmp);

  if strfind(tmp,'nasion'),
    tmp = sscanf(tmp,'%s %d %f %f %f');
    scan3dd.nasion = [tmp(end-2) tmp(end-1) tmp(end)];
    n = n + 1;
    continue;
  end
  if strfind(tmp,'left'),
    tmp = sscanf(tmp,'%s %d %f %f %f');
    scan3dd.lpa = [tmp(end-2) tmp(end-1) tmp(end)];
    n = n + 1;
    continue;
  end
  if strfind(tmp,'right'),
    tmp = sscanf(tmp,'%s %d %f %f %f');
    scan3dd.rpa = [tmp(end-2) tmp(end-1) tmp(end)];
    n = n + 1;
    continue;
  end
  if strfind(tmp,'centroid'),
    tmp = sscanf(tmp,'%s %d %f %f %f');
    scan3dd.origin = [tmp(end-2) tmp(end-1) tmp(end)];
    n = n + 1;
    continue;
  end
  if strfind(tmp,'ref'),
    tmp = sscanf(tmp,'%s %d %f %f %f');
    scan3dd.ref = [tmp(end-2) tmp(end-1) tmp(end)];
    n = n + 1;
    continue;
  end
end

frewind(fid);
fprintf('done\n');

fprintf('...searching for electrodes...');

ok = 1;
while ok,
  tmp = fgetl(fid);
  if tmp < 0, break; end

  if strfind(lower(tmp),'nasion'),   continue; end
  if strfind(lower(tmp),'left'),     continue; end
  if strfind(lower(tmp),'right'),    continue; end
  if strfind(lower(tmp),'centroid'), continue; end
  if strfind(lower(tmp),'ref'),      continue; end

  tmp = sscanf(tmp,'%s %d %f %f %f');

  if tmp(end-3) == 69,
    scan3dd.label{end+1} = char(tmp(1:end-4))';
    scan3dd.x(end+1,1) = tmp(end-2);
    scan3dd.y(end+1,1) = tmp(end-1);
    scan3dd.z(end+1,1) = tmp(end);
    continue;
  end
  if strfind(char(tmp(1:end-4))','32'),
    break;
    % found a head shape point
    scan3dd.hsp(end+1,:) = [tmp(end-2),tmp(end-1),tmp(end)];
    continue;
  end
end

frewind(fid);
fprintf('done\n');

fprintf('...searching for head shape points...');

ok = 1;
while ok,
  tmp = fgetl(fid);
  if tmp < 0, break; end

  if strfind(lower(tmp),'nasion'),   continue; end
  if strfind(lower(tmp),'left'),     continue; end
  if strfind(lower(tmp),'right'),    continue; end
  if strfind(lower(tmp),'centroid'), continue; end
  if strfind(lower(tmp),'ref'),      continue; end
  if strfind(lower(tmp),'69'),       continue; end

  tmp = sscanf(tmp,'%d %f %f %f');

  if tmp(end-3) == 32,
    % found a head shape point
    scan3dd.hsp(end+1,:) = [tmp(end-2),tmp(end-1),tmp(end)];
    continue;
  end
end

frewind(fid);
fprintf('done\n');

fclose(fid);

return


% MP_INTERFACE_HCURL: create a global numbering of basis functions in multipatch domains, assigning the correct orientation for tangential traces.
%
%   [glob_num, glob_ndof, dofs_ornt] = mp_interface_hcurl (interfaces, sp);
%
% INPUT:
%
%  interfaces: structure with the information of the interfaces between patches (see mp_geo_read_file)
%  sp:         object representing the space of discrete functions, with the curl-preserving transform (see sp_vector)
%
% OUTPUT:
%
%  glob_num:  global numbering of the discrete basis functions
%  glob_ndof: total number of degrees of freedom
%  dofs_ornt: a cell-array with the orientation of the basis functions
%
% Copyright (C) 2010, 2011, 2015 Rafael Vazquez
%
%    This program is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.

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

function [glob_num, glob_ndof, dofs_ornt] = mp_interface_hcurl (interfaces, sp)

  npatch = numel (sp);

  ndim = size (sp{1}.ndof_dir, 2);

  if (~isempty (interfaces))
    glob_num   = cell (npatch, 1);
    dofs_ornt  = cell (npatch, 1);
% patch_intrfc is only used for ndim == 3
    patch_intrfc = cell (npatch, 1);

    ttform = cell (ndim-1, npatch, numel (interfaces));
    ppnum  = cell (ndim-1, numel (interfaces));

    for iptc = 1:npatch
      glob_num{iptc} = zeros (1, sp{iptc}.ndof);
      dofs_ornt{iptc} = ones (1, sp{iptc}.ndof);
      patch_intrfc{iptc} = union (find([interfaces.patch1] == iptc), ...
                                  find([interfaces.patch2] == iptc));
    end

    for intrfc = 1:numel(interfaces)
      iptc1  = interfaces(intrfc).patch1;
      iptc2  = interfaces(intrfc).patch2;
      iside1 = interfaces(intrfc).side1;
      iside2 = interfaces(intrfc).side2;
      for idim = 1:ndim-1
        ttform{idim,iptc1, intrfc} = sp{iptc1}.boundary(iside1).dofs(sp{iptc1}.boundary(iside1).comp_dofs{idim});
        nghbr_dofs{idim} = reshape (sp{iptc2}.boundary(iside2).dofs(sp{iptc2}.boundary(iside2).comp_dofs{idim}), ...
				    [sp{iptc2}.boundary(iside2).ndof_dir(idim,:), 1]);
      end
      if (ndim == 2)
        if (interfaces(intrfc).ornt == -1)
          nghbr_dofs{1} = flipud (nghbr_dofs{1});
        end
      elseif (ndim == 3)
        if (interfaces(intrfc).flag == -1)
          aux = nghbr_dofs{1};
          nghbr_dofs{1} = nghbr_dofs{2}';
          nghbr_dofs{2} = aux';
        end
        if (interfaces(intrfc).ornt1 == -1)
          nghbr_dofs{1} = flipud (nghbr_dofs{1});
          nghbr_dofs{2} = flipud (nghbr_dofs{2});
        end
        if (interfaces(intrfc).ornt2 == -1)
          nghbr_dofs{1} = fliplr (nghbr_dofs{1});
          nghbr_dofs{2} = fliplr (nghbr_dofs{2});
        end
      end
      for idim = 1:ndim-1
        ttform{idim,iptc2, intrfc} = nghbr_dofs{idim}(:)';
        ppnum{idim,intrfc} = zeros (1, numel(sp{iptc1}.boundary(iside1).comp_dofs{idim}));
      end
    end

    glob_ndof = 0;
% We start with the dofs that do not belong to any interface
    for iptc = 1:npatch
      non_intrfc_dofs = setdiff(1:sp{iptc}.ndof, [ttform{:,iptc,:}]);
      glob_num{iptc}(non_intrfc_dofs) = glob_ndof + (1:numel(non_intrfc_dofs));
      glob_ndof = glob_ndof + numel (non_intrfc_dofs);
    end

% Then we set the interfaces
    for intrfc = 1:numel(interfaces)
      iptc     = interfaces(intrfc).patch1;
      iptc2    = interfaces(intrfc).patch2;

      for idim = 1:ndim-1
        new_dofs{idim} = find (glob_num{iptc}(ttform{idim, iptc, intrfc}) == 0);
        new_dofs_number = glob_ndof + (1:numel (new_dofs{idim}));
        glob_num{iptc}(ttform{idim, iptc, intrfc}(new_dofs{idim})) = new_dofs_number;
        dofs_ornt{iptc}(ttform{idim, iptc, intrfc}(new_dofs{idim})) = 1;
        ppnum{idim,intrfc}(new_dofs{idim}) = new_dofs_number;
        glob_ndof = glob_ndof + numel (new_dofs{idim});
      end

      if (ndim == 2)
        glob_num{iptc2}(ttform{1, iptc2, intrfc}) = ...
             glob_num{iptc}(ttform{1, iptc, intrfc});
        dofs_ornt{iptc2}(ttform{1, iptc2, intrfc}) = ...
             interfaces(intrfc).ornt * dofs_ornt{iptc}(ttform{1, iptc, intrfc});
      elseif (ndim == 3)
        [glob_num, dofs_ornt, ppnum] = set_same_interface (iptc, intrfc, ...
            ttform, new_dofs, interfaces, glob_num, dofs_ornt, ppnum, patch_intrfc);
        [glob_num, dofs_ornt, ppnum] = set_same_patch (iptc, intrfc, ...
            ttform, new_dofs, interfaces, glob_num, dofs_ornt, ppnum, patch_intrfc);

      end
    end

  else
    glob_ndof = 0;
    glob_num = cell (npatch, 1);
    dofs_ornt  = cell (npatch, 1);
    for iptc = 1:npatch
      glob_num{iptc} = glob_ndof + (1:sp{iptc}.ndof);
      glob_ndof = glob_ndof + sp{iptc}.ndof;
      dofs_ornt{iptc} = ones (1, sp{iptc}.ndof);
    end
  end

end

function [glob_num, dofs_ornt, ppnum] = set_same_patch (iptc, intrfc, ...
            ttform, new_dofs, interfaces, glob_num, ...
            dofs_ornt, ppnum, patch_intrfc);

  for idim = 1:size(ttform, 1)
    intrfc_dofs{idim} = ttform{idim, iptc, intrfc}(new_dofs{idim});
  end

  for ii = setdiff (patch_intrfc{iptc}, intrfc)
    for idim = 1:size(ttform, 1)
      jdim = mod (idim, 2) + 1;
      [~, pos1{idim}, pos2{idim}] = intersect (ttform{idim, iptc, ii}, intrfc_dofs{idim});
      not_set_p1{idim} = find (ppnum{idim,ii}(pos1{idim}) == 0);

      [~, pos1b{idim}, pos2b{jdim}] = ...
          intersect (ttform{idim, iptc, ii}, intrfc_dofs{jdim});
      not_set_p1b{idim} = find (ppnum{idim, ii}(pos1b{idim}) == 0);
    end

    if (~(all (cellfun (@isempty, not_set_p1))))
      for idim = 1:size(ttform, 1)
        ppnum{idim,ii}(pos1{idim}(not_set_p1{idim})) = ...
          ppnum{idim,intrfc}(new_dofs{idim}(pos2{idim}(not_set_p1{idim})));
        renew_dofs{idim} = pos1{idim}(not_set_p1{idim});
      end
      [glob_num, dofs_ornt, ppnum] = set_same_interface (iptc, ii, ...
          ttform, renew_dofs, interfaces, glob_num, dofs_ornt, ppnum, patch_intrfc);
    elseif (~(all (cellfun (@isempty, not_set_p1b))))
      for idim = 1:size(ttform, 1)
        jdim = mod (idim, 2) + 1;
        ppnum{idim,ii}(pos1b{idim}(not_set_p1b{idim})) = ...
          ppnum{jdim,intrfc}(new_dofs{jdim}(pos2b{jdim}(not_set_p1b{idim})));
        renew_dofs{idim} = pos1b{idim}(not_set_p1b{idim});
      end
      [glob_num, dofs_ornt, ppnum] = set_same_interface (iptc, ii, ...
          ttform, renew_dofs, interfaces, glob_num, dofs_ornt, ppnum, patch_intrfc);
    end
  end
end

function [glob_num, dofs_ornt, ppnum] = set_same_interface (iptc, intrfc, ...
            ttform, new_dofs, interfaces, glob_num, ...
            dofs_ornt, ppnum, patch_intrfc)

  ornt(1) = interfaces(intrfc).ornt1;
  ornt(2) = interfaces(intrfc).ornt2;

  iptc2 = setdiff ([interfaces(intrfc).patch1 interfaces(intrfc).patch2], iptc);
  for idim = 1:size(ttform, 1)
    intrfc_dofs{idim} = ttform{idim, iptc, intrfc}(new_dofs{idim});
    glob_num{iptc2}(ttform{idim, iptc2, intrfc}(new_dofs{idim})) = ...
                              glob_num{iptc}(intrfc_dofs{idim});
    dofs_ornt{iptc2}(ttform{idim, iptc2, intrfc}(new_dofs{idim})) = ...
             ornt(idim) * dofs_ornt{iptc}(intrfc_dofs{idim});
%             interfaces(intrfc).ornt(idim) * dofs_ornt{iptc}(intrfc_dofs{idim});
  end

  [glob_num, dofs_ornt, ppnum] = set_same_patch (iptc2, intrfc, ...
           ttform, new_dofs, interfaces, glob_num, ...
           dofs_ornt, ppnum, patch_intrfc);

end


function value = p12_autonomous ( )

%*****************************************************************************80
%
%% P12_AUTONOMOUS reports whether problem P12 is autonomous.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer VALUE, is 1 if the equation is autonomous.
%
  value = 1;

  return
end


disp('make some variables...')
x = 2.3
y = rand(4, 3, 2)
z = 'durp durp durp'

disp('import the matlab module')
pymex('import matlab')

disp('"pull" the variables from matlab to python')
pymex('x, y, z = matlab.pull("x", "y", "z")')

disp('print the variables as seen by python')
pymex('matlab.mex_print(x, y, z)')

disp('"push" the variables from python to matlab')
pymex('matlab.push("x2", x, "y2", y, "z2", z)')

disp('test that y is equal to y2')
y == y2


function out = rval(f)
%RVAL  Obtain the value of a ONEFUN at its right endpoint.
%   RVAL(F) returns the F(1).

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

out = feval(f, 1);

end


function test_suite = testContainsRegexp
%testContainsRegexp Unit tests for containsRegexp

%   Steven L. Eddins
%   Copyright 2008 The MathWorks, Inc.

initTestSuite;

function testOneStringContains
assertTrue(xunit.utils.containsRegexp('MATLAB is great', '[A-Z]'));

function testOneStringDoesntContain
assertTrue(~ xunit.utils.containsRegexp('no upper-case letters', '[A-Z]'));

function testCellArray
strs = {'MATLAB is great', 'no upper-case letters'};
assertEqual(xunit.utils.containsRegexp(strs, '[A-Z]'), [true false]);
assertEqual(xunit.utils.containsRegexp(strs', '[A-Z]'), [true; false]);


%   AUTHORSHIP
%   Math Lead & Primary Developer:  Connor Meehan <connor.gw.meehan@gmail.com>
%   Secondary Developer: Stephen Meehan <swmeehan@stanford.edu>
%   Bioinformatics Lead:  Wayne Moore <wmoore@stanford.edu>
%   Funded by the Herzenberg Lab at Stanford University
%   License: BSD 3 clause
%
function y=probability_bin_labels(ptrs, labels, N)
assert(max(ptrs)<=N, 'Expect bin pointer can be higher than bin');
if size(ptrs,2)==1
    assert(size(ptrs,1)>N, 'Expect more bin pointers than bins');
elseif size(ptrs,1)==1
    assert(size(ptrs,2)>N, 'Expect more bin pointers than bins');
else
    assert(false, 'Expect 1 column for bin pointers');
end
y=zeros(1,N);
y(ptrs)=labels;
end


function y = cvx_basis( x )

if isempty( x )
    y = sparse( 1, 0 );
else
    y = sparse( reshape( x, 1, numel(  x  ) ) );
end

% Copyright 2005-2016 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function h=vline(varargin)
%VLINE draws vertical lines
%   VLINE(X) draws one vertical line for each element in vector X
%   VLINE(AX,X) draws the lines to the axes specified in AX
%   VLINE(X,...) accepts HG param/value pairs for line objects
%   H=VLINE(...) returns a handle to each line created

%   Copyright 2007-2008 The MathWorks, Inc.
%   $Revision: 1.1.6.3 $  $Date: 2008/05/23 15:39:00 $

if isempty(varargin) || (ishandle(varargin{1}) && length(varargin)==1)
    error('stats:hline:NotEnoughArgs','Not enough arguments');
end

if ishandle(varargin{1})
    ax=varargin{1};
    varargin=varargin(2:end);
else
    ax=gca;
end

x = varargin{1};
varargin=varargin(2:end);

hh=graph2d.constantline(x,'parent',ax,varargin{:});
hh = changedependvar(hh,'x');

if nargout>0
    h=hh;
end


function x = parse(inStr)

% parse 是一个函数，它接收一个由空格分隔的文本组成的字符串向量，
% 并将各个字符串项解析为一个 n 项矩阵，每个字符串一行。

% x     - the return matrix of strings
% inStr - the blank separated string vector

%%  切割字符串
strLen = size(inStr, 2);
x = blanks(strLen);
wordCount = 1;
last = 0;
for i = 1 : strLen
  if inStr(i) == ' '
    wordCount = wordCount + 1;
    x(wordCount, :) = blanks(strLen);
    last = i;
  else
    x(wordCount, i - last) = inStr(i);
  end
end

github-repos/MATLAB/Time9Y-Matlab-Machine/Matlab-Machine-6590d27c49bb2c9415613f132fc2b50fea982c60/009_Optimize time series prediction of BP neural network based on genetic algorithm/goat/parse.m


function value = p28_autonomous ( )

%*****************************************************************************80
%
%% P28_AUTONOMOUS reports whether problem P28 is autonomous.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer VALUE, is 1 if the equation is autonomous.
%
  value = 1;

  return
end


% -------------------------------------------------------------------------- %
% function hfssPolyline(fid, Name, Points, Units, [Closed], [segmentType], ...
%                       [Color], [Transparency])
% Description:
% ------------
%
% Parameters:
% -----------
% Name   - Name Attribute for the PolyLine.
% Points - Points as 3-Tuples, ex: Points = [0, 0, 1; 0, 1, 0; 1, 0 1];
%          Note: size(Points) must give [nPoints, 3].
% Units  - units of the segments (specify using either 'in', 'mm', 'meter'
%          or anything else defined in HFSS).
% Closed  - (Optional; bool) Closes the polyline to form a sheet. By
%           default is false.
% segmentType - (Optional) Defines the cross-section of the segment. Only
%               'Line' is supported. By default is 'Line'.
% Color       - (Optional) Defines the RGB color with a 3-tuple [R, G, B].
%               By default is set to [0, 0, 0] (black).
% Transparency - (Optional) Defines the transparency of the line. By
%                default is set to 0.8.
%
% Example:
% --------
% -------------------------------------------------------------------------- %

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

% ----------------------------------------------------------------------------
% CHANGELOG
%
% ??-???-????: *Initial release (VR).
% 07-Aug-2014: *Fix representation of polylines (DRP).
% 07-Aug-2014: *Added option for closed polyline (DRP).
% 01-Sep-2020: *Fixed closed polyline assignment (DRP).
% 20-Apr-2021: *Added missing documentation (DRP).
% 21-Apr-2021: *Changed default color and transparency to that of the
%               hfssRectangle function (DRP).
% ----------------------------------------------------------------------------

% ----------------------------------------------------------------------------
% Modified by Daniel Rodriguez Prado
% danysan@gmail.com
% 20 Apr 2021
% ----------------------------------------------------------------------------

function hfssPolyline(fid, Name, Points, Units, Closed, segmentType, ...
                      Color, Transparency)
if (nargin < 5)
    Closed = [];
	segmentType = [];
	Color = [];
	Transparency = [];
elseif (nargin < 6)
    segmentType = [];
	Color = [];
	Transparency = [];
elseif (nargin < 7)
    Color = [];
	Transparency = [];
elseif (nargin < 8)
    Transparency = [];
end

if isempty(Closed)
    Closed = 'false';
end
if isempty(segmentType)
	segmentType = 'Line';
end
if isempty(Color)
	Color = [132, 132, 193];
end
if isempty(Transparency)
	Transparency = 0.75;
end

nPoints = length(Points(:, 1));

% Preamble.
fprintf(fid, '\n');
fprintf(fid, 'oEditor.CreatePolyline _\n');
fprintf(fid, '\tArray("NAME:PolylineParameters", ');
fprintf(fid, '"IsPolylineCovered:=", true, ');
if (Closed == true)
    fprintf(fid, '"IsPolylineClosed:=", true, _\n');
else
    fprintf(fid, '"IsPolylineClosed:=", false, _\n');
end

% Enter the Points.
fprintf(fid, '\t\tArray("NAME:PolylinePoints", _\n');
for iP = 1:nPoints-1
	fprintf(fid, '\t\t\tArray("NAME:PLPoint", ');
	fprintf(fid, '"X:=", "%.4f%s", ', Points(iP, 1), Units);
	fprintf(fid, '"Y:=", "%.4f%s", ', Points(iP, 2), Units);
	fprintf(fid, '"Z:=", "%.4f%s"), _\n', Points(iP, 3), Units);
end
fprintf(fid, '\t\t\tArray("NAME:PLPoint", ');
fprintf(fid, '"X:=", "%.4f%s",   ', Points(nPoints, 1), Units);
fprintf(fid, '"Y:=", "%.4f%s",   ', Points(nPoints, 2), Units);
fprintf(fid, '"Z:=", "%.4f%s")_\n', Points(nPoints, 3), Units);
fprintf(fid, '\t\t\t), _ \n');

% Create Segments.
fprintf(fid, '\t\tArray("NAME:PolylineSegments", _\n');
for iP = 1:nPoints-2
    fprintf(fid, '\t\t\tArray("NAME:PLSegment", ');
    fprintf(fid, '"SegmentType:=",  "%s", ', segmentType);
    fprintf(fid, '"StartIndex:=", %d, ', iP-1);
    fprintf(fid, '"NoOfPoints:=", 2), _\n');
end
fprintf(fid, '\t\t\tArray("NAME:PLSegment", ');
fprintf(fid, '"SegmentType:=",  "%s", ', segmentType);
fprintf(fid, '"StartIndex:=", %d, ', iP);
fprintf(fid, '"NoOfPoints:=", 2) _\n');
fprintf(fid, '\t\t\t) _\n');
fprintf(fid, '\t\t), _\n');

% Polyline Attributes.
fprintf(fid, 'Array("NAME:Attributes", _\n');
fprintf(fid, '"Name:=", "%s", _\n', Name);
fprintf(fid, '"Flags:=", "", _\n');
fprintf(fid, '"Color:=", "(%d %d %d)", _\n', Color(1), Color(2), Color(3));
fprintf(fid, '"Transparency:=", %f, _\n', Transparency);
fprintf(fid, '"PartCoordinateSystem:=", "Global", _\n');
fprintf(fid, '"MaterialName:=", "vacuum", _\n');
fprintf(fid, '"SolveInside:=", true)\n');


%RANDRESET  Reset state of random generators
%
%   RANDRESET                   - reset states to 1
%   RANDRESET(STATE)            - reset states to STATE
%   STATE = RANDRESET           - retrieve present state (no reset)
%   OLDSTATE = RANDRESET(STATE) - retrieve present state and reset

function output = randreset(state)

if nargin < 1 & nargout < 1
   state = 1;
end

if nargin > 0
  if iscell(state)
    % old state format, force switch to old generator
    rand('seed',0);
    % new state format, force switch to new generator
  elseif isstruct(state)
    rng(0,'twister');
  end
end

if verLessThan('matlab','8.1.0') || strcmp(getfield(rng,'Type'),'Legacy')
  % old random number generators

  if nargout > 0
    % retrieve present state
    randstate = cell(1,2);
    randstate{1} = rand('state');
    randstate{2} = randn('state');
    output = randstate;
  end

  if ~(nargout == 1 & nargin == 0)
    % reset
    if iscell(state)
      rand('state',state{1});
      randn('state',state{2});
    else
      rand('state',state);
      randn('state',state);
    end
  end

else
  % new random number generator (rng)

  if nargout > 0
    % retrieve present state
    output = rng;
  end

  if ~(nargout == 1 & nargin == 0)
    % reset
    rng(state);
  end

end


I = im2double(imread('fruit.bmp'));
I_d = Yang2010(I);
figure(1)
subplot(1, 3, 1), imshow(I), xlabel('(a)', 'FontName', 'Helvetica', 'FontSize', 8, 'VerticalAlignment', 'bottom')
subplot(1, 3, 2), imshow(I_d), xlabel('(b)', 'FontName', 'Helvetica', 'FontSize', 8, 'VerticalAlignment', 'bottom')
subplot(1, 3, 3), imshow(I-I_d), xlabel('(c)', 'FontName', 'Helvetica', 'FontSize', 8, 'VerticalAlignment', 'bottom')
set(gcf, 'PaperUnits', 'inches')
set(gcf, 'PaperPosition', [0, 0, 5.35, 3])
print('example.png', '-dpng', '-r300')
% convert figure1.png -trim figure1.png


function [DialedNum] = FrameSequeneRules(A);

%Computes the most probable dialed number based on design rules
%Input Variables
%           A    = Input Frame Decode Matrix
%
% Output Variables
%    DialedNum   = Number determined after analyzing a block of frames

% Checking for minimum number of arguments
if nargin < 1
    error('Not enough input arguments');
end

PossibleNums=cell(1,length(A));
RepeatSequence=[];
t=1;
k=1;

% Check to see what is repeating most number of times other than a pause
% signal
for i=1:(length(A)-1)
    if  strcmp(A(i),A(i+1)) && A(i) ~= 'p'
        k = k+1;
    else
        t=t+1;
        k = 1;
    end

       PossibleNums{t}=A(i);
       RepeatSequence(t)=k;
end

[R,C]=max(RepeatSequence);
DialedNum = PossibleNums{C};


function value = p21_autonomous ( )

%*****************************************************************************80
%
%% P21_AUTONOMOUS reports whether problem P21 is autonomous.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer VALUE, is 1 if the equation is autonomous.
%
  value = 1;

  return
end


function[]=jlab_index(varargin)
%JLAB_INDEX  Alphabetical index into JLAB and JDATA contents.
%
% JDATA index
%   about_floats  - Historical dataset of eddy-resolving subsurface floats.
%   about_ibcao   - International Bathymetric Chart of the Arctic Ocean topography.
%   about_sandwell - One minute resolution topography data from Smith and Sandwell.
%   about_tpjaos  - Sea surface height anomalies from the Beckley merged dataset.
%   readtopo      - Read one-minute topography data from Smith and Sandwell.
%   topo_copyright - Copyright statement for the Smith and Sandwell topography.
%
% JLAB index
%   ab2kl         - Converts A and B to ellipse parameters Kappa and Lambda.
%   about_jtopo   - One-sixth degree global topography, from Smith and Sandwell + IBCAO.
%   allall        - ALLALL(X)=ALL(X(:))
%   anatrans      - Analytic part of signal.
%   anyany        - ANYANY(X)=ANY(X(:))
%   aresame       - Test whether two N-D arrays are the same.
%   arrayify      - Converts a set of scalars or arrays into column arrays.
%   axeshandles   - Returns handles to all axes children.
%   bellpoly      - Complete Bell polynomials.
%   besselitilde  - I-type Bessel function after factoring off exponential growth.
%   besselktilde  - K-type Bessel function after factoring off exponential decay.
%   bindata       - Rapidly sort data into adjacent bins.
%   blocklen      - Counts the lengths of 'blocks' in an array.
%   blocknum      - Numbers the contiguous blocks of an array.
%   blurspec      - Returns the blurred and aliased spectrum given the autocovariance.
%   boxon         - Sets 'box' property to 'off'.
%   boxon         - Sets 'box' property to 'on'.
%   catstruct     - Concatenates the array elements of a cell array of structures.
%   cell2col      - Converts cell arrays of numeric arrays into 'column-appended' form.
%   cellabs       - Absolute value of each element in a cell array.
%   celladd       - Addition acting on each element in a cell array.
%   cellchunk     - Converts cell array data into uniform length 'chunks'.
%   celldiv       - Division acting on each element in a cell array.
%   celldot       - Dot product for arrays of column vectors.
%   cellength     - Length of each element in a cell array.
%   cellfill      - Fills missing data marked by INFs in a cell array.
%   cellfirst     - Returns the first (or last) element of each entry in a cell array.
%   cellget       - Indexes a cell array of numerical arrays by ID number.
%   cellgrid      - Interpolate a cell array of numeric arrays onto a regular grid.
%   cellimag      - Imaginary part of each element in a cell array.
%   cellimit      - Limits the ranges of times in a cell array of numerical arrays.
%   cellindex     - Applies a cell array of indices to a cell array of column vectors.
%   celllog10     - Base ten logarithm of each element in a cell array.
%   cellmax       - Maximum of each element in a cell array.
%   cellmean      - Mean value of each element a cell array, possibly weighted.
%   cellmed       - Median value of each element a cell array.
%   cellmin       - Minimum of each element in a cell array.
%   cellmult      - Multiplication acting on each element in a cell array.
%   cellpack      - Removes all INF values from cell arrays of numeric arrays.
%   cellpair      - Complex pairing for elements in a cell array.
%   cellplot      - Rapidly plot all elements of a cell array of numeric arrays.
%   cellprune     - Removes all empty cells, or cells less than a specified length.
%   cellreal      - Real part of each element in a cell array.
%   cellsize      - Size of each element in a cell array along specified dimension.
%   cellsplit     - Splits cell arrays of numeric arrays at data gaps.
%   cellstd       - Standard deviation of each element a cell array, possibly weighted.
%   cellstrip     - Strips INF values from the beginnings or ends of cell arrays.
%   cellsum       - Sum of each element a cell array, possibly weighted.
%   chisquared    - The chi-squared distribution.
%   choose        - Binomial coefficient: CHOOSE(N,K) = N!K!/(N-K)!
%   closedcurves  - Locate and interpolate closed curves in a possibly periodic domain.
%   cms2kmd       - Converts centimeters per second to kilometers per day.
%   col2cell      - Converts 'column-appended' data into cell arrays of numeric arrays.
%   col2mat       - Expands 'column-appended' data into a matrix.
%   colbreaks     - Insert NANs into discontinuties in a vector.
%   colorquant    - Set the color axis according to quantiles of the data.
%   commentlines  - Returns the comment lines from m-files.
%   corfreq       - Coriolis frequency in radians per hour.
%   crop          - Gets rid of whitespace around an image. [by A. Bliss]
%   crop_license  - License statement for CROP by Andrew Bliss.
%   cum2mom       - Convert cumulants to moments.
%   curveinterp   - Interpolate a field or its gradient onto a set of curves.
%   curvemoments  - Centroid, area, and many other moments of a closed curve.
%   deg180        - Converts degrees to the range [-180,180].
%   deg360        - Converts degrees to the range [0, 360].
%   degunwrap     - Unwraps arrays given in degrees.
%   discretecolorbar - Plots a colorbar with discrete variation.
%   divgeom       - Geometric decomposition of eddy vorticity flux divergence.
%   dlines        - Add diagonal lines to a plot.
%   doublen       - Interpolates a time series to double its length.
%   ecconv        - Converts between eccentricity measures.
%   eddyfit2d     - Least squares fit of 2D velocity data to an eddy profile.
%   eddylevels    - Eddy ridge significance levels using the survival function.
%   eddyridges    - Coherent eddy ridges from Lagrangian trajectories.
%   ellband       - Bandwidth of modulated elliptical signals in two or three dimensions.
%   ellcurves     - Returns curves corresponding to specified ellipse properties.
%   elldiff       - Differentiation of modulated elliptical signals.
%   ellipseplot   - Plot ellipses.
%   ellparams     - Ellipse parameters of a modulated bivariate or trivariate oscillation.
%   ellpol        - Polarization parameters of an elliptical signal.
%   ellrad        - Average and instantaneous ellipse radius.
%   ellrossby     - Ellipse Rossby number, for oceanographic applications.
%   ellsig        - Creates a modulated elliptical signal in two or three dimensions.
%   ellvel        - Average and instantaneous ellipse velocities.
%   fillbad       - Linearly interpolate over bad data points.
%   findfiles     - Returns all files in a directory with a specified extension.
%   findpath      - Returns the full pathname of a directory on the Matlab search path.
%   fixlabels     - Specify precision of axes labels.
%   flipmap       - Flips the current colormap upside-down.
%   flipx         - Flips the direction of the x-axis
%   flipy         - Flips the direction of the y-axis
%   fminsearchbnd - FMINSEARCH, but with bound constraints by transformation. [By J. D'Errico]
%   fontsize      - Rapidly set title, axes, label, and text fontsizes.
%   fourier       - Returns the Fourier frequencies for a given length time series.
%   frac          - Fraction: FRAC(A,B)=A./B
%   griddrifters  - Average drifter velocities onto a space/time 3D grid.
%   gulf4plot     - A four-panel circulation plot for the Gulf of Mexico.
%   haxby         - The Haxby colormap.
%   haxby_copyright - Copyright statement for the HAXBY colormap.
%   hermfun       - Orthonormal Hermite functions. [with F. Rekibi]
%   hermpoly      - Hermite polynomials. [with F. Rekibi]
%   hlines        - Add horizontal lines to a plot.
%   hodograph     - Generate hodograph plots (simple and fancy).
%   imlog         - Imaginary part of log: IMLOG(X)=UNWRAP(IMAG(LOG(X)))
%   inellipse     - Locates points on the interior of ellipses.
%   inregion      - Tests whether lat/lon points lie within a specified box.
%   instmom       - Univariate and multivariate instantaneous moments.
%   interplatlon  - Interpolation for working with latitude and longitude.
%   inticks       - Sets the 'tickdir' property of the current axis to 'in'.
%   iseven        - True for even integer values; false otherwise.
%   isodd         - True for odd integer values; false otherwise.
%   isomax        - Returns those transform maxima that are isolated from others.
%   isridgepoint  - Finds wavelet ridge points using one of several criterion.
%   jdawson       - The Dawson function and its derivatives. [With P.J. Acklam]
%   jdeg2rad      - Converts degrees to radians.
%   jfig          - Shorthand for tweaking figures.
%   jhanning      - Hanning window.
%   jhelp         - Opens linked JLAB help files in Matlab's internal web browser.
%   jlab_addpath  - Adds JLAB and JDATA subdirectories to your Matlab search path.
%   jlab_allhelp  - Displays the help comments for all JLAB modules.
%   jlab_changes  - Changes to JLAB in each release.
%   jlab_highlights - Introduction to some of the most useful routines.
%   jlab_index    - Alphabetical index into JLAB and JDATA contents.
%   jlab_install  - Instructions for installing JLAB.
%   jlab_license  - License statement and permissions for JLAB package.
%   jlab_makefigs - Makes figures for papers by J.M. Lilly.
%   jlab_runtests - Runs a test suite for JLAB package.
%   jlab_thanks   - Sources of support for developing this software.
%   jmat2         - 2x2 rotation matrix through specified angle.
%   jmat3         - 3x3 rotation matrix through specified angle.
%   jpcolor       - Modified version of PCOLOR appropriate for cell-centered grids.
%   jprint        - Print to a specified directory and crop the resulting file.
%   jrad2deg      - Converts radians to degrees.
%   kl2ab         - Converts ellipse parameters Kappa and Lambda to A and B.
%   lansey        - The Lansey modification of Cynthia Brewer's "Spectral" colormap.
%   lansey_copyright - Copyright statement for the Lansey colormap.
%   latlon2uv     - Converts latitude and longitude to horizontal velocity.
%   latlon2xy     - Converts latitude and longitude into tangent plane coordinates.
%   latlon2xyz    - Converts latitude and longitude into 3D Cartesian coordinates.
%   latratio      - Set plot aspect ratio for latitude / longitude plot.
%   letterlabels  - For automatically putting letter labels on subplots.
%   linecolor     - Set line colors based on a property value within a colormap.
%   linehandles   - Finds all line and patch handles from a given set of axes.
%   linering      - Moves lines through the current line style order.
%   linestyle     - Rapidly set color, style, and width properties of lines.
%   linestyleparse - Parses the input string to LINESTYLE.
%   lininterp     - Fast linear interpolation for arbitrary-sized arrays.
%   lnsd          - Last non-singleton dimension of an array.
%   lonshift      - Shifts longitude origin for plotting purposes.
%   make          - Create a structure containing named variables as fields.
%   makefigs_analytic - has been moved to JLAB_MAKEFIGS.
%   makefigs_asilomar - has been moved to JLAB_MAKEFIGS.
%   makefigs_bandwidth - has been moved to JLAB_MAKEFIGS.
%   makefigs_closedcurves - Makes a sample figure for CLOSEDCURVES.
%   makefigs_curvemoments - Makes a sample figure for CURVEMOMENTS.
%   makefigs_dlines - Makes a sample figure for DLINES.
%   makefigs_doublen - Makes a sample figure for DOUBLEN.
%   makefigs_ecconv - Makes a sample figure for ECCONV.
%   makefigs_element - Makes all figures for Lilly (2017), "Element Analysis."
%   makefigs_ellband - Makes a sample figure for ELLBAND.
%   makefigs_ellipseplot - Makes a sample figure for ELLIPSEPLOT.
%   makefigs_ellvel - Makes a sample figure for ELLVEL.
%   makefigs_gulfcensus - Makes all figures for Lilly and Perez-Brunius (2021b).
%   makefigs_gulfdrifters - Makes all figures for Lilly and Perez-Brunius (2021a).
%   makefigs_hermfun - Makes a sample figure for HERMFUN.
%   makefigs_inellipse - Makes a sample figure for INELLIPSE.
%   makefigs_instmom - Makes some sample figures for INSTMOM.
%   makefigs_jdawson - Makes a sample figure for DJAWSON.
%   makefigs_jfig - Makes a sample figure for JFIG.
%   makefigs_jpcolor - Makes a sample figure for JPCOLOR.
%   makefigs_jtopo - Makes a sample figure for ABOUT_JTOPO.
%   makefigs_lansey - Makes a sample figure for LANSEY.
%   makefigs_matern - Makes all figures for Lilly et al. 2017.
%   makefigs_maternoise - Makes a sample figure for MATERNOISE.
%   makefigs_maternspec - Makes some sample figures for MATERNSPEC.
%   makefigs_mconf - Makes sample figure for MCONF.
%   makefigs_morlfreq - Makes a sample figure for MORLFREQ.
%   makefigs_morlwave - Makes a sample figure for MORLWAVE.
%   makefigs_morsearea - Makes a sample figure for MORSEAREA.
%   makefigs_morsebox - Makes a sample figure for MORSEBOX.
%   makefigs_morsefreq - Makes a sample figure for MORSEFREQ.
%   makefigs_morseregion - Makes somes sample figures for MORSEREGION.
%   makefigs_morsespace - Makes some sample figures for MORSESPACE.
%   makefigs_morsewave - Makes some sample figures for MORSEWAVE.
%   makefigs_morsies - has been moved to JLAB_MAKEFIGS.
%   makefigs_mspec - Makes some sample figures for MSPEC.
%   makefigs_multivariate - has been moved to JLAB_MAKEFIGS.
%   makefigs_patchcontourf - Makes a sample figure for PATCHCONTOURF.
%   makefigs_periodize - Makes a sample figure for PERIODIZE.
%   makefigs_polysmooth - Makes some sample figures for POLYSMOOTH.
%   makefigs_polysmooth2 - Makes a sample figure for POLYSMOOTH using TPJAOS.MAT.
%   makefigs_psi2fields - Makes a sample figure for PSI2FIELDS.
%   makefigs_regionplot - Makes some sample figures for REGIONPLOT.
%   makefigs_ridges - has been moved to JLAB_MAKEFIGS.
%   makefigs_ridgetrim - Makes a sample figure for RIDGETRIM.
%   makefigs_ridgewalk - Makes a sample figure for RIDGEWALK.
%   makefigs_seminfhaxby - Makes a sample figure for SEMINFHAXBY.
%   makefigs_simplepdf - Makes a sample figure for SIMPLEPDF.
%   makefigs_slidetrans - Makes a sample figure for SLIDETRANS.
%   makefigs_sphereinterp - Makes two sample figures for SPHEREINTERP.
%   makefigs_stickvect - Makes a sample figure for STICKVECT.
%   makefigs_superfamily - has been moved to JLAB_MAKEFIGS.
%   makefigs_topoplot - Makes a sample figure for TOPOPLOT.
%   makefigs_trackextract - Makes a sample figure for TRACKEXTRACT.
%   makefigs_trajextract - Makes a sample figure for TRAJEXTRACT.
%   makefigs_trajwrap - Makes a sample figure for TRAJWRAP.
%   makefigs_transfer - Makes all figures for Lilly and Elipot (2021).
%   makefigs_trivariate - has been moved to JLAB_MAKEFIGS.
%   makefigs_twodhist - Makes a sample figure for TWODHIST.
%   makefigs_twodmed - Makes a sample figure for TWODMED.
%   makefigs_twodstats - Makes a sample figure for TWODSTATS.
%   makefigs_vortex - has been moved to JLAB_MAKEFIGS.
%   makefigs_wavespecplot - Makes a sample figure for WAVESPECPLOT.
%   makefigs_wavetrans - Makes a sample figure for WAVETRANS.
%   makefigs_widgist - Makes some sample figures for WIGDIST.
%   mat2col       - Compress NAN-padded matrix data into long columns.
%   materncfun    - Returns the normalization or C-function for a Matern process.
%   maternchol    - Cholesky decomposition of Matern and fBm covariances. [with A. Sykulski]
%   materncov     - Autocovariance of the Matern random process and variations.
%   maternedge    - Long-time cutoff edge for the Matern impulse response function.
%   maternfit     - Parametric spectral fit to the Matern form. [with A. Sykulski]
%   maternfun     - Returns the Matern function.
%   maternimp     - Impulse response function for the Matern random process.
%   maternoise    - Realizations of the Matern process and variations, including fBm. [with A. Sykulski]
%   maternspec    - Fourier spectrum of the Matern random process and variations.
%   matinv        - Fast inversion of arrays of small matrices.
%   matmult       - Matrix multiplication for arrays of matrices.
%   matsave       - Create and save structure of variables as a mat-file.
%   max2eddy      - Converts transform maxima into oceanic coherent eddy properties.
%   maxmax        - MAXMAX(X)=MAX(X(ISFINITE(X)))
%   maxprops      - Returns properties of wavelet transform maxima.
%   mconf         - Confidence intervals for the multitaper spectral estimate.
%   minmin        - MINMIN(X)=MIN(X(ISFINITE(X)))
%   mom2cum       - Convert moments to cumulants.
%   monthstats    - Mean month and standard deviation using circular statistics.
%   morlfreq      - Compute Morlet wavelet carrier frequency given peak frequency.
%   morlwave      - Morlet wavelet.
%   morseafun     - Returns the generalized Morse wavelet amplitude or a-function.
%   morsearea     - Time-frequency concentration area of Morse wavelets. [with F. Rekibi]
%   morsebox      - Heisenberg time-frequency box for generalized Morse wavelets.
%   morsederiv    - Frequency-domain derivatives of generalized Morse wavelets.
%   morsefreq     - Frequency measures for generalized Morse wavelets. [with F. Rekibi]
%   morsehigh     - High-frequency cutoff of the generalized Morse wavelets.
%   morsemom      - Frequency-domain moments of generalized Morse wavelets.
%   morseproj     - Projection coefficient for two generalized Morse wavelets.
%   morseprops    - Properties of the demodulated generalized Morse wavelets.
%   morseregion   - Generalized Morse wavelet time-frequency concentration region.
%   morsespace    - Logarithmically-spaced frequencies for generalized Morse wavelets.
%   morsewave     - Generalized Morse wavelets of Olhede and Walden (2002).
%   morsexpand    - Generalized Morse wavelets via time-domain Taylor series.
%   mspec         - Multitaper power and cross spectra.
%   msvd          - Singular value decomposition for polarization analysis.
%   ncinterp      - One-line interpolation from 3D lat/lon/time field in NetCDF file.
%   ncload        - Load all variables from a NetCDF file and convert trajectories to cells.
%   nocontours    - Removes contours from a CONTOURF plot.
%   noisedrifters - Create a noise Lagrangian dataset matching mean and variance.
%   nonnan        - Return all non-NAN elements of an array.
%   noxlabels     - Remove some or all x-axis tick mark labels.
%   noylabels     - Remove some or all y-axis tick mark labels.
%   oprod         - Outer product:  OPROD(X,Y)=X*CONJ(Y')
%   orbitbreaks   - Separate orbit into passes based on turning points.
%   outticks      - Sets the 'tickdir' property of the current axis to 'out'.
%   packfig       - Squeeze together rows and/or columns of the current figure.
%   patchcontourf - Generate filled contours using patches, with specified colors.
%   pdfprops      - Mean and variance associated with a probability distribution.
%   periodindex   - Returns time index in increments of instantaneous period.
%   periodize     - Returns a doubly periodic version of an input array.
%   polparams     - Spectral matrix polarization parameters.
%   polysmooth    - Mapping using local polynomial fitting, also known as loess.
%   polysmooth_bandwidth - Determine bandwidth given population for POLYSMOOTH.
%   polysmooth_kernel - Returns the weighting kernel employed by POLYSMOOTH.
%   polysmooth_presort - Sort arguments to POLYSMOOTH in case of missing data.
%   polysmooth_sortfield - Returns sorted field values for a mapping problem.
%   printall      - Print and close all open figures.
%   provec        - Generate progressive vector diagrams (simple and fancy).
%   psi2fields    - Velocity and other fields from the streamfunction. [with P.E. Isachsen]
%   quadinterp    - Fast quadratic interpolation for arbitrary-sized arrays.
%   radearth      - The radius of the earth in kilometers.
%   regionplot    - Plots a simple box indicating a latitude / longitude region.
%   reporttest    - Reports the result of an m-file function auto-test.
%   res           - Residual after flooring:  RES(X)=X-FLOOR(X)
%   ridgechains   - Forms ridge curves by connecting transform ridge points.
%   ridgeinterp   - Interpolate quantity values onto ridge locations.
%   ridgelen      - Wavelet ridge length expressed as number of full cycles.
%   ridgemap      - Maps ridge quantities back onto the time series.
%   ridgemult     - Ridge multiplicity, the number of simultaneous ridges present.
%   ridgetrim     - Trim edge effect regions from wavelet ridges.
%   ridgewalk     - Extract wavelet transform ridges, including bias estimates.
%   rot           - Complex-valued rotation:  ROT(X)=EXP(SQRT(-1)*X)
%   sampletimes   - Computes mean sampling intervals and their statistics.
%   seminfhaxby   - The seminf-Haxby colormap.
%   sig2latlon    - Converts an oscillatory signal to lat/lon displacements.
%   simpleddy     - Streamfunction, velocity, and vorticity for various eddy profiles.
%   simplepdf     - Gaussian, uniform, Cauchy, and exponential pdfs.
%   sleptap       - Calculate Slepian tapers.
%   slidetrans    - Sliding-window ('moving-window') Fourier transform.
%   specdiag      - Diagonalize a 2 x 2 spectral matrix.
%   sphere2uvw    - Converts a 3D spherical vector to a 3D Cartesian vector.
%   spherecurl    - Curl of a vector field on the surface of a sphere.
%   spheredist    - Computes great circle distances on a sphere.
%   spherediv     - Divergence of a vector field on the surface of a sphere.
%   spheregrad    - Gradient of a field on the surface of a sphere.
%   sphereinterp  - Fast linear interpolation on the sphere from non-plaid grids.
%   spherelap     - Laplacian of a field on the surface of a sphere.
%   spheresort    - Sorted great circle distances to nearby points on the earth.
%   spheretrans   - Wavelet transform for oscillations on the surface of a sphere.
%   squared       - Squares the modulus of its argument:  SQUARED(X)=ABS(X).^2
%   standalone    - Create stand-alone version of an m-file, including dependencies.
%   stickvect     - Plots "stick vectors" for multicomponent velocity time series.
%   structindex   - Applies an index to all array-valued fields in a structure.
%   tidefreq      - Frequencies of the eight major tidal components.
%   timeseries_boundary - Apply boundary conditions to data before transform.
%   tmat          - 2x2 complex grouping matrix.  TMAT = [1  i; 1 -i] / SQRT(2)
%   to_grab_from_caller - Returns a string to grab variable values from caller.
%   to_overwrite  - Returns a string to overwrite original arguments.
%   topo_copyright - Copyright statement for the Smith and Sandwell topography.
%   topoplot      - Plot regional or global topography at one-sixth degree resolution.
%   trackextract  - Extracts alongtrack altimetry segments within given region.
%   trajchunk     - Chunks Lagrangian trajectories based on the Coriolis period.
%   trajextract   - Extracts Lagrangian trajectory segments within given region.
%   trajunwrap    - Unwraps Lagrangian trajectories from a periodic domain.
%   trajwrap      - Wraps Lagrangian trajectories to fit within a periodic domain.
%   transmax      - Locates modulus maximum points of wavelet transform.
%   transmaxdist  - Distributions of wavelet transform maxima in noise.
%   twodhist      - Two-dimensional histogram.
%   twodmed       - Median value of a function of two variables.
%   twodsort      - Distances from data points to nearby grid points.
%   twodstats     - Mean, variance, and covariance of functions of two variables.
%   twospecplot   - Plots a pair of rotary or Cartesian spectra.
%   use           - Copies structure fields into named variables in workspace.
%   uv2latlon     - Integrates horizontal velocity to give latitude and longitude.
%   uvplot        - Plots the real and imaginary parts of a signal on the same axis.
%   vcolon        - Condenses its arguments, like X(:).
%   vdiff         - Length-preserving first central difference.
%   vectmult      - Matrix multiplication for arrays of vectors.
%   vempty        - Initializes multiple variables to empty sets or empty cell arrays.
%   vfilt         - Filtering along rows without change in length.
%   vindex        - Indexes an N-D array along a specified dimension.
%   vindexinto    - Indexes into N-D array along a specified dimension.
%   vlines        - Add vertical lines to a plot.
%   vmean         - Mean over non-NaN elements along a specified dimension.
%   vmedian       - Median over finite elements along a specified dimension.
%   vmoment       - Central moment over non-NaN elements along a specfied dimension.
%   vrep          - Replicates an array along a specified dimension.
%   vrms          - Root-mean-square of non-NaN elements along a specified dimension.
%   vshift        - Cycles the elements of an array along a specified dimension.
%   vsize         - Returns the sizes of multiple arguments.
%   vsqueeze      - Squeezes multiple input arguments simultaneously.
%   vstd          - Standard deviation over non-NaN elements along a specfied dimension.
%   vsum          - Sum over non-NaN elements along a specified dimension.
%   vswap         - VSWAP(X,A,B) replaces A with B in numeric array X.
%   vtranspose    - Transpose multiple input arguments simultaneously.
%   vzeros        - Initializes multiple variables to arrays of zeros or nans.
%   wavespecplot  - Plot of wavelet spectra together with time series.
%   wavetrans     - Continuous wavelet transform.
%   whichdir      - Returns directory name containing file in search path.
%   wigdist       - Wigner distribution (alias-free algorithm).
%   windtrans     - Ekman-like transfer-functions for the wind-driven response.
%   xlin          - Sets x-axis scale to linear.
%   xlog          - Sets x-axis scale to logarithmic.
%   xoffset       - Offsets lines in the x-direction after plotting.
%   xtick         - Sets locations of x-axis tick marks.
%   xy2latlon     - Converts tangent plane coordinates into latitude and longitude.
%   xyz2latlon    - Converts 3D Cartesian coordinates into latitude and longitude.
%   yearfrac      - Converts a DATENUM into 'year.fraction' and 'month.fraction'.
%   ylin          - Sets y-axis scale to linear.
%   ylog          - Sets y-axis scale to log.
%   yoffset       - Offsets lines in the y-direction after plotting.
%   ytick         - Sets locations of y-axis tick marks.
%   ztick         - Sets locations of z-axis tick marks.
%   __________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2015--2021 J.M. Lilly --- type 'help jlab_license' for details

if nargin==0
    help jlab_index
else
    if strcmpi(varargin{1},'--create')
        jlab_index_create;
        return
    end
end

function[]=jlab_index_create
jlab_dir=whichdir('jlab_license');
jdata_dir=[jlab_dir(1:end-4) 'jdata'];

for k=1:2
    switch k
        case 1
            mfiles=findfiles(jlab_dir,'m','recursive');
        case 2
            mfiles=findfiles(jdata_dir,'m','recursive');
    end
    for i=1:length(mfiles)
        if strcmp(mfiles{i},'Contents.m')
            mfiles{i}=[];
        end
    end
    mfiles=mfiles(cellength(mfiles)>0);
    mfiles=strs2mat(mfiles);

    for i=size(mfiles,2):-1:1
        [temp,sorter]=sort(mfiles(:,i));
        mfiles=mfiles(sorter,:);
    end
    clear comments
    for i=1:size(mfiles,1)
        %mfiles(i,:)
        comments{i}=commentlines(mfiles(i,:));
    end
    switch k
        case 1
            comments1=strs2mat(comments);
        case 2
            comments2=strs2mat(comments);
    end
end

% clear comments
% comments{1}=comments2;
% comments{2}=comments1;

disp('Start here -->')
disp('%JLAB_INDEX  Alphabetical index into JLAB and JDATA contents.')
disp('%')
disp('% JDATA index')
disp(comments2)
disp('%')
disp('% JLAB index')
disp(comments1)

function[mat]=strs2mat(strcell)

for i=1:length(strcell)
    strcell{i}=real(strcell{i}');
end

cell2col(strcell);
col2mat(strcell);
vswap(strcell,nan,32);
mat=char(strcell');

function[]=jlab_index_test

%reporttest('JLAB_INDEX',aresame())


function pos =  DECODE_MFSK(Metrics,M)

%give the most likely output, given a set of input Metrics

max_metric = Metrics(1);
pos = 0;

for i = 2:M
    if Metrics(i) > max_metric
        max_metric = Metrics(i);
        pos = i - 1;
    end
end


% spdiag - sparse diagonal matrix
%
% Copyright(c) 2009 Ryota Tomioka
% This software is distributed under the MIT license. See license.txt

function D = spdiag(d)

if isempty(d)
  D = [];
  return;
end

if size(d,1)<size(d,2)
  d = d';
end

D = spdiags(d,0,size(d,1),size(d,1));


function varargout = drawLabels(varargin)
%DRAWLABELS Draw labels at specified positions
%
%   DRAWLABELS(X, Y, LBL) draw labels LBL at position X and Y.
%   LBL can be either a string array, or a number array. In this case,
%   string are created by using sprintf function, with '%.2f' mask.
%
%   DRAWLABELS(POS, LBL) draw labels LBL at position specified by POS,
%   where POS is a N*2 int array.
%
%   DRAWLABELS(..., NUMBERS, FORMAT) create labels using sprintf function,
%   with the mask given by FORMAT (e. g. '%03d' or '5.3f'), and the
%   corresponding values.
%
%   ---------
%
%   author : David Legland
%   INRA - TPV URPOI - BIA IMASTE
%   created the 15/12/2003.
%

%   HISTORY
%   09/03/2007: (re)implement it...
%   2011-10-11 add management of axes handle

% check if enough inputs are given
if isempty(varargin)
    error('wrong number of arguments in drawLabels');
end

% extract handle of axis to draw on
if isscalar(varargin{1}) && ishandle(varargin{1})
    ax = varargin{1};
    varargin(1) = [];
else
    ax = gca;
end

% process input parameters
var = varargin{1};
if size(var, 2) == 1
    % coordinates given as separate arguments
    if length(varargin) < 3
        error('wrong number of arguments in drawLabels');
    end
    px  = var;
    py  = varargin{2};
    lbl = varargin{3};
    varargin(1:3) = [];
else
    % parameters given as a packed array
    if length(varargin) < 2
        error('wrong number of arguments in drawLabels');
    end
    px  = var(:,1);
    py  = var(:,2);
    lbl = varargin{2};
    varargin(1:2) = [];
end

% format for displaying numeric values
format = '%.2f';
if ~isempty(varargin)
    format = varargin{1};
end
if size(format, 1) == 1 && size(px, 1) > 1
    format = repmat(format, size(px, 1), 1);
end

% compute the strings that have to be displayed
labels = cell(length(px), 1);
if isnumeric(lbl)
    for i = 1:length(px)
        labels{i} = sprintf(format(i,:), lbl(i));
    end
elseif ischar(lbl)
    for i = 1:length(px)
        labels{i} = lbl(i,:);
    end
elseif iscell(lbl)
    labels = lbl;
end
labels = char(labels);

% display the text
h = text(px, py, labels, 'parent', ax);

% format output
if nargout > 0
    varargout = {h};
end


%CELLWRITE Write a cell array to a comma separated value file.
%   CELLWRITE(FILENAME, C) writes cell array C into FILENAME as comma
%   separated values.
%
%   NOTE: This function is not completely compatible with CSVWRITE.
%   Offsets are not supported and 0 values are not omitted.
%
%   See also CSVWRITE, CSVREAD, DLMREAD, DLMWRITE, WK1READ, WK1WRITE.
function cellwrite(filename, cellarray)
% The cell array is traversed, the contents of each cell are converted
% to a string, and a CSV file is written using low level fprintf
% statements.
[rows, cols] = size(cellarray);
fid = fopen(filename, 'w');
for i_row = 1:rows
    file_line = '';
    for i_col = 1:cols
        contents = cellarray{i_row,i_col};
        if isnumeric(contents)
            contents = num2str(contents);
        elseif isempty(contents)
            contents = '';
        end
        if i_col<cols
            file_line = [file_line, contents, ','];
        else
            file_line = [file_line, contents];
        end
    end
    count = fprintf(fid,'%s\n',file_line);
end
st = fclose(fid);
if st == -1
    error('Bad file write')
end


function [V,F3,F4] = load_obj_file(modelname, opts)
% loadawobj load a Wavefront/Alias obj style model.
%    It will only consider polygons with 3 or 4 vertices.
%    [v,f3,f4]=loadawobj(modelname)
%    s=loadawobj(modelname)
%    s=loadawobj(modelname,1) % will load vertex normals and textures
% Programme will normally ignore normal and texture data unless the
% option is given.
% It will also ignore any part of the obj specification that is not a
% polygon mesh, ie nurbs and the materials file (.mtl). Please let me
% know if these are needed.
%
% Examples:
%   loadawobj('name.obj') will load and display name.obj
%   S=loadawobj('name.obj') will load obj into S
%   patch('Vertices',S.v','Faces',S.f3','FaceColor','g');
%
%
% s=loadawobj(modelname) gives a structure
%  version
%  vertices
%  f3 (triangles)
%  f4 (quadrilaterals)
%  groups
%  g3 faces per group
%  g4 faces per group
%  Vn3 Vertex normals indices for f3
%  Vn4 Vertex normals indices for f4
%  Vertex normals (if option is given)
%  Vertex textures (if option is given)
%
% where the file is grouped the following code fragment can be adapted
% to split out groups
%
% clf; axis('equal'); col='mybgrcmy';
% for jj=3:length(S.g)+2
%     patch('Vertices',S.v','Faces',S.f3(:,S.g3(jj-1):S.g3(jj)-1)','FaceColor',col(jj));
%     pause;
% end;
%
% See also Anders Sandberg's vertface2obj.m and saveobjmesh.m
%
% there is still a good chance that obj files will not load. I
% would be grateful for any reports and examples of those that fail.
%
% W.S. Harwin, University Reading, 2006,2010,2015.
% Matlab BSD license
% thanks also to Doug Hackett

version=0.3;
if nargin <1
  disp('specify model name')
end

fid = fopen(modelname,'r');
if (fid<0)
  error(['can not open file: ' modelname]);
  return ;
end

vnum=1;
f3num=1; % triangle (f3) faces so far
f4num=1; % quad (f4) faces so far
vtnum=1; % vertex textures so far
vnnum=1; % vertex normals so far
gnum=0;  % groups so far
g3num=1; %
g4num=1;
Vtmp=[]; % set to null so that it can be assigned in the structure

% Line by line passing of the obj file

while ~feof(fid)
  Ln=fgets(fid);
  Ln=removespace(Ln);
  objtype=sscanf(Ln,'%s',1);
  l=length(Ln);
  if l==0  % isempty(s) ;
%    disp(['empty' Ln]);
    continue
  end
%  disp(Ln)
  Lyn=Ln; %temp hack
  switch objtype
    case '#' % comment
%       disp(Ln);
    case 'v' % vertex
      v=sscanf(Ln(2:end),'%f');
      Vtmp(:,vnum)=v;
      vnum=vnum+1;
    case 'vt'	% textures
      if nargin>=2; % option to collect
          vtxtr=sscanf(Ln(3:end),'%f');
          Vtexture(:,vtnum)=vtxtr;
          vtnum=vtnum+1;
      end
    case 'g' % sub mesh
%       disp(Ln);
%      if f3num > g3num(end);
      g3num=[g3num f3num];
      g4num=[g4num f4num];
      gnum=gnum+1;
      g{gnum}=Ln(3:end);
    case 'mtllib' % material library
%         disp(Ln);
    case 'usemtl' % use this material name
%         disp(Ln);
    case 'l' % Line
%         disp(Ln);
    case 's' %smooth shading across polygons
%         disp(Ln);
    case 'vn' % normals
      if nargin>=2; % option to collect
          vnorms=sscanf(Ln(3:end),'%f');
          Vnorms(:,vnnum)=vnorms;
          vnnum=vnnum+1;
      end
    case 'f' % faces
      nvrts=length(findstr(Ln,' ')); % spaces as a predictor of n vertices
      slashpat=findstr(Ln,'/');
      nslash=length(slashpat);
      if nslash >1 % dblslash can be 0, 1 or >1
        dblslash=slashpat(2)-slashpat(1); else dblslash=0;
      end
      Ln=Ln(3:end); % get rid of the f
      if nslash == 0 % Face = vertex
%        disp('-v');
        f1=sscanf(Ln,'%f');
      elseif nslash == nvrts && dblslash>1 % Face = v/tc
%        disp('-v/tc');
        data1=sscanf(Ln,'%f/%f');
        if nvrts == 3
          f1=data1([1 3 5]);
          tc1=data1([2 4 6]);
        end
        if nvrts == 4;
          f1=data1([1 3 5 7]);
          tc1=data1([2 4 6 8]);
        end
      elseif nslash == 2*nvrts && dblslash==1 % v//n
%        disp('-v//n');
        data1=sscanf(Ln,'%f//%f');
        if nvrts == 3
          f1=data1([1 3 5]);
          vn1=data1([2 4 6]);
          Vn3(:,f3num)=f1;
        end
        if nvrts == 4;
          f1=data1([1 3 5 7]);
          vn11=data1([2 4 6 8]);
          Vn4(:,f4num)=f1;
        end
      elseif nslash == 2*nvrts && dblslash>1 % v/tc/n
%        disp('-v/tc/n');
        data1=sscanf(Ln,'%f/%f/%f');
        if nvrts == 3
          f1=data1([1 4 7]);
          tc1=data1([2 5 8]);
          vn1=data1([3 6 9]);
          Vn3(:,f3num)=f1;
        end
        if nvrts == 4;
          f1=data1([1 4 7 10]);
          tc1=data1([2 5 8 11]);
          vn1=data1([3 6 9 12]);
          Vn4(:,f4num)=f1;
        end
      end
% Now put the data into the array(s)
      if nvrts == 3
          F3(:,f3num)=f1;
          f3num=f3num+1;
      elseif nvrts ==4
          F4(:,f4num)=f1;
          f4num=f4num+1;
      else
          warning(sprintf('v nvrts=%d %s',nvrts, Ln));
      end
    otherwise
%      if ~strcmp(Lyn,char([13 10])) % carriage return
%        if ~ all(Lyn == ' ') % ignore lines with only space
%           disp(['unprocessed-' Ln '-']); % see what has not been processed
%          double(Ln)
          %        end
%      end
    end

end

fclose(fid);

% plot if no output arguments are given
if nargout ==0
  if exist('F3','var')
    patch('Vertices',Vtmp','Faces',F3','FaceColor','g');
  end
  if exist('F4','var')
    patch('Vertices',Vtmp','Faces',F4','FaceColor','b');
  end
  axis('equal')
  clear Vtmp F3 F4
end

if nargout >=2
  V=Vtmp;
  if ~ exist('F3','var')
    warning('No 3 element faces')
    F3=[];
  end
  if nargout ==3
    if ~ exist('F4','var')
      warning('No 4 element faces')
      F4=[];
    end
  end
end

if nargout ==1
  V.version=version;
  V.v=Vtmp;
  if exist('F3','var')
      V.f3=F3;  end
  if exist('F4','var')
    V.f4=F4;  end
  if gnum>0
      V.g=g;  end
  V.g3=[g3num f3num];
  V.g4=[g4num f4num];
  if exist('Vn3','var')
    V.Vn3=Vn3;  end
  if exist('Vn4','var')
    V.Vn4=Vn4;  end
  if exist('Vnorms','var')
    V.Vnorms=Vnorms;  end
  if exist('Vtexture','var')
    V.Vtexture=Vtexture;  end
end

function Lyn=removespace(Lyn)
% A not an elegant way to remove
% surplus space
Lyn=strtrim(Lyn);
Lyn=strrep(Lyn,'       ',' '); % 8-2 .. 12-6
Lyn=strrep(Lyn,'    ',' '); % 5-2 6-3 4-1
Lyn=strrep(Lyn,'  ',' '); % 3-2 2-1
Lyn=strrep(Lyn,'  ',' ');
Lyn=strrep(Lyn,char([13 10]),''); % remove cr/lf
Lyn=strrep(Lyn,char([10]),''); % remove lf


function plot2DPlane(x1,x2,y1,y2,h_newfig)

if h_newfig
    figure;
    set(gcf,'position',[500,100,1000,650])
    set(gcf,'color','w');
end
set(gca,'visible','off')
mArrow2(x1,0,x2,0,{'color','k'});
mArrow2(0,y1,0,y2,{'color','k'});
xlim([x1 x2])
ylim([y1 y2])

for i = (x1+1):(x2-1)
    line([i i],[-0.05 0.05],'color','k')
    if i<=0
        t= text(i-0.2, -0.3,num2str(i));
    else
        t= text(i-0.05, -0.3,num2str(i));
    end
    t.FontSize=15;

end

for i = (y1+1):(y2-1)
    line([-0.05 0.05],[i i],'color','k')

    if i<0
        t = text(-0.4, i,num2str(i));
    elseif i>0
        t = text(-0.3, i,num2str(i));
    end
    t.FontSize = 15;
end
t = text(x2*0.9,0.3,'x');
t.FontSize = 15;
t = text(0.2,y2*0.9,'y');
t.FontSize = 15;
axis square


function [GPUDeviceNames, GPUDeviceIdx, GPUDeviceCC] = hlp_getGPUDeviceNames(minComputeCapability)
% Return the names of all GPU devices on this machine
% This requires the Parallel Computing Toolbox
% Devices with Compute Capability less than minComputeCapability are
% ignored
% The Index of each device is returned in GPUDeviceIdx
%
% Author: Tim Mullen, SCCN/INC/UCSD 2014

if nargin<1
    minComputeCapability = 1.3; end
ws = warning('off','all');
dcount = gpuDeviceCount;
GPUDeviceNames = [];
GPUDeviceIdx   = [];
GPUDeviceCC    = [];

% save selected device
gs = gpuDevice();
for k=1:dcount
    % select the device
    if gs.Index==k
        g=gs;
    else
        g=gpuDevice(k);
    end
    % skip devices with compute capability less than minComputeCapability
    GPUDeviceCC(k) = str2double(g.ComputeCapability);
    if GPUDeviceCC(k) < minComputeCapability
        continue; end
    % get name and index of the device
    GPUDeviceNames{end+1} = g.Name;
    GPUDeviceIdx(end+1)   = g.Index;
end
% restore gpu device
gpuDevice(gs.Index);
warning(ws);


function p = uplus(p)
%UPLUS        Polynomial unary plus  + p
%

% written  08/27/00     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, improved performance
%


function candoit = canGetGradient(problem)
% Checks whether the gradient can be computed for a problem structure.
%
% function candoit = canGetGradient(problem)
%
% Returns true if the gradient of the cost function can be computed given
% the problem description, false otherwise.
%
% See also: canGetCost canGetDirectionalDerivative canGetHessian

% This file is part of Manopt: www.manopt.org.
% Original author: Nicolas Boumal, Dec. 30, 2012.
% Contributors:
% Change log:

    candoit = isfield(problem, 'grad') || isfield(problem, 'costgrad') || ...
              canGetEuclideanGradient(problem);

end


function [ a1, a2 ] = i4vec_swap ( n, a1, a2 )

%*****************************************************************************80
%
%% I4VEC_SWAP swaps the entries of two I4VEC's.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 April 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of entries in the arrays.
%
%    Input, integer A1(N), A2(N), the vectors to swap.
%
%    Output, integer A1(N), A2(N), the swapped vectors.
%
  a3(1:n) = a1(1:n);
  a1(1:n) = a2(1:n);
  a2(1:n) = a3(1:n);

  return
end


function S=int2rgbm(R,G,B)
%INT2RGBM Convert intensity arrays to RGB movie.
%   INT2RGBM(R,G,B) converts separate 3-D intensity movies R, G,
%   and B, representing the red, green, and blue color planes of
%   an RGB video, respectively, into a 4-D RGB movie array.

% Copyright 2003 The MathWorks, Inc.
% $Revision: 1.1 $ $Date: 2004/12/17 02:43:25 $

error(nargchk(3,3,nargin));
sz=size(R);
sz=[sz(1:2) 1 sz(3)];
S = cat(3,reshape(R,sz),reshape(G,sz),reshape(B,sz));


function n = p13_n ( )

%*****************************************************************************80
%
%% P13_N returns the number of variables for problem 13.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 March 2000
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer N.  If N is positive, N represents the
%    only legal value for N for this problem.  If N is
%    negative, the absolute value of N is the least legal
%    value of N, but other values are allowable.
%
  n = - 1;

  return
end


%% Load Images
wallpaper1=imread('Nike.jpg');
wallpaper2=imread('Fire.jpg');

%% Display Wallpaper1
image(wallpaper1);
axis equal; grid off;

%% Display Wallpaper2
image(wallpaper2);
axis equal; grid off;

%% Scale and Display Wallpaper1
darkerlogo=0.4*wallpaper1;
image(darkerlogo);
axis equal; grid off;

%% Add images
% Image fusion is made here ;)
fusion=darkerlogo+wallpaper2;
image(fusion);
axis equal; grid off;


function figbolden(pos,pv,m)
%FIGBOLDEN embolden, resize and recolour the current figure =(POS,PV,M)
%
% Inputs: pos = [xmin ymin width height] gives the lower left corner position and the window size in pixels
%               [width height] leaves the lower left corner alone
%               [width] has a standard aspect ratio of 4:3
%               [-width/height] leaves the area unchanged but fixes the aspect ratio
%         pv is a cell name containing attribute-value pairs.
%            default = {'FontName' 'Arial'; 'FontSize' 16; 'LineWidth' 2; 'MarkerSize' 8}
%            Note that the "listfonts" MATLAB command will list the available fonts
%         m is a mode string:
%                'l' lists the changes made
%                'd' append default pv settings (e.g. use [] for second argument)
%                'c' change default colours to improve contrast on a white background
%                    g->[0,0.7,0],c->[0,0.7,0.7],y->[0.83,0.83,0]
%                'x' suppresses all changes
%
% Bug: gives an error message if log axes have been used

%      Copyright (C) Mike Brookes 2003
%      Version: $Id: figbolden.m 9186 2016-12-13 08:51:37Z dmb $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

ps={'Title' 'XLabel' 'YLabel' 'Children'};
if nargin<3
    m='';
end
if nargin<2 || any(m=='d')
    pv={'FontName' 'Arial'; 'FontSize' 16; 'LineWidth' 2; 'MarkerSize' 8};
end
pp={'Symbol';'Wingdings'};      % protected fonts
if nargin<1
    pos=[];
end
mlist=any(m=='l');  % list changes
mnotx=~any(m=='x'); % do changes
scsz=get(0,'screensize');
if length(pos)
    po=get(gcf,'position');
    if length(pos)>2            % position is specified
        po(1:2)=pos(1:2);
        pos(1:2)=[];      % remove xmin,ymin
    end
    if length(pos)>1
        po(3:4)=pos(1:2);
    else
        if pos(1)>0
            po(3:4)=[1 0.75]*pos(1);
        else
            po(3:4)=[-pos(1) 1]*sqrt(-po(3)*po(4)/pos(1)); % preserve area
        end
    end
    set(gcf,'position',po);
end
if any(m=='c')
    cc='gcy';
    cv=[0,0.7,0;0,0.7,0.7;0.83,0.83,0];
    for ic=1:3
        hlist=findobj(gcf,'color',cc(ic));
        if length(hlist)
            if mnotx
                set(hlist,'color',cv(ic,:));
            end
            if mlist
            for ih=1:length(hlist)
                 fprintf(['change %f Color: ''%c'' -> [%g %g %g]\n'],hlist(ih),cc(ic),cv(ic,:));
            end
            end
        end
    end
end
hlist=get(gcf,'children');
while length(hlist)
    pl=get(hlist(1));
    %fprintf('list length = %d, handle = %f\n',length(hlist),hlist(1));
    for i=1:size(pv,1)
        if isfield(pl,pv{i,1})
            if i>1 || all(~strcmpi(get(hlist(1),pv{i,1}),pp))
                pval=get(hlist(1),pv{i,1});
                if ~all(size(pval)==size(pv{i,2})) || ~all(pval(:) == pv{i,2}(:))
                    if mnotx
                        set(hlist(1),pv{i,1},pv{i,2})
                    end
                    if mlist
                        if ischar(pval)
                            fch='s';
                        else
                            fch='g';
                        end
                        fprintf(['change %f %s: %' fch ' -> %' fch '\n'],hlist(1),pv{i,1},pval,pv{i,2});
                    end
                end
            end
        end
    end
    for i=1:length(ps)
        if isfield(pl,ps{i})
            hlist=[hlist; get(hlist(1),ps{i})];
            %fprintf('add %f:%s\n',hlist(1),ps{i});
        end
    end
    hlist(1)=[];
end


% LOADODS: Loads data from an open document spreadsheet (ods) file into a cell
%          array
%
% SYNTAX: data = loadods(filename,options)
%
% INPUTS:
%   filename:   String representing the path and name of the ods file
%   options:    Structural variable containing optional arguments
%
% OUTPUTS:
%   data:       MxN cell array containing data from the spreadsheet
%
% OPTIONS:
%   sheet_name: Name of a specific sheet to load [defaults to the first sheet]
%   blank:      Value to store for blank spreadsheet cells [NaN]
%
% VERSION: 1.0
%

%Antonio Quarta - sgheppy88@gmal.com
%
% based on Alex Marten loadods.m function

function data = loadods(filename,opt1,opt2)
	% Set default options
            if nargin<2, sheetn = '';bchar=nan; end
            if nargin==2
                if  ~ischar(opt1)
                    sheetn = opt1;
                    bchar=nan;
                else
                    sheetn='';
                    bchar=opt2;
                end
            end
            if nargin==3
                sheetn = opt1;
                bchar=opt2;
            end

	% Check for the existence of the ods file
	if exist(filename)~=2
		error('The file does not exist');
	end

	% Create a temporary directory to unzip the ods file into
	if ~mkdir(tempdir,filename)
		error('Permission error');
	end
	dir_temp = strcat(tempdir,filename);

	% Unzip the contents of the ods file
	unzip(filename,dir_temp);

	% Load the XML file containing the spreadsheet data
	try
 		XMLfile = xmlread(strcat(dir_temp,'/content.xml'));
	catch
	   error('Unable to read the spreadsheet data');
	end

	% Parse down to the <office:spreadsheet> node

	nodes = XMLfile.getChildNodes;
        nodes2=nodes;
        i=0;
        trovato=0;
        while (~trovato && i < nodes.getLength )
            if (nodes.item(i).getNodeName ==  'office:document-content')
                node=nodes.item(i);
                nodes = node.getChildNodes;
                i=0;
            end
            if (nodes.item(i).getNodeName ==  'office:body')
                node=nodes.item(i);
                nodes = node.getChildNodes;
                i=0;
            end
            if (nodes.item(i).getNodeName ==  'office:spreadsheet')
                node=nodes.item(i);
                nodes = node.getChildNodes;
                trovato=1;
            end
            i=i+1;
        end

	% Find the requested sheet by name or default to the first sheet
	if ~isempty(sheetn)
		numSheets = nodes.getLength;
		for count = 1:numSheets
			sheet = nodes.item(count-1);
			if strcmp(get_attribute(sheet,'table:name'),sheetn)
				break
			end
		end
	else
            i=0;
            trovato=0;
            while (~trovato && i < nodes.getLength)
                if( nodes.item(i).getNodeName == 'table:table')
                    sheet = nodes.item(i);

                trovato=1;
               end
               i=i+1;
            end
	end

	% Get the begin of rows
 	nodes = sheet.getChildNodes;
	num_nodes = nodes.getLength;
	num_cols = 0;
	        for count = 1:num_nodes
		node = nodes.item(count-1);
            	if strcmp(char(node.getNodeName),'table:table-row')
                    count = count-2;
			break
		end
	end

	% Get the number of rows
	num_rows = num_nodes-count-1;

	% Initialize memory for the data
	data = cell(1,1);

	% Extract the data for the sheet
        rn=0;
        numrep=0;
	for row_num = 1:num_rows
            if ( ~strcmp(nodes.item(count+row_num).getNodeName,'#text') ...
                 && exist_validvalue( nodes.item(count+row_num)) )
                rn=rn+1;
                row = nodes.item(count+row_num);
                cols = row.getChildNodes;
                col_num = 0;
                num_items = cols.getLength-1;

                for item_num = 0:num_items
                    if ( ~strcmp(cols.item(item_num).getNodeName,'#text') ...
                         && exist_attribute(cols.item(item_num), ...
                                            'office:value') )
                        col = cols.item(item_num);
                        if (exist_attribute(col, ...
                                            'table:number-columns-repeated'))
                            numrep = str2num(get_attribute(col,['table:' ...
                                                'number-columns-repeated']));
                        end
                        value_type = get_attribute(col,'office:value-type');
                        if strcmp(value_type,'string')
                            temp = col.getChildNodes;
                            temp = temp.item(0);
                            temp = temp.getChildNodes;
                            temp = temp.item(0);
                            if any(strcmp(methods(temp),'getData'))
                                    value = char(temp.getData);
                            else
                                value = options.blank;
                            end
                        elseif strcmp(value_type,'float')
                            value = str2num(get_attribute(col,'office:value'));
                        else
                            value = bchar;
                        end
                        if numrep
                            for i=1:numrep
                            col_num = col_num+1;
                            data{rn,col_num} = value;
                            end
                            numrep=0;
                        else
                            col_num = col_num+1;
                            data{rn,col_num} = value;
                        end
                    end
                end
            end

 end

	% Remove the temporary files
	if ~rmdir(dir_temp,'s')
		warning('Temporary files could not be removed');
	end

end

% Returns the value of the attribute_name in node
function attribute = get_attribute(node,attribute_name)
	attribute = [];
	if node.hasAttributes
		attributes = node.getAttributes;
		num_attributes = attributes.getLength;
		for count = 1:num_attributes
			item = attributes.item(count-1);
		 	if strcmp(char(item.getName),attribute_name)
				attribute = char(item.getValue);
			end
		end
	end
end
function attribute = exist_attribute(node,attribute_name)
    if node.hasAttributes
        attributes=node.getAttributes;
        num_attributes=attributes.getLength;
        for count = 1:num_attributes
            item= attributes.item(count-1);
            if(strcmp(char(item.getName),attribute_name))
                attribute=1;
                return ;
            end
        end
        attribute=0;
        return ;
    end
    attribute=0;
    return ;
end
% It will return 1 if row contains any cells with a valid value.
% node is valid row
function result = exist_validvalue( node )
    cols = node.getChildNodes;
    col_num = 0;
    num_items = cols.getLength-1;
    for item_num = 0:num_items
        if (  ~strcmp(cols.item(item_num).getNodeName,'#text') ...
                         && exist_attribute(cols.item(item_num), ...
                                            'office:value') )
            result = 1 ;
            return ;
        end
    end
    result = 0;
    return ;
end


function cg_rc_test ( )

%*****************************************************************************80
%
%% CG_RC_TEST tests the CG_RC library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 January 2013
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CG_RC_TEST:\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the CG_RC library.\n' );

  cg_test01 ( );
  cg_test02 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CG_RC_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function r4_normal_01_test ( )

%*****************************************************************************80
%
%% R4_NORMAL_01_TEST tests R4_NORMAL_01.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 July 2006
%
%  Author:
%
%    John Burkardt
%
  seed = 123456789;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'R4_NORMAL_01_TEST\n' );
  fprintf ( 1, '  R4_NORMAL_01 computes a sequence of \n' );
  fprintf ( 1, '  normally distributed pseudorandom numbers.\n' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  The initial seed is %d\n', seed );
  fprintf ( 1, '\n' );

  for i = 1 : 10
    [ r, seed ] = r4_uniform_01 ( seed );
    fprintf ( 1, '  %6d  %14f\n', i, r );
  end

  return
end


%PARSEEXPR Parses a string expression.
%
%   [ S_EXPR, CSUBEXPR ] = PARSEEXPR( S_EXPR, S_SUBEXPR, C_ALLOWEXPR )
%   Parses the string expression in S_EXPR and returns a cell array
%   CSUBEXPR with variable expressions to process. Also returns a modified
%   expression S_EXPR which has the sub variable names substituted with
%   'S_SUBEXPR(:,I)' where I is the index in CSUBEXPR to the corresponding
%   variable. This enables a call to EVAL(S_EXPR) after the expressions in
%   CSUBEXPR has been computed and copied to the S_SUBEXPR array. The
%   optional array C_ALLOWEXPR allows strings as subexpressions (which
%   function names would otherwise be removed).
%
%   See also SYMVARBE

% Copyright 2013-2022 Precise Simulation, Ltd.


function[h]=hlines(y,sty)
%HLINES   Add horizontal lines to a plot.
%
%   HLINES(Y,STYLE) puts horizontal lines at locations Y having style
%   described by the string STYLE.  HLINES draws the lines to fit the
%   current axis.
%
%   The SYTLE strings follow the format specified in LINESTYLE.  Thus
%   STYLE='2b--' draws blue dotted lines of width 2.
%
%   HLINES(Y) uses the default STYLE='g--', a green dashed line.
%
%   H=HLINES(...) returns an array of handles H to the lines.
%
%   See also VLINES, DLINES.
%   _________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2000--2008 J.M. Lilly --- type 'help jlab_license' for details

if strcmpi(y,'--t')
    return
end

if nargin==1
	sty='g--';
end

hold on
y=y(:)';
ax=axis;
x1=ax(1)*ones(size(y));
x2=ax(2)*ones(size(y));
y=[y;y];
x=[x1;x2];
h=plot(x,y);
linestyle(h,sty);
axis(ax)

if nargout==0
   clear h
end


function cm = getColorMap(num_colors)
%GETCOLORMAP    Return default k-Wave color map.
%
% DESCRIPTION:
%       getColorMap returns the default color map used for display and
%       visualisation across the k-Wave Toolbox. Zero values are displayed
%       as white, positive values are displayed as yellow through red to
%       black, and negative values are displayed as light to dark
%       blue-greys. If no value for num_colors is provided, cm will have
%       256 colors.
%
% USAGE:
%       cm = getColorMap()
%       cm = getColorMap(num_colors)
%
% OPTIONAL INPUTS:
%       num_colors  - number of colors in the color map (default = 256)
%
% OUTPUTS:
%       cm          - three column color map matrix which can be applied
%                     using colormap
%
% ABOUT:
%       author      - Bradley Treeby
%       date        - 3rd July 2009
%       last update - 17th July 2009
%
% This function is part of the k-Wave Toolbox (http://www.k-wave.org)
% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox
%
% See also colormap

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

% set literals
if nargin == 0
    neg_pad = 48;
    num_colors = 256;
else
    neg_pad = round(48*num_colors/256);
end

% define colour spectrums
neg = bone(num_colors/2 + neg_pad);
neg = neg(1 + neg_pad:end, :);
pos = flipud(hot(num_colors/2));

% create custom colour map
cm = [neg; pos];