% op_plotspec.m
% Jamie Near, McGill University 2015.
%
% USAGE:
% out=op_plotspec(in,ppmmin,ppmmax,xlab,ylab,tit);
%
% DESCRIPTION:
% Plot the MR spectrum in the frequency domain.
%
% INPUTS:
% in     = input data in matlab structure format.  This argument can be a
%          MATLAB structure (formatted according to the FID-A structure
%          format), or it can be a cell array, where the elemenets of each
%          cell are FID-A structures.  In the latter case, each spectrum in
%          the structure will be plotted, with the option of a vertical
%          offset.
% ppmmin = lower limit of ppm scale to plot (optional.  Default = 0.2 ppm).
% ppmmax = upper limit of ppm scale to plot (optional.  Default = 5.2 ppm).
% xlab   = Label for the x-axis (optional.  Default = 'Frequency (ppm)');
% ylab   = label for the y-axis (optional.  Default = '');
% tit    = label for the title of the plot (optional.  Default = '');
%
% OUTPUTS:
% out    = Figure handle.

function out=op_plotspec(in,ppmmin,ppmmax,xlab,ylab,tit)

if nargin<6
    tit='';
    if nargin<5
        ylab='';
        if nargin<4
            xlab='Frequency (ppm)';
            if nargin<3
                ppmmax=5.2;
                if nargin<2
                    ppmmin=0.2;
                    if nargin<1
                        error('ERROR: no input spectrum specified.  Aborting!!');
                    end
                end
            end
        end
    end
end

if isstruct(in)
    if ndims(squeeze(in.fids))>2
        disp('More than 1 dimension detected in addition to the frequency dimension.');
        disp('Which dimension would you like to be displayed? ');
        if in.dims.coils
            disp(['     Enter: ''' num2str(in.dims.coils) ''' to display signal from all RF channels.']);
        end
        if in.dims.averages
            disp(['     Enter: ''' num2str(in.dims.averages) ''' to display signal from all averages.']);
        end
        if in.dims.subSpecs
            disp(['     Enter: ''' num2str(in.dims.subSpecs) ''' to display signal from all subspectra.']);
        end
        if in.dims.extras
            disp(['     Enter: ''' num2str(in.dims.extras) ''' to display signal from the ''extras'' dimension.']);
        end
        dim=input('............ ');
    else
        dim=0;
    end
    fignum=figure;
    if ~dim
        out=plot(in.ppm,real(squeeze(in.specs)));
    elseif dim==2
        out=plot(in.ppm,real(squeeze(in.specs(:,:,1))));
    elseif dim==3
        out=plot(in.ppm,real(squeeze(in.specs(:,1,:,1))));
    elseif dim==4
        out=plot(in.ppm,real(squeeze(in.specs(:,1,1,:,1))));
    elseif dim==5
        out=plot(in.ppm,real(squeeze(in.specs(:,1,1,1,:))));
    end
    xlim([ppmmin ppmmax]);
    set(gca,'XDir','reverse');
    set(gca,'FontSize',16);
    if isempty(ylab)
        set(gca,'YColor','w');
    else
        set(gca,'YColor','k');
    end
    set(gca,'XColor','k');
    set(gca,'Color','w');
    set(gcf,'Color','w');
    box off;
    title(tit);
    xlabel(xlab,'FontSize',20);
    ylabel(ylab,'FontSize',20);
    Fig1Ax1 = get(fignum, 'Children');
    Fig1Ax1Line1 = get(Fig1Ax1, 'Children');
    set(Fig1Ax1Line1, 'LineWidth', 1.2);
    %set(Fig1Ax1Line1,'MarkerSize', 10);
elseif iscell(in)
    if ndims(squeeze(in{1}.specs))>2
        disp('More than 1 dimension detected in addition to the frequency dimension.');
        disp('Which dimension would you like to be displayed? ');
        if in{1}.dims.coils
            disp(['     Enter: ''' num2str(in{1}.dims.coils) ''' to display signal from all RF channels.']);
        end
        if in{1}.dims.averages
            disp(['     Enter: ''' num2str(in{1}.dims.averages) ''' to display signal from all averages.']);
        end
        if in{1}.dims.subSpecs
            disp(['     Enter: ''' num2str(in{1}.dims.subSpecs) ''' to display signal from all subspectra.']);
        end
        if in{1}.dims.extras
            disp(['     Enter: ''' num2str(in{1}.dims.extras) ''' to display signal from the ''extras'' dimension.']);
        end
        dim=input('............ ');
    else
        dim=0;
    end
    figure;
    if ~dim
        out=plot(in{1}.ppm,real(in{1}.specs));
    elseif dim==2
        out=plot(in{1}.ppm,real(squeeze(in{1}.specs(:,:,1))));
    elseif dim==3
        out=plot(in{1}.ppm,real(squeeze(in{1}.specs(:,1,:,1))));
    elseif dim==4
        out=plot(in{1}.ppm,real(squeeze(in{1}.specs(:,1,1,:,1))));
    elseif dim==5
        out=plot(in{1}.ppm,real(squeeze(in{1}.specs(:,1,1,1,:))));
    end
    ylabel('ARB UNITS');
    disp('Multiple input spectra detected!! ')
    stagger=input('Please enter the desired vertical spacing of the spectra in ARB UNITS:  ');
    close;
    fignum=figure;
    hold
    colours=distinguishable_colors(length(in));
    for n=1:length(in)
        if ~dim
            out=plot(in{n}.ppm,real(in{n}.specs)+(n-1)*stagger,'Color',colours(n,:));
        elseif dim==2
            out=plot(in{n}.ppm,real(squeeze(in{n}.specs(:,:,1)))+(n-1)*stagger,'Color',colours(n,:));
        elseif dim==3
            out=plot(in{n}.ppm,real(squeeze(in{n}.specs(:,1,:,1)))+(n-1)*stagger,'Color',colours(n,:));
        elseif dim==4
            out=plot(in{n}.ppm,real(squeeze(in{n}.specs(:,1,1,:,1)))+(n-1)*stagger,'Color',colours(n,:));
        elseif dim==5
            out=plot(in{n}.ppm,real(squeeze(in{n}.specs(:,1,1,1,:)))+(n-1)*stagger,'Color',colours(n,:));
        end
        xlim([ppmmin ppmmax]);
        set(gca,'XDir','reverse');
        set(gca,'FontSize',16);
        if isempty(ylab)
            set(gca,'YColor','w');
        else
            set(gca,'YColor','k');
        end
        set(gca,'XColor','k');
        set(gca,'Color','w');
        set(gcf,'Color','w');
        box off;
        title(tit);
        xlabel(xlab,'FontSize',20);
        ylabel(ylab,'FontSize',20);
        Fig1Ax1 = get(fignum, 'Children');
        Fig1Ax1Line1 = get(Fig1Ax1, 'Children');
        set(Fig1Ax1Line1, 'LineWidth', 1.2);
    end
else
    error('ERROR:  Input data format not recognized.  ABORTING!!');
end


classdef TestUndistort
    %TestUndistort

    methods (Static)
        function test_1
            im = uint8([...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 1 1 1 0 0 0 0;...
                0 0 0 1 1 1 0 0 0 0;...
                0 0 0 1 1 1 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
            ]);
            result = cv.undistort(im, eye(3), []);
            validateattributes(result, {class(im)}, {'size',size(im)});
            assert(isequal(result, im));
        end

        function test_error_argnum
            try
                cv.undistort();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end


function ft = f13_title ( )

%*****************************************************************************80
%
%% F13_TITLE returns the title for function f13.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 August 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string FT, the function title.
%
  ft = 'Rescaled Runge function';

  return
end


function i4vec_part_test ( )

%*****************************************************************************80
%
%% I4VEC_PART_TEST tests I4VEC_PART.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 April 2009
%
%  Author:
%
%    John Burkardt
%
  n = 5;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'I4VEC_PART_TEST\n' );
  fprintf ( 1, '  I4VEC_PART partitions an integer.\n' );

  nval = 17;
  fprintf ( 1, '\n' );
  fprintf ( 1, '  NVAL = %d\n', nval );

  a = i4vec_part ( n, nval );

  i4vec_print ( n, a, '  Partitioned:' )

  nval = -49;
  fprintf ( 1, '\n' );
  fprintf ( 1, '  NVAL = %d\n', nval );

  a = i4vec_part ( n, nval );

  i4vec_print ( n, a, '  Partitioned:' );

  return
end


function mn = r8cvv_size ( m, nr )

%*****************************************************************************80
%
%% R8CVV_SIZE determines the size of an R8CVV.
%
%  Discussion:
%
%    An R8CVV is a "vector of vectors" of R8's.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 November 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the number of rows in the array.
%
%    Input, integer NR(M), the size of each row.
%
%    Output, integer MN, the size of the cell array.
%
  mn = sum ( nr(1:m) );

  return
end


function [bcx,bcy] = specific_flow(xbd,ybd)
%tightcavity_flow   Reference problem 5.3 alternative inflow condition
%   [bcx,bcy] = specific_flow(xbd,ybd);
%   input
%          xbd          x coordinate vector
%          ybd          y coordinate vector
%
%   specifies watertight cavity flow boundary condition
%   IFISS function: DJS; 6 March 2005.
% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage
bcx=0*xbd; bcy=0*xbd;
k=find(ybd==1 & xbd>-1 & xbd<1); bcx(k)=1;
return


function i4mat_print ( m, n, a, title )

%*****************************************************************************80
%
%% I4MAT_PRINT prints an I4MAT.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 September 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns of the matrix.
%
%    Input, integer A(M,N), an M by N matrix to be printed.
%
%    Input, string TITLE, a title.
%
  i4mat_print_some ( m, n, a, 1, 1, m, n, title );

  return
end


function next = next_boundary_node_q9 ( node )

%*****************************************************************************80
%
%% NEXT_BOUNDARY_NODE_Q9 returns the next boundary node in a Q9 element.
%
%  Reference Element Q9:
%
%    |
%    1  4--7--3
%    |  |     |
%    |  |     |
%    S  8  9  6
%    |  |     |
%    |  |     |
%    0  1--5--2
%    |
%    +--0--R--1-->
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NODE, the index of the current node.  An input
%    value of 0 (or any "unusual" value") indicates that the
%    first edge node is desired.
%
%    Output, integer NEXT, the index of the next edge node.
%
  if ( node == 1 )
    next = 5;
  elseif ( node == 5 )
    next = 2;
  elseif ( node == 2 )
    next = 6;
  elseif ( node == 6 )
    next = 3;
  elseif ( node == 3 )
    next = 7;
  elseif ( node == 7 )
    next = 4;
  elseif ( node == 4 )
    next = 8;
  else
    next = 1;
  end

  return
end


function [ a, b ] = p00_lim ( problem )

%*****************************************************************************80
%
%% P00_LIM returns the integration limits for any problem.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 September 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer PROBLEM, the problem index.
%
%    Output, real A(2), B(2), the lower and upper limits of integration.
%
  if ( problem == 1 )
    [ a, b ] = p01_lim ( );
  elseif ( problem == 2 )
    [ a, b ] = p02_lim ( );
  elseif ( problem == 3 )
    [ a, b ] = p03_lim ( );
  elseif ( problem == 4 )
    [ a, b ] = p04_lim ( );
  elseif ( problem == 5 )
    [ a, b ] = p05_lim ( );
  elseif ( problem == 6 )
    [ a, b ] = p06_lim ( );
  elseif ( problem == 7 )
    [ a, b ] = p07_lim ( );
  elseif ( problem == 8 )
    [ a, b ] = p08_lim ( );
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'P00_LIM - Fatal error!\n' );
    fprintf ( 1, '  Illegal problem index = %d\n', problem );
    error ( 'P00_LIM - Fatal error!\n' );
  end

  return
end


function root_num = p13_root_num ( )

%*****************************************************************************80
%
%% P13_ROOT_NUM returns the number of known roots for problem 13.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 May 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer ROOT_NUM, the number of known roots.
%
  root_num = 1;

  return
end


function next = next_boundary_node_ql ( node )

%*****************************************************************************80
%
%% NEXT_BOUNDARY_NODE_QL returns the next boundary node in a QL element.
%
%  Reference Element QL:
%
%    |
%    1  4---5---6
%    |  |       |
%    |  |       |
%    S  |       |
%    |  |       |
%    |  |       |
%    0  1---2---3
%    |
%    +--0---R---1-->
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NODE, the index of the current node.  An input
%    value of 0 (or any "unusual" value") indicates that the
%    first edge node is desired.
%
%    Output, integer NEXT, the index of the next edge node.
%
  if ( node == 1 )
    next = 2;
  elseif ( node == 2 )
    next = 3;
  elseif ( node == 3 )
    next = 6;
  elseif ( node == 6 )
    next = 5;
  elseif ( node == 5 )
    next = 4;
  else
    next = 1;
  end

  return
end


function exact = p00_exact ( problem, dim_num )

%*****************************************************************************80
%
%% P00_EXACT returns the exact integral for any problem.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer PROBLEM, the number of the desired test problem.
%
%    Input, integer DIM_NUM, the dimension of the problem.
%
%    Output, real EXACT, the exact value of the integral.
%
  if ( problem == 1 )
    exact = p01_exact ( dim_num );
  elseif ( problem == 2 )
    exact = p02_exact ( dim_num );
  elseif ( problem == 3 )
    exact = p03_exact ( dim_num );
  elseif ( problem == 4 )
    exact = p04_exact ( dim_num );
  elseif ( problem == 5 )
    exact = p05_exact ( dim_num );
  elseif ( problem == 6 )
    exact = p06_exact ( dim_num );
  elseif ( problem == 7 )
    exact = p07_exact ( dim_num );
  elseif ( problem == 8 )
    exact = p08_exact ( dim_num );
  elseif ( problem == 9 )
    exact = p09_exact ( dim_num );
  elseif ( problem == 10 )
    exact = p10_exact ( dim_num );
  elseif ( problem == 11 )
    exact = p11_exact ( dim_num );
  elseif ( problem == 12 )
    exact = p12_exact ( dim_num );
  elseif ( problem == 13 )
    exact = p13_exact ( dim_num );
  elseif ( problem == 14 )
    exact = p14_exact ( dim_num );
  elseif ( problem == 15 )
    exact = p15_exact ( dim_num );
  elseif ( problem == 16 )
    exact = p16_exact ( dim_num );
  elseif ( problem == 17 )
    exact = p17_exact ( dim_num );
  elseif ( problem == 18 )
    exact = p18_exact ( dim_num );
  elseif ( problem == 19 )
    exact = p19_exact ( dim_num );
  elseif ( problem == 20 )
    exact = p20_exact ( dim_num );
  elseif ( problem == 21 )
    exact = p21_exact ( dim_num );
  elseif ( problem == 22 )
    exact = p22_exact ( dim_num );
  elseif ( problem == 23 )
    exact = p23_exact ( dim_num );
  elseif ( problem == 24 )
    exact = p24_exact ( dim_num );
  elseif ( problem == 25 )
    exact = p25_exact ( dim_num );
  elseif ( problem == 26 )
    exact = p26_exact ( dim_num );
  elseif ( problem == 27 )
    exact = p27_exact ( dim_num );
  elseif ( problem == 28 )
    exact = p28_exact ( dim_num );
  elseif ( problem == 29 )
    exact = p29_exact ( dim_num );
  elseif ( problem == 30 )
    exact = p30_exact ( dim_num );
  elseif ( problem == 31 )
    exact = p31_exact ( dim_num );
  elseif ( problem == 32 )
    exact = p32_exact ( dim_num );
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'P00_EXACT - Fatal error!\n' );
    fprintf ( 1, '  Illegal problem number = %d\n', problem );
    error ( 'P00_EXACT - Fatal error!' );
  end

  return
end


function out = get(f, prop)
%GET   GET method for the CHEBTECH1 class
%   P = GET(F, PROP) returns the property P specified in the string PROP from
%   the CHEBTECH1 F.  The string PROP may be the name of a CHEBTECH1 property
%   (see the CHEBTECH and CHEBTECH1 classdef files for lists) or any of the
%   following strings:
%       'POINTS'          - 1st-kind Chebyshev grid corresponding to F.
%       'VALUES'          - Values of F at Chebyshev points.
%       'LVAL'            - Value of F at -1.
%       'RVAL'            - Value of F at +1.
%       'TECH'            - Handle to the CHEBTECH1 constructor. *
%       'VSCALE'          - Vertical scale of the CHEBTECH1.
%
% See also CHEBTECH, CHEBTECH1.

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

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DEVELOPER NOTE:
%  * Currently get(f, 'tech') returns a function handle to the tech constructor.
%    This may change in future to return instead an empty instance of the tech.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

switch prop
    case fieldnames(f)
        out = f.(prop);
    case 'points'
        out = f.points();
    case 'lval'
        out = lval(f);
    case 'rval'
        out = rval(f);
    case 'values'
        out = f.coeffs2vals(f.coeffs);
    case 'vscale'
        out = vscale(f);
    case 'tech'
        % TODO: Return function handle, or empty instance of the tech?
        out = @chebtech1;
    otherwise
        error('CHEBFUN:CHEBTECH1:get:propName', ...
            'Unknown property name ''%s'' for object of type CHEBTECH1.', prop);
end

end


function out = isnan(f)
%ISNAN   Test if a TRIGTECH has any NaN values.
%   ISNAN(F) returns TRUE if F has any NaN values and FALSE otherwise.
%
% See also ISFINITE, ISINF.

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

% Check if any values are NaN:
out = any(isnan(f.values(:)));

end


function r82col_print_part ( n, a, max_print, title )

%*****************************************************************************80
%
%% R82COL_PRINT_PART prints "part" of an R82COL.
%
%  Discussion:
%
%    An R82COL is an (N,2) array of R8's.
%
%    The user specifies MAX_PRINT, the maximum number of lines to print.
%
%    If N, the size of the vector, is no more than MAX_PRINT, then
%    the entire vector is printed, one entry per line.
%
%    Otherwise, if possible, the first MAX_PRINT-2 entries are printed,
%    followed by a line of periods suggesting an omission,
%    and the last entry.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 April 2015
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of entries of the vector.
%
%    Input, real A(N,2), the vector to be printed.
%
%    Input, integer MAX_PRINT, the maximum number of lines
%    to print.
%
%    Input, string TITLE, a title.
%
  if ( max_print <= 0 )
    return
  end

  if ( n <= 0 )
    return
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, '%s\n', title );
  fprintf ( 1, '\n' );

  if ( n <= max_print )

    for i = 1 : n
      fprintf ( 1, '  %4d  %14g  %14g\n', i, a(i,1), a(i,2) );
    end

  elseif ( 3 <= max_print )

    for i = 1 : max_print-2
      fprintf ( 1, '  %4d  %14g  %14g\n', i, a(i,1), a(i,2) );
    end
    fprintf ( 1, '  ....  ..............  ..............\n' );
    i = n;
    fprintf ( 1, '  %4d  %14g  %14g\n', i, a(i,1), a(i,2) );

  else

    for i = 1 : max_print - 1
      fprintf ( 1, '  %4d  %14g  %14g\n', i, a(i,1), a(i,2) );
    end
    i = max_print;
    fprintf ( 1, '  %4d  %14g  %14g  ...more entries...\n', i, a(i,1), a(i,2) );

  end

  return
end


function r8_uniform_01_test ( )

%*****************************************************************************80
%
%% R8_UNIFORM_01_TEST tests R8_UNIFORM_01.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 April 2009
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'R8_UNIFORM_01_TEST\n' );
  fprintf ( 1, '  R8_UNIFORM_01 produces a sequence of random values.\n' );

  seed = 123456789;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Using random seed %d\n', seed );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  SEED  R8_UNIFORM_01(SEED)\n' );
  fprintf ( 1, '\n' );
  for i = 1 : 10
    seed_old = seed;
    [ x, seed ] = r8_uniform_01 ( seed );
    fprintf ( 1, '  %12d  %14f\n', seed, x );
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Verify that the sequence can be restarted.\n' );
  fprintf ( 1, '  Set the seed back to its original value, and see that\n' );
  fprintf ( 1, '  we generate the same sequence.\n' );

  seed = 123456789;
  fprintf ( 1, '\n' );
  fprintf ( 1, '  SEED  R8_UNIFORM_01(SEED)\n' );
  fprintf ( 1, '\n' );

  for i = 1 : 10
    seed_old = seed;
    [ x, seed ] = r8_uniform_01 ( seed );
    fprintf ( 1, '  %12d  %14f\n', seed, x );
  end

  return
end


function value = p13_exact ( dim_num )

%*****************************************************************************80
%
%% P13_EXACT returns the exact integral for problem 13.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer DIM_NUM, the spatial dimension.
%
%    Output, real VALUE, the exact value of the integral.
%
  value = 0.0;

  return
end


function demoDrawPoint3d
%DEMODRAWPOINT3D Demo of drawPoint3d
%
%   Example
%     demoDrawPoint3d
%
%   See also
%

% ------
% Author: oqilipo
% Created: 2018-01-12, using R2017b
% Copyright 2018

%% Initialisation
ptsx = rand(1,5);
ptsy = rand(1,5);
ptsz = rand(1,5);

pts2 = rand(5,3);

%% 1
figure('color','w');
drawPoint3d(ptsx, ptsy, ptsz)
hold on
drawPoint3d(gca,pts2)
%% 2
figure('color','w')
drawPoint3d(pts2,'g.')
hold on
drawPoint3d(gca,ptsx, ptsy, ptsz,'r')
%% 3
figure('color','w')
props.Marker='o';
props.MarkerEdgeColor='r';
props.MarkerFaceColor='g';
props.LineStyle='none';
drawPoint3d(ptsx, ptsy, ptsz,props,'MarkerSize',12)
hold on
drawPoint3d(gca,pts2,props,'MarkerSize',5)
%% 4
figure('color','w')
drawPoint3d(ptsx, ptsy, ptsz,'MarkerSize',8,props,'Marker','s')
hold on
drawPoint3d(gca, pts2,'MarkerSize',12,props,'Marker','h')
%% 5
figure('color','w')
drawPoint3d(ptsx, ptsy, ptsz,props)
hold on
drawPoint3d(gca,pts2,props)


function [ y, m, d, f ] = now_to_ymdf_common ( )

%*****************************************************************************80
%
%% NOW_TO_YMDF_COMMON expresses the current date as a Common YMDF date.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer Y, M, D, real F,
%    the YMDF date.
%
  c = clock ( );

  y = c(1);
  m = c(2);
  d = c(3);
  h = c(4);
  n = c(5);
  s = c(6);
  mu = 0.0;

  f = mu;
  f = s + f / 1000.0;
  f = n + f / 60.0;
  f = h + f / 60.0;
  f = f / 24.0;

  return
end


function s = tifs2seq(file)
%TIFS2SEQ Create a MATLAB sequence from a multi-frame TIFF file.
%
%   Copyright 2002-2020 Gatesmark
%
%   This function, and other functions in the DIPUM Toolbox, are based
%   on the theoretical and practical foundations established in the
%   book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark
%   Press, 2020.
%
%   Book website: http://www.imageprocessingplace.com
%   License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt

% Get the number of frames in the multi-frame TIFF.
frames = size(imfinfo(file), 1);

% Read the first frame, preallocate the sequence, and put the first
% in it.
i = imread(file, 1);
s = zeros([size(i) 1 frames], 'uint8');
s(:,:,:,1) = i;

% Read the remaining TIFF frames and add to the sequence.
for i = 2:frames
    s(:,:,:,i) = imread(file, i);
end


function n = p22_n ( )

%*****************************************************************************80
%
%% P22_N returns the number of variables for problem 22.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 December 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 = 3;

  return
end


function [z,I,J] = joinvars(x,y)
%JOINVARS     joins sets of variables x and y into one set z
%
%   [z,I,J] = joinvars(x,y)
%
%On entry, string or string cell array x is a set of mutually disjoint variables,
%  and string or string cell array y is a set of mutually disjoint variables.
%On return, variables x and y are merged into z such that
%  z(I) corresponds to the set x, and z(J) corresponds to the set y.
%

% written  08/28/00     S.M. Rump
%

  % make sure, variables are stored in cell arrays (covers univariate case)
  if ~iscell(x)
    x = {x};
  end
  if ~iscell(y)
    y = {y};
  end

  nx = length(x);
  [z,dummy,IJ] = unique([x y]);
  I = IJ(1:nx);
  J = IJ(nx+1:end);


%SETFEATSIZE Set featsize of datafile
%
%   A = SETFEATSIZE(A,FEATSIZE)
%
% INPUT
%   A        - Datafile
%   FEATSIZE - Desired feature size,
%              Default: compute from first object in A
%
% OUTPUT
%   A       - Datafile
%
% DESCRIPTION
% If A is a dataset, its featsize is set. The featsize of a datafile
% is unclear as objects may have different sizes. For that reason
% the feature sizes of datafiles might better be set to 0, unless the
% objects are images of the same size.
%
% SEE ALSO (PRTools Guide)
% DATAFILES


function [ X Y ] = selPts
%[ X Y ] = selPts
%	manually select several points in current figure
%   selection is stopped when ESC is pressed

X = []; Y = [];
ctrlLen = 0;
while 1
	[X1 Y1] = ginput(1);
	if isempty(X1), break; end
	X = [X;X1];
	Y = [Y;Y1];
	plot(X1,Y1,'bo');
	ctrlLen = ctrlLen+1;
% 	text(X1+3,Y1,num2str(ctrlLen));
end

end


function cnndataout = cnntrain(cnndatain)
%CNNTRAIN Training of convolutional neural network.
%   CNNDATAOUT = CNNTRAIN(CNNDATAIN) Training of convolutional neural
%   network. Type
%
%     >> help cnninfo
%
%   at the prompt for a detailed description of all parameters.
%
%   NOTE: The custoim folder FCNNtoolbox must be in the MATLAB path.
%
%   TRAINING STARTING "FRESH." The inputs to cnntrain are the result of
%   running function cnninit: [cnn,fcnn] = cnninit(cnnparam), whose
%   outputs are the initialized cnn and fcnn. Additional inputs are as
%   listed below.
%
%   cnndatain.cnn = cnn
%   cnndatain.fcnn = fcnnn
%   cnndatain.Images
%   cnndatain.R
%   cnndatain.Epochs
%   cnndatain.MiniBatchSize
%   cnndatain.MSE (set to [] initially)
%   cnndatain.SmoothMSE (set to [] initially)
%
%   TRAINING IN MULTISTAGES.
%   When training takes a long time, it is helpful to train for a
%   manageable number of epochs and then repeat the process, but starting
%   with the last results of training. For this, we make the following
%   modifications in cnndatain before starting the next training session
%   if we want to do another training session without making any changes
%   to any of the cnndatain fields.
%
%   cnndatain = cnndataout;
%
%   If we want to make changes to any of the fields of structure
%   cnndatain, we make following the preceding line of code. For
%   example, to change the number of epochs and continue training, we
%   write:
%
%   cnndatain = cnndataout;
%   cnndatain.Epochs = some new value;
%
%   The other fields of cnndatain are not changed.
%
%   TRAINING STARTING WITH PRETRAINED CNN/FCNN If, instead of starting
%   with a freshly initialized CNN and FCNN, we want to start training
%   with previously-trained CNN and FCNN, we do it as follows. Suppose
%   that the saved the MATLAB workspace after some training session as
%   SavedCNNFCNN_200Epochs.mat. To continue training where the previous
%   training left off, we write:
%
%   load SavedCNNFCNN_200Epochs.mat
%   cnndatain = cnndataout;
%
%   The file SavedCNNFCNN_200Epochs.mat carries with it all the
%   parameters of the last application of cnninit and cnntrain from
%   which they were saved. Any changes in cnndatain, like the number of
%   Epochs, are implemented as explained before.
%
%   The other fields of cnndatain are not changed.
%
%
%   OUTPUTS
%   The outputs of this function in structure cnndataout, with fields:
%
%   cnndataout.cnn
%    The complete, trained cnn.
%
%   cnndataout.fcnn
%    The complete, trained fully-connected net
%
%   cnndataout.MSE
%    A vector containing the training MSE error values as a function of
%    epoch.
%
%   cnndataout.SmoothMSE
%    A smoothed version of cnndataout.MSE
%
%   Copyright 2002-2020 Gatesmark
%
%   This function, and other functions in the DIPUM Toolbox, are based
%   on the theoretical and practical foundations established in the
%   book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark
%   Press, 2020.
%
%   Book website: http://www.imageprocessingplace.com
%   License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt

% SETUP

% Check input image for size M-by-M-by-depth-by-NI, where M is the
% (square) image size, depth is the image depth (e.g., 1 for grayscale
% images and 3 for RGB images), and NI is the number of images.
if (ndims(cnndatain.Images) ~= 4)
   error('Images have to be of sizeM-by-M-by-depth-by-NI')
end

% cnn and fcnn.
cnn = cnndatain.cnn;
fcnn = cnndatain.fcnn;

% Number of cnn layers.
Lc = numel([cnn.NumLayerKernels]);
% Number of fcnn layers.
L = numel([fcnn.NumNodes]);

% Pixel values must be in the range [0,1].
if (max(cnndatain.Images(:)) > 1) || (min(cnndatain.Images(:)) < 0)
   error('Image pixels must be in the range [0,1]')
end

% The input image array of size M-by-M-by-depth-by-NI, where M is the
% (square) image size, depth is the image depth (e.g., 1 for
% grayscale images and 3 for RGB images), and NI is the number of
% images.
NI = size(cnndatain.Images,4);

% Minibatch size. Defaults to the number of patterns.
if ~isfield(cnndatain,'MiniBatchSize')
   cnndatain.MiniBatchSize = size(cnndatain.R,2);
end
MBS = cnndatain.MiniBatchSize;

% The num of images divided by the minibatch size must be an integer.
if rem(NI,MBS) ~= 0
   error('(num images)/(minibatch size) must be an integer')
end
batchReps = NI/MBS;

% Number of training epochs.
NE = cnndatain.Epochs;

% Training errors.
MSE = cnndatain.MSE;
SmoothMSE = cnndatain.SmoothMSE;

% TRAIN THE NETWORK.

h = waitbar(0,'Training the CNN . . . .');
for t = 1:NE
   % Randomize the order of the input images.
   r = randperm(NI);
   for j = 1:batchReps
      % Extract a random imagebatch of MBS images from the input images.
      minibatch = cnndatain.Images(:,:,:,r((j - 1)*MBS + 1 : j*MBS));

      % Extract the corresponding columns from input.R.
      batchR = cnndatain.R(:,r((j - 1)*MBS + 1 : j*MBS));

      % Feedforward through the CNN.
      cnn = cnnff(cnn,minibatch);

      % Feedforward through the FCNN.
      X = cnn(Lc).OutputVectors;
      fcnn = fcnnff(fcnn,X);

      % Backprop through fully-connected net.
      R = batchR;
      fcnn = fcnnbp(fcnn,R);

      % Backprop through cnn.
      delback = fcnn(1).D; % del vector fedback from the fcnn.
      cnn = cnnbp(cnn,delback);

      % Compute average gradients for the minibatch.
      cnn = cnngradients(cnn);

      % Update the cnn weights.
      cnn = cnnupdateweights(cnn);

      % Update the fcnn weights.
      fcnn = fcnnupdateweights(fcnn);

      % Output error.
      fcnnerror = 0.5*(fcnn(L).A - R);

      % Mean-squared error (MSE) for the current minibatch.
      currentMSE = sum(sum((fcnnerror).^2))/size(fcnnerror,2);

      % Update MSE and SmoothMSE.
      if isempty(MSE) % Initialize at beginning.
         MSE(1) = currentMSE;
         SmoothMSE(1) = currentMSE;
      end
      MSE(end + 1) = currentMSE;
      % For smoothing, you could also use MATLAB function smoothdata,
      % but it tends to be much more aggresive that the following
      % "lowpass" filter which is more local and results in a smoothed
      % function whose shape better preserves the nuances of the raw
      % data. If you prefer to use funcdtion smoothdata you can apply ot
      % externally to function cnndataout.MSE
      SmoothMSE(end + 1) = 0.9*SmoothMSE(end) + 0.1*currentMSE;

      waitbar(t/NE)

   end

end
close(h)

% OUTPUT THE TRAINED CNN, FCNN, AND THE MSE ERROR VECTORS.
% Save original inputs.
cnndataout = cnndatain;
% Update the parameters that changed in this function.
cnndataout.cnn = cnn;
cnndataout.fcnn = fcnn;
cnndataout.MSE = MSE;
cnndataout.SmoothMSE = SmoothMSE;


function dlap_rhs_print ( n, rhs )

%*****************************************************************************80
%
%% DLAP_RHS_PRINT prints the right hand side vector from a DLAP file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    31 January 2014
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Mark Seager,
%    A SLAP for the Masses,
%    Lawrence Livermore National Laboratory,
%    Technical Report UCRL-100267, December 1988.
%
%  Parameters:
%
%    Input, integer N, the order of the matrix.
%
%    Input, real RHS(N), the right hand side vector to be written.
%
   r8vec_print ( n, rhs, '  DLAP right hand side vector:' );

  return
end


%Author : Athi Narayanan S
%M.E, Embedded Systems,
%K.S.R College of Engineering
%Erode, Tamil Nadu, India.
%http://sites.google.com/site/athisnarayanan/

function mergedBlks = merge_blocks(data)

s = size(data);
mergedBlks = zeros((s(3) * s(1)), (s(4) * s(2)));

%Merging the Blocks
for i = 1 : s(3)
    for j = 1 : s(4)
        localBlk = data(:,:,i,j);
        rowStart = ((i - 1) * s(1)) + 1;
        rowEnd = i * s(1);
        colStart = ((j - 1) * s(2)) + 1;
        colEnd = j * s(2);
        mergedBlks(rowStart:rowEnd, colStart:colEnd) = localBlk;
    end
end


function varargout = msg(Flag, varargin)
% MSG Report process informations to the workspace.
% ------------------------------------------------------------------------------
% DESCRIPTION/NOTES
% With this function informations about processes and variables can be printed
% to the workspace.
% ------------------------------------------------------------------------------
% INPUT
% 1 [Flag]
%   Flag describing the scope of the report. Any Flag can be used, however,
%   the following flags have a special purpose:
%   S ... to define the start of a process
%   E ... to define the end of a process
%   V ... to report the value of a variable
%   T ... to report a text string
%   D ... to report a table (of data)
%   O ... to set persistant options for this function (e.g. log level)
%   Conventions for arbitrary flags:
%   I ... for output of informations
%   X ... for error output
%   W ... for warnings
%
% 2 [ProcHierarchy] (not required for flags V, T, D and O)
%   Cell describing the hierarchy of the process.
%
% 3 [Info] (required for all flags, except S, E, D and O)
%   String containing report information.
%
% 4 ['Prec', Prec] (optional for flag V)
%   Precision of variable output.
%
% 5 ['MaxPrec', MaxPrec] (optional for flag V)
%   Maximal precision output for variables (see examples section).
%
% 6 ['FieldWidth', FieldWidth] (optional for flag V)
%   Field width for variable output (see examples section).
%
% 7 ['LogLevel', LogLevel] (optional for all flags, except O)
%   Define the log level of the message. Possible values:
%   * 'basic' -> for output of basic information.
%   * 'debug' -> for output of detailed information.
%
% 8 ['SetLogLevel', SetLogLevel] (optional for flag O)
%   Define which messages are reported to the workspace. Possible values:
%   * 'basic'  -> output of messages with log level 'basic'.
%   * 'debug'  -> output of messages with log level 'basic' and 'debug'.
%   * 'off'    -> no message output.
%
% 9 'GetLogLevel' (optional for flag O)
%   Get actual log level.
%
% 10 ['SetLogfile', SetLogfile] (optional for flag O)
%    Define a logfile instead of displaying the output information on the
%    workspace.
% ------------------------------------------------------------------------------
% EXAMPLES
% 1 Report the start of a process and begin time measurement for this process.
%   msg('S', {'POINTCLOUD' 'ESTIMATE NORMALS'});
%
% 2 Report an info update for the same process.
%   msg('I', {'POINTCLOUD' 'ESTIMATE NORMALS'}, 'Normal estimation by PCA');
%
% 3 Report the end of the process.
%   msg('E', {'POINTCLOUD' 'ESTIMATE NORMALS'});
%
% 4 Print a variable.
%   msg('V', 6378137, 'Semi-major axis (GRS80)');
%
% 5 Print variable with specified precision.
%   msg('V', pi, 'pi', 'Prec', 7);
%
% 6 Print variable with definition of MaxPrec and FieldWidth.
%   msg('V', pi, 'pi', 'Prec', 7, 'MaxPrec', 10, 'FieldWidth', 20);
%
%   V :         3.1415927    = pi
%       12345678901234567890
%      >     FieldWidth     <
%                > MaxPrec  <
%                > Prec  <
%
% 8 Print a text string.
%   msg('T', 'A text information');
%
% 9 Print a data table.
%
%   tabularData.Caption = 'CAPTION OF DATA TABLE';
%   tabularData.ColumnCaptions     = {'value' 'usage'  'file'    % first row
%                                     ''      'yes/no' ''     }; % second row
%   tabularData.ColumnWidths       = [8        10       0     ];
%   tabularData.ColumnPrecs        = [2        NaN      NaN   ]; % NaN for char columns
%   tabularData.ColumnRightMargins = [1        3        0     ]; % optional
%
%   tabularData.Data = {7.654  'yes' 'file1.txt'
%                       6.3245 'no'  'file2_with_long_name.txt'
%                       8.12   'yes' 'file3.txt'};
%
%   tabularData.Notes = {'Note: files are located in folder ''D:\data\'''}; % optional
%
%   msg('D', tabularData);
%
% 10 Set log level to 'basic', so that only messages with log level equal to
%    'basic' are reported.
%    msg('O', 'SetLogLevel', 'basic');
%
% 11 Get actual log level.
%    origLogLevel = msg('O', 'GetLogLevel');
% ------------------------------------------------------------------------------
% philipp.glira@gmail.com
% ------------------------------------------------------------------------------

% Preparations -----------------------------------------------------------------

persistent logLevel % log level of output
if isempty(logLevel), logLevel = 'debug'; end % initialize

persistent logFile
if isempty(logFile), logFile = ''; end % initialize

% Set options
if strcmpi(Flag, 'O')

    % Set log level
    idx = find(strcmpi('SetLogLevel', varargin));
    if ~isempty(idx)
        logLevel = varargin{idx+1};
    end

    % Get log level
    idx = find(strcmpi('GetLogLevel', varargin));
    if ~isempty(idx)
        varargout{1} = logLevel;
    end

    % Set log file
    idx = find(strcmpi('SetLogFile', varargin));
    if ~isempty(idx)
        logFile = varargin{idx+1};
    end

    return;

% Retrieve log level of message
else

    % Check if log level of message is defined (without parsing all input arguments)
    idx = find(strcmpi('LogLevel', varargin));
    if ~isempty(idx) % if log level of message is defined
        logLevelMsg = varargin{idx+1};
        varargin(idx:idx+1) = []; % delete log level arguments (no parsing)
    else % if log level of message is NOT defined
        logLevelMsg = 'debug'; % default value
    end

end

% Check log level and eventually stop function ---------------------------------
% In order to save time, this section has to be placed at the beginning of the
% function

% If logLevel is set to off leave the function
if strcmpi(logLevel, 'off')
    return;

% If logLevel is set to basic ...
elseif strcmpi(logLevel, 'basic')

    % ... and log level of message is set to debug, leave the function
    if strcmpi(logLevelMsg, 'debug'), return; end

end

% ... continue with normal parsing of input arguments

% Input parsing ----------------------------------------------------------------

% Global parameters
p = inputParser;

if strcmpi(Flag, 'V')
    p.addRequired( 'Var'              , @(x) isnumeric(x) || islogical(x));
    p.addRequired( 'Info'             , @ischar);
    p.addParameter('Prec'         , 3 , @isnumeric);
    p.addParameter('MaxPrec'      , 9 , @isnumeric);
    p.addParameter('FieldWidth'   , 20, @isnumeric);

elseif any(strcmpi(Flag, {'S' 'E'}))
    p.addRequired(  'ProcHierarchy'    , @iscell);

elseif strcmpi(Flag, 'T')
    p.addRequired(  'Info'             , @ischar);

elseif strcmpi(Flag, 'D')
    p.addRequired(  'TabularData'      , @isstruct);

else
    p.addRequired(  'ProcHierarchy'    , @iscell);
    p.addRequired(  'Info'             , @ischar);
end

p.parse(varargin{:});
p = p.Results;

% Variable declaration ---------------------------------------------------------

persistent tictoc   % for time measurement

% Output string
out = [];

% Add time info to output ------------------------------------------------------

if any(strcmpi(Flag, {'V' 'T' 'D'}))
    % No time information, just empty string with same length
    tInfo = char( ones(1,numel(timeinfo)) *32 );

elseif strcmpi(Flag, 'S')
    tInfo = timeinfo;
    % Start timer for specific process
    tictoc.(genvarname([p.ProcHierarchy{:}])).tic = tic;

else
    % Elapsed time for specific process
    t = toc(tictoc.(genvarname([p.ProcHierarchy{:}])).tic);
    % No time information, just empty string with same length
    tInfo = char( ones(1,numel(timeinfo)) *32 );
    % Write elapsed time right-aligned into string
    tString = sprintf('+%.3fs', t);
    tInfo(end-numel(tString)+1:end) = tString;
end

out = [out tInfo];

% Add separator between two columns to output ----------------------------------

out = [out ' | '];

% Add flag to output -----------------------------------------------------------

out = [out Flag ' : '];

% Add process hierarchy string to output ---------------------------------------

if all(~strcmpi(Flag, {'V' 'T' 'D'}))
    for i = 1:numel(p.ProcHierarchy)
        switch i
            case 1
                procStr = upper(p.ProcHierarchy{i});
            otherwise
                procStr = [procStr ' > ' upper(p.ProcHierarchy{i})];
        end
    end
    out = [out procStr];
end

% Add info string to output ----------------------------------------------------

if ~any(strcmpi(Flag, {'S' 'E' 'V' 'T' 'D'}))
    out = [out ' : '];

    % If p.Info contains \n, replace them by left part of output
    logIdxSep = out == '|';
    leftPart = char( ones(1,numel(out)) *32 );
    leftPart(logIdxSep) = '|';
    p.Info = strrep(p.Info, sprintf('\n'), sprintf('\n%s', leftPart));

    out = [out p.Info];
end

% Add variable info to output --------------------------------------------------

if strcmpi(Flag, 'V')
    if p.Prec == 0, p.MaxPrec = p.MaxPrec+1; end
    out = [out sprintf('%*.*f%*s = %s', p.FieldWidth-p.MaxPrec+p.Prec, p.Prec, p.Var, p.MaxPrec-p.Prec, '', p.Info)];
end

% Add text info to output ------------------------------------------------------

if strcmpi(Flag, 'T')
    out = [out p.Info];
end

% Add tabular data to output ---------------------------------------------------

if strcmpi(Flag, 'D')

    % First: delete all columns containing only NaNs
    idx2del = [];
    for i = 1:size(p.TabularData.Data,2)
        if all(isnan([p.TabularData.Data{:,i}]))
            idx2del = [idx2del; i];
        end
    end
    p.TabularData.Data(:,idx2del) = [];
    p.TabularData.ColumnCaptions(:,idx2del) = [];
    p.TabularData.ColumnWidths(idx2del) = [];
    p.TabularData.ColumnPrecs(idx2del) = [];

    % Add column margins if not defined
    if ~isfield(p.TabularData, 'ColumnRightMargins')
        p.TabularData.ColumnRightMargins = [ones(1, size(p.TabularData.Data,2)-1) 0];
    end

    % Save prefix
    prefix = out;
    clear out

    % Separation line
    lengthSeparationLine = sum(p.TabularData.ColumnWidths) + sum(p.TabularData.ColumnRightMargins);
    if lengthSeparationLine < 80, lengthSeparationLine = 80; end
    out{1,1} = [prefix repmat('-', 1, lengthSeparationLine)];

    % Report table caption
    out{2,1} = [prefix p.TabularData.Caption];

    % Report column captions
    formatSpec = [];
    for col = 1:size(p.TabularData.ColumnCaptions,2)
        formatSpec = [formatSpec '%' num2str(p.TabularData.ColumnWidths(col)) 's' repmat(' ', 1,p.TabularData.ColumnRightMargins(col))];
    end
    formatSpec = strtrim(formatSpec); % remove trailing spaces
    for row = 1:size(p.TabularData.ColumnCaptions,1)
        out{end+1,1} = [prefix sprintf(formatSpec, p.TabularData.ColumnCaptions{row, :})];
    end

    % Report data
    formatSpec = [];
    for col = 1:size(p.TabularData.Data,2)
        if isnan(p.TabularData.ColumnPrecs(col))
            columnFormatSpec = ['%' num2str(p.TabularData.ColumnWidths(col)) 's'];
        else
            columnFormatSpec = ['%' num2str(p.TabularData.ColumnWidths(col)) '.' num2str(p.TabularData.ColumnPrecs(col)) 'f'];
        end
        formatSpec = [formatSpec columnFormatSpec repmat(' ', 1,p.TabularData.ColumnRightMargins(col))];
    end
    formatSpec = strtrim(formatSpec); % remove trailing spaces
    for row = 1:size(p.TabularData.Data,1)
        out{end+1,1} = [prefix sprintf(formatSpec, p.TabularData.Data{row, :})];
    end

    % Notes?
    if isfield(p.TabularData, 'Notes')
        for i = 1:numel(p.TabularData.Notes)
           out{end+1,1} = [prefix p.TabularData.Notes{i}];
        end
    end

    % Separation line
    out{end+1,1} = [prefix repmat('-', 1, lengthSeparationLine)];

end

% Write output to command window -----------------------------------------------

% Output to log file
if ~isempty(logFile)
    fid = fopen(logFile, 'at');
    if ~iscell(out)
        fprintf(fid, '%s\n', out);
    else % only in case of Flag = 'D'
        for i = 1:numel(out)
            fprintf(fid, '%s\n', out{i});
        end
    end
    fclose(fid);
% Output to work space
else
    if any(strcmpi(Flag, {'X'})) % standard error output
        fprintf(2, '%s\n', out);
    else % standard output
        if ~iscell(out)
            fprintf(1, '%s\n', out);
        else % only in case of Flag = 'D'
            for i = 1:numel(out)
                fprintf(1, '%s\n', out{i});
            end
        end
    end
end

% wk 2015-04-25 Wolfgang Rieger criticized that when redirecting the output of opalsICP to a file, the output stream seems to be buffered, and hence he cannot closely follow the progress of opalsICP when watching the file in a text editor.
% In fact, this seems to be the case for stdout and stderr, see: http://undocumentedmatlab.com/blog/improving-fwrite-performance
% Let's check if stdout and stderr can be flushed explicitly by the following command, see: http://stackoverflow.com/questions/2633019/how-can-i-flush-the-output-of-disp-in-matlab-or-octave
% wk 2015-04-26 this seems to be unnecessary, because the output of ICP4opals is directed to the opals logging system via the handler installed by opalsICP. Thus, flush the screen log stream (std::cout) in opalsICP instead.
% drawnow('update')

end % function end

% ------------------------------------------------------------------------------

function tInfo = timeinfo
tInfo = [datestr(now,'yyyy-mm-dd HH:MM:SS.FFF') 's'];
end


%  INTERNAL FUNCTION
%
%  Examples:
%
%  test=(date2serial(1990):date2serial(1995))
%  serial2date(test)
%
%  test=(date2serial('1990'):date2serial('1995'))
%  serial2date(test)
%
%  test=(date2serial('1990h1'):date2serial('1995h2'))
%  serial2date(test)
%
%  test=(date2serial('1990q1'):date2serial('1995q4'))
%  serial2date(test)
%
%  test=(date2serial('1990m1'):date2serial('1995m6'))
%  serial2date(test)
%


function varargout = plot(varargin)
%PLOT   Basic linear plot for CHEBFUN objects.
%   PLOT(F) plots the CHEBFUN object F in the interval where it is defined. If F
%   is complex valued, PLOT(F) is equivalent to PLOT(real(F), imag(F)).
%
%   PLOT(F, G) plots the CHEBFUN G versus the CHEBFUN F. Quasimatrices and
%   array-valued CHEBUFUN objects are also supported in the natural way.
%
%   PLOT(F, S) allows various line types, plot symbols, and colors to be used
%   when S is a character string made from one element from any or all the
%   following 3 columns:
%
%            b     blue          .     point              -     solid
%            g     green         o     circle             :     dotted
%            r     red           x     x-mark             -.    dashdot
%            c     cyan          +     plus               --    dashed
%            m     magenta       *     star             (none)  no line
%            y     yellow        s     square
%            k     black         d     diamond
%            w     white         v     triangle (down)
%                                ^     triangle (up)
%                                <     triangle (left)
%                                >     triangle (right)
%                                p     pentagram
%                                h     hexagram
%
%   The entries from the centre columns are plotted at the grid being used to
%   represent F (typically Chebyshev).
%
%   The X,Y pairs, or X,Y,S triples, can be followed by parameter/value pairs to
%   specify additional properties of the lines. For example,
%            f = chebfun(@sin);
%            plot(f, 'LineWidth', 2, 'Color', [.6 0 0])
%   will create a plot with a dark red line width of 2 points.
%
%   PLOT(F1, S1, F2, S2, F3, S3, ...) or PLOT(F1, G1, S1, F2, G2, S2, ...)
%   combines the plots defined by the (F,G,S) triples or (F,S) doubles, where
%   the F's and G's are CHEBFUN object and the S's are strings.
%
%   [HLINE, HPOINT, HJUMP] = PLOT(F) returns column vectors of handles to
%   lineseries objects (one for each column in the case of array-valued CHEBFUN
%   objects), corresponding to the line, point, and jump plots, respectively.
%
%   PLOT(F, 'interval', [A, B]) restricts the plot to the interval [A, B], which
%   can be useful when the domain of F is infinite, or for 'zooming in' on, say,
%   oscillatory CHEBFUN objects. If plotting an array-valued CHEBFUN or more
%   than one CHEBFUN in a call like PLOT(F, 'b', G, '--r', 'interval', [A, B])
%   this property is applied globally. Markers, such as 'o', or '.', are ignored
%   if the interval flag is used.
%
%   Besides the usual parameters that control the specifications of lines (see
%   linespec), the parameter JumpLine and DeltaLine determines the linestyle for
%   the discontinuities and the delta functions of the CHEBFUN F, respectively.
%   For example, PLOT(F, 'JumpLine', '-r') will plot discontinuities as solid
%   red lines and PLOT(F, 'deltaline', '-r') will plot the delta functions as
%   solid red lines. By default the plotting style for JumpLine is ':', and '-'
%   for delta functions and colours are chosen to match the lines they
%   correspond to. It is possible to modify other properties of JumpLines syntax
%   like PLOT(F, 'JumpLine', {'color', 'r', 'LineWidth', 5}). JumpLines and
%   deltaLines can be suppressed with the argument 'none'.
%
%   Note that the PLOT(F, 'numpts', N) option for V4 is deprecated, and this
%   call now has no effect.
%
% See also PLOTDATA, PLOT3.

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

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DEVELOPER NOTE:
%  We actually plot a fifth 'dummy' plot which contains both the line and marker
%  styles. This is the only plot which has 'handlevis', 'on', and so will be
%  included in subsequent calls to LEGEND(). The handle to this plot is included
%  as the fifth output, and the plot itself is set to 'visible', 'off'. Note
%  that if a user modifies the plot by adjusting HLINE or HPOINT, subsequent
%  calls the LEGEND will not have the updated style. There's no way to get
%  around this without a complicated callback procedure.
%
%  Note, to clarify, the reason we need all this is that we must plot the line
%  and points as different plots. MATLAB/PLOT() doesn't have this problem.
%
%  Also note that the handles are now output as individually, rather than
%  forced in to an array.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% TODO: Document plotting of DELTFAFUN objects. (In particular, handle output)

%% Deal with an empty input:
if ( isempty(varargin{1}) )
    if ( nargout == 1 )
        varargout{1} = plot([]);
    end
    return
end

%% Initialization:

% Suppress inevitable warning for growing these arrays:
%#ok<*AGROW>

% Store the hold state of the current axis:
holdState = ishold;

% Store the current X and Y-limits, and whether ylim is in manual or auto mode.
if ( holdState )
    xLimCurrent = get(gca, 'xlim');
    yLimCurrent = get(gca, 'ylim');
    yLimModeCurrent = get(gca, 'ylimmode');
end

% Initialize flags:
isComplex = false;
intervalIsSet = false;

% Initialize XLIM and YLIM. Note that the first entries are initialized to be
% UPPER limits on the LOWER parts of the axes, while the second entries
% correspond to LOWER bounds on the UPPER parts of the axes. Hence, this
% somewhat strange convention.
xLim = [inf, -inf];
yLim = [inf, -inf];
defaultXLim = 1;
defaultYLim = 1;

% Check to see if the 'interval' flag has been set:
interval = [];
loc = find(strcmpi(varargin, 'interval'));
if ( any(loc) )
    interval = varargin{loc+1};
    varargin(loc:loc+1) = [];
    intervalIsSet = true;
else
    % TODO: Do we want to support this?
    % Allow plot(f, [a, b]) as shorthand for plot(f, 'interval', [a, b]):
    loc = find(cellfun(@(f) isa(f, 'chebfun'), varargin));
    for k = 1:numel(loc)
        if ( loc(k) < nargin && isnumeric(varargin{loc(k)+1}) )
            interval = varargin{loc(k)+1};
            varargin(loc(k)+1) = [];
            intervalIsSet = true;
            break
        end
    end
end

% Support 'interval' by evaluating on a fixed grid size (2000 points). See #602.
if ( intervalIsSet )
    for k = 1:numel(varargin)
        if ( isa(varargin{k}, 'chebfun') )
            dom = union(domain(varargin{k}), interval);
            dom(dom < interval(1) | dom > interval(end)) = [];
            varargin{k} = chebfun(@(x) feval(varargin{k}, x), dom, 2000);
        end
    end
end

% Initialise storage:
lineData = {};
pointData = {};
jumpData = {};
deltaData = {};
jumpLineIsSet = any(cellfun(@(v) ischar(v) && strcmpi(v, 'JumpLine'), varargin));

% Remove global plotting options from input arguments.
[lineStyle, pointStyle, jumpStyle, deltaStyle, varargin] = ...
    chebfun.parsePlotStyle(varargin{:});

%% Preparation of the data:

% Get the data for plotting from PLOTDATA():
while ( ~isempty(varargin) )

    % Acquire plotting data for each CHEBFUN / pair of CHEBFUNs:
    if ( (numel(varargin) > 1) && ... % PLOT(f, g).
            (isa(varargin{2}, 'chebfun') || isnumeric(varargin{2})) )
        % Remove CHEBFUN objects from array input:
        f = varargin{1};
        g = varargin{2};
        varargin(1:2) = [];

        % We can only plot real against real:
        isComplex = false;
        if ( ~isreal(f) || ~isreal(g) )
            warning('CHEBFUN:CHEBFUN:plot:complex', ...
                'Imaginary parts of complex X and/or Y arguments ignored.');
            f = real(f);
            g = real(g);
        end

        % Call PLOTDATA():
        if ( isnumeric(f) )
            % For plotting numeric data in a CHEBFUN/PLOT() call.
            newData = plotData(chebfun());
            newData.xLine = f;
            newData.yLine = g;
            newData.xPoints = f;
            newData.yPoints = g;
            newData.xJumps = NaN;
            newData.yJumps = NaN;
            newData.xDeltas = NaN;
            % Do nothing
        elseif ( numel(f) == 1 && numel(g) == 1 )
            % Array-valued CHEBFUN case:
            newData = plotData(f, g);
        else
            % QUASIMATRIX case:
            f = num2cell(f);
            g = num2cell(g);
            if ( numel(f) > 1 && numel(g) > 1 )
                if ( numel(f) ~= numel(g) )
                    error('CHEBFUN:CHEBFUN:plot:dim', ...
                    'CHEBFUN objects must have the same number of columns.');
                end
                for k = 1:numel(f)
                    newData(k) = plotData(f{k}, g{k});
                end
            elseif ( numel(f) > 1 && numel(g) == 1 )
                for k = 1:numel(f)
                    newData(k) = plotData(f{k}, g{1});
                end
            elseif ( numel(f) == 1 && numel(g) > 1 )
                for k = 1:numel(f)
                    newData(k) = plotData(f{1}, g{k});
                end
            end
        end

    else  % PLOT(f).

        % Remove CHEBFUN from array input:
        f = varargin{1};
        varargin(1) = [];
        isComplex = ~isreal(f);

        % Loop over the columns:
        for k = 1:numel(f)
            if ( isComplex )
                newData(k) = plotData(real(f(k)), imag(f(k)));
            else
                newData(k) = plotData(f(k));
            end
        end

    end

    % Style data.
    pos = 0;
    styleData = [];

    lv = length(varargin);
    % Find the location of the next CHEBFUN in the input array:
    while ( (pos < lv) && ~isa(varargin{pos+1}, 'chebfun') )
        if ( pos+1 < lv && isnumeric(varargin{pos+1}) && ...
                isnumeric(varargin{pos+2}) )
            break
        end
        pos = pos + 1;
    end

    if ( pos > 0 )
        styleData = varargin(1:pos);
        varargin(1:pos) = [];
        % Remove deprecated 'numpts' option:
        idx = find(strcmp(styleData, 'numpts'), 1);
        if ( any(idx) )
            styleData(idx:(idx+1)) = [];
        end
    end

    % Loop over the columns:
    for k = 1:numel(newData)

        % Update axis limits:
        xLim = [min(newData(k).xLim(1), xLim(1)), ...
            max(newData(k).xLim(2), xLim(2))];
        yLim = [min(newData(k).yLim(1), yLim(1)), ...
            max(newData(k).yLim(2), yLim(2))];

        % Append new data:
        lineData = [lineData, newData(k).xLine, newData(k).yLine, styleData];
        pointData = [pointData, newData(k).xPoints, newData(k).yPoints, ...
            styleData];
        jumpData = [jumpData, newData(k).xJumps, newData(k).yJumps, styleData];
        deltaData{k} = {newData(k).xDeltas, newData(k).yDeltas, ...
            newData(k).yDeltaBase, styleData};

        defaultXLim = defaultXLim & newData(k).defaultXLim;
        defaultYLim = defaultYLim & newData(k).defaultYLim;
    end

    % If xLim(1) == xLim(2), let Matlab figure out a proper xLim:
    if ( ~diff(xLim) )
        defaultXLim = 1;
    end

    % If yLim(1) == yLim(2), let Matlab figure out a proper yLim:
    if ( ~diff(yLim) )
        defaultYLim = 1;
    end

end

%% Plotting starts here:

% Acquire initial color cycle if running R2014b+.
if ( ~verLessThan('matlab', '8.4') )
    if ( ~holdState )
        set(gca, 'ColorOrderIndex', 1);
    end
    originalColorOrder = get(gca, 'ColorOrderIndex');
end

% Plot the lines:
h1 = plot(lineData{:});
set(h1, 'Marker', 'none', lineStyle{:})

% Ensure the plot is held:
hold on

% Get color cycle prior to point plot if running R2014b.
if ( ~verLessThan('matlab', '8.4') )
    newColorOrder = get(gca, 'ColorOrderIndex');
    set(gca, 'ColorOrderIndex', originalColorOrder)
end

% Plot the points:
h2 = plot(pointData{:});
% Change the style accordingly:
set(h2, 'LineStyle', 'none', pointStyle{:})
if ( intervalIsSet )
    % Markers are meaningless if the 'interval' flag is used.
    set(h2, 'Marker', 'none', pointStyle{:})
end

% Reset color cycle prior to jump plot if running R2014b.
if ( ~verLessThan('matlab', '8.4') )
    set(gca, 'ColorOrderIndex', originalColorOrder);
end

% Plot the jumps:
if ( isempty(jumpData) || ischar(jumpData{1}) )
    jumpData = {[]};
end
h3 = plot(jumpData{:});
% Change the style accordingly:
if ( ~isempty(jumpStyle) )
    set(h3, jumpStyle{:});
end
if ( ~jumpLineIsSet )
    if ( isComplex )
        set(h3, 'LineStyle', 'none')
    else
        set(h3, 'LineStyle', ':')
    end
    set(h3, 'Marker', 'none')
end

% Plot the Delta functions:
if ( isempty(deltaData) || ~isnumeric(deltaData{1}{1}) )
    h4 = plot([]);
else
    h4 = plotDeltas(deltaData);
end
if ( ~isempty(deltaStyle) )
    set(h4, deltaStyle{:});
end

% Reset colors prior to legend data plot if running R2014b.
if ( ~verLessThan('matlab', '8.4') )
    set(gca, 'ColorOrderIndex', originalColorOrder);
end

% Generate data for the dummy plot for the legend.  dummyData is the same as
% lineData but with the numeric entries replaced by NaNs of suitable dimension
% so that they don't show up on the plot but are still "active" for the legend.
dummyData = lineData;
for i = 1:1:length(dummyData)
    if ( isnumeric(lineData{i}) )
        dummyData{i} = NaN(1, size(dummyData{i}, 2));
    end
end

% Plot the dummy data, which includes both line and point style:
hDummy = plot(dummyData{:});
if ( ~isempty(lineStyle) || ~isempty(pointStyle) )
    set(hDummy, lineStyle{:}, pointStyle{:});
end

% Reset colors prior to legend data plot if running R2014b.
if ( ~verLessThan('matlab', '8.4') )
    set(gca, 'ColorOrderIndex', newColorOrder);
end

%% Setting xLim and yLim:

% If holding, then make sure not to shrink the X-limits.
if ( holdState )
    xLim = [min(xLimCurrent(1), xLim(1)), max(xLimCurrent(2), xLim(2))];
    yLim = [min(yLimCurrent(1), yLim(1)), max(yLimCurrent(2), yLim(2))];
end

% We always want to set the x-limits. Otherwise, plots like
%   plot(chebfun(@(x) sin(x), [0 pi])
% will have extra white space around the ends of the domain, and look ugly.

if ( diff(xLim) )
    set(gca, 'xLim', xLim)
end

% Set the Y-limits if appropriate values have been suggested, or if we were
% holding on when we entered this method:
if ( ~defaultYLim || (holdState && strcmp(yLimModeCurrent, 'manual')) ) && ...
        ( diff(yLim) )
    set(gca, 'yLim', yLim)
end

%% Misc:

% Return hold state to what it was before:
if ( ~holdState )
    hold off
end

% We don't want these guys to be included in LEGEND(), so we turn them off.
set(h1, 'handlevis', 'off');
set(h2, 'handlevis', 'off');
set(h3, 'handlevis', 'off');
set(h4, 'handlevis', 'off');

% Ensure that the both the handle for the dummy plot and the dummy plot itself
% are visible for LEGEND().  The dummy plot could in theory have its 'Visible'
% property set to 'off', but the data is NaN, so it doesn't draw anything
% anyway.  Moreover, if 'Visible' is 'off', the entries in the legend will be
% grayed out in R2016b and later.
set(hDummy, 'handlevis', 'on', 'visible', 'on');     %  ¯\_(o.O)_/¯

% Give an output to the plot handles if requested:
if ( nargout > 0 )
    varargout = {h1 ; h2 ; h3 ; h4 ; hDummy};
end

end

function h = plotDeltas(deltaData)
%PLOTDELTAS   Plots delta functions.
    h = [];

    % Get and save the current ColorOrder if running on R2014a or earlier.
    if ( verLessThan('matlab', '8.4') )
        originalColorOrder = get(gca, 'ColorOrder');
        colorOrder = circshift(originalColorOrder, 1);
    end

    for k = 1:1:numel(deltaData)
        % Set color for the next delta function plot.
        if ( verLessThan('matlab', '8.4') )
            % Manually manipulate the ColorOrder for R2014a or earlier.
            colorOrder = circshift(colorOrder, -1);
            set(gca, 'ColorOrder', colorOrder);
        else
            % Use ColorOrderIndex for R2014b and later.
            set(gca, 'ColorOrderIndex', k);
        end

        h = [h, plotDeltasForOneFunction(deltaData{k}{:})];
    end

    % Restore the ColorOrder if running on R2014a or earlier.
    if ( verLessThan('matlab', '8.4') )
        set(gca, 'ColorOrder', originalColorOrder);
    end
end

function h = plotDeltasForOneFunction(varargin)
%PLOTDELTASFORONEFUNCTION   Plots delta functions for one function.

h = [];
j = 1;
while ( ~isempty(varargin) )
    % Extract data which is in triplets:
    xData = varargin{1};  % locations of delta functions
    yData = varargin{2};  % magnitude of delta functions
    yBase = varargin{3};  % starting height for delta functions

    % Delete these arguments, since they have been copied:
    varargin(1:3) = [];

    % Handle the delta style argument:
    style = '';
    if ( ~isempty(varargin{1}) && iscell(varargin{1}) )
        style = varargin{1}{1};
    end
    varargin(1) = [];

    % Ignore complete NaN data:
    if ( all(isnan(xData)) )
        continue
    end

    if ( isnumeric(xData) )
        % Remove mixed NaN data:
        nanIdx = isnan(xData);
        xData(nanIdx) = [];
        yData(nanIdx) = [];
        yBase(nanIdx) = [];

        % merge duplicate delta functions.
        [yData, xData, dupIdx] = deltafun.mergeColumns(yData.', xData.');
        xData = xData.';
        yData = yData.';

        % For delta functions at discontinuities, set the base value to the
        % average of the function values:
        yBase(dupIdx-1) = 1/2*(yBase(dupIdx-1)+yBase(dupIdx));
        yBase(dupIdx) = [];
        yFinish = yBase + yData;

        % Add NaNs in order to plot isolated vertical lines:

        % NaNs for xData:
        xFullData = zeros(3*size(xData,1), 1);
        xFullData(1:3:end) = xData;
        xFullData(2:3:end) = xData;
        xFullData(3:3:end) = NaN;

        % NaNs for yData
        yFullData = zeros(3*size(xData,1), 1);
        yFullData(1:3:end) = yBase;
        yFullData(2:3:end) = yFinish;
        yFullData(3:3:end) = NaN;

        fullData{1} = xFullData;
        fullData{2} = yFullData;
        fullData{3} = style;
    end

    % Plot the vertical lines:
    h(j) = plot(fullData{:});

    % Plot the markers for delta functions:
    for jj = 1:length(xData)
        % For positive delta functions, we plot an arrow:
        if ( yData(jj) >= 0 )
            marker = '^';
        end
        % For negative delta functions, we plot a v:
        if ( yData(jj) < 0 )
            marker = 'v';
        end

        % Plot the markers and match the color with the delta lines:
        hjj = plot(xData(jj), yFinish(jj), marker, ...
            'markersize', 6, 'linestyle', 'none', 'handlevis', 'off');
        set(hjj, 'color', get(h(j), 'color'));
        set(hjj, 'markerfacecolor', get(h(j), 'color'))
    end

    j = j + 1;
end

end


function y = cvx_blkdiag( varargin )

% A reimplemenetation of MATLAB's blkdiag function, which is broken in
% certain versions of MATLAB.

if nargin == 1,
    y = varargin{1};
else
    isYsparse = false;
    for k = 1 : nargin,
        x = varargin{k};
        [ p2(k+1), m2(k+1) ] = size(x); %#ok
        if issparse(x), isYsparse = true; end
    end
    p1 = cumsum(p2);
    m1 = cumsum(m2);
    if isYsparse
        y = sparse( varargin{1} );
        for k = 2 : nargin,
            y = [y sparse(p1(k),m2(k+1)); sparse(p2(k+1),m1(k)) varargin{k}]; %#ok
        end
    else
        y = zeros(p1(end),m1(end));
        for k=1:nargin
            y(p1(k)+1:p1(k+1),m1(k)+1:m1(k+1)) = varargin{k};
        end
    end
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 x = p04_root ( i )

%*****************************************************************************80
%
%% P04_ROOT returns a root for problem 4.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 May 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer I, the index of the requested root.
%
%    Output, real X, the value of the root.
%
  if ( i == 1 )
    x = 0.09534461720025875;
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'P04_ROOT - Fatal error!\n' );
    fprintf ( 1, '  Illegal root index = %d\n', i );
    error ( 'P04_ROOT - Fatal error!' );
  end

  return
end


function pass = test_empty( pref )
% For empty chebfun2v objects, does each command deal with them
% appropriately?
% Alex Townsend, March 2013.

%%
% Check that the chebfun2v commands work for empty Chebfun2v objects.

pass = 1;
F = chebfun2v;
try
    conj(F);
    cross(F,F);
    F.';
    curl(F);
    divergence(F);
    dot(F,F);
    F(1,1);
    imag(F);
    isempty(F);
    laplacian(F);
    F-F;
    F.*F;
    norm(F);
    F+F;
    F.^2;
    real(F);
    roots(F);
    F*F;
    F';
catch
   pass = 0;
end

end


% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function q = gait(cycle, k, offset, flip)
    k = mod(k+offset-1, numrows(cycle)) + 1;
    q = cycle(k,:);
    if flip
        q(1) = -q(1);   % for left-side legs
    end
end


function product=prod(X)
%PROD (overloaded)

product = 1;
for i = 1:length(X)
   pick = cell(1,1);pick{1}={i};
   product = product*subsref(X,struct('type','()','subs',pick));
end


function varargout = deal(X, simplifyFlag)
%DEAL   Deal for chebmatrices.
%   [A,B,C,...] = DEAL(X) assigns to the variables A,B,C... the entries in the
%   chebmatrix X by row-major ordering so that A=X(1,1), B=X(1,2), C=X(1,3),
%   etc. If the number of outputs is less than the number of entries in X,
%   only those entries are assigned. By default, outputs are simplified (i.e.
%   they are passed through chebfun.simplify) before they are returned.
%
%   [A,B,C,...] = DEAL(X, SIMPLIFYFLAG), with SIMPLIFYFLAG = FALSE skips the
%   default simplification step.
%
%   DEAL is especially useful for the solution of differential equations,
%   wherein one may write, for example,
%
%       N = chebop(@(x,u,v) [diff(u) + v; diff(v) - u], [0,1]);
%       N.bc = @(x,u,v) [u(0) - 1; v(0)];
%       [u,v] = deal(N \ 0);  % solution components of a system
%                             % of differential equations
%
%   However, users do not normally need this syntax as it is
%   simpler to write  [u,v] = N \ 0 ; .

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

if ( nargin < 2 )
    % By default, call simplify:
    simplifyFlag = true;
end

if ( nargout > prod(size(X)) )
    error('CHEBFUN:CHEBMATRIX:deal:tooManyOutputs', ...
        ['Number of outputs should be less than or equal ' ...
         'to the number of elements in input chebmatrix.'])
end

X = X.';
blocks = X.blocks(:);

if ( simplifyFlag )
    for blockCounter = 1:length(blocks)
        if ( isa(blocks{blockCounter}, 'chebfun') )
            blocks{blockCounter} = simplify(blocks{blockCounter});
        end
    end
end

varargout = blocks(1:nargout);


function [ a, b ] = p30_lim ( )

%*****************************************************************************80
%
%% P30_LIM returns the integration limits for problem 30.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 November 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real A, B, the lower and upper limits of integration.
%
  a = 2.0;
  b = 7.0;

  return
end


function unicycle_test07 ( )

%*****************************************************************************80
%
%% UNICYCLE_TEST07 tests UNICYCLE_UNRANK.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    13 June 2012
%
%  Author:
%
%    John Burkardt
%
  n = 5;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'UNICYCLE_TEST07\n' );
  fprintf ( 1, '  UNICYCLE_UNRANK, given a rank, computes the\n' );
  fprintf ( 1, '  corresponding unicycle.\n' );
  fprintf ( 1, '\n' );
  rank = 6;
  fprintf ( 1, '  The requested rank is %d\n', rank );

  u = unicycle_unrank ( n, rank );

  unicycle_print ( n, u, '  The unicycle:' );

  return
end


function vec = readBinaryDoubles(fileName, format)

% READBINARYDOUBLES Read information from a binary file in as doubles.
% FORMAT
% DESC reads in information from a binary file as a vector of doubles.
% ARG fileName : the name of the file.
% ARG format : the file format for 'fopen', defaults to 'ieee-le'.
% RETURN vec : vector of values in the file.
%
% COPYRIGHT : Neil D. Lawrence, 2009
%
% SEEALSO : fopen, fread, fclose

% NDLUTIL

  if nargin < 2
    format = 'ieee-le';
  end
  fid = fopen(fileName, 'r', format);
  vec = fread(fid, inf, 'double')';
  fclose(fid);
end


function Out = unPivot(In,dim,rmPad)

% UNPIVOT Ungroup a pivot table into a flat dataset (n m by 3 matrix).
%
%   UNPIVOT(IN) Else by default
%       - In: cell or numeric pivot table (2-D).
%               -- In(1) must be NaN
%               -- Nested cells are not allowed
%
%   UNPIVOT(IN, DIM) How to sort output
%       - Dim: scalar, 1 or 2. Respectively sort output by column header or by row header.
%
%   UNPIVOT(IN, DIM, RMPAD) Remove padded values
%       - rmPad: specify which values are considered as padded.
%                NaN, scalars or char 1 by m.
%
%   OUT = ...
%       - Numeric or cell m by 3 matrix. First two columns, header values.
%         Sorted by the first column (ex-colHead) if DIM == 1 or by the
%         second column (ex-rowHead) if DIM == 2.
%
% Additional features:
% - FEX Pivot/unPivot page
%
% See also PIVOT

% Author: Oleg Komarov (oleg.komarov@hotmail.it)
% 16 dec 2009 - Created
% 20 dec 2009 - Compatibility from 7.1; added link to the submission
% 22 jan 2010 - Fixed column position in Out (the first was switched with the second)

% ------------------------------------------------------------------------
% CHECK
% ------------------------------------------------------------------------

% #Ninput
error(nargchk(1,3,nargin));

% In
if isscalar(In) || isvector(In)
    error('unPivot:inFmt','IN is not a pivot table')
elseif iscell(In)
    if ~isnan(In{1}); error('unPivot:inFmt','IN first element must be NaN'); end
    cellIn = true;
    if any(any(cellfun('isclass', In, 'cell')))
        error('unPivot:inFmt','IN nested cells not admitted')
    end
elseif isnumeric(In); cellIn = false;
    if ~isnan(In(1)); error('unPivot:inFmt','IN first element must be NaN'); end
else error('unPivot:inFmt','IN invalid format')
end

% Dim
if nargin == 1 || isempty(dim); dim = 1;
elseif isnumeric(dim)
    if ~(dim == 1 || dim == 2)
        error('unPivot:dimFmt','DIM must be 1 or 2')
    end
else error('unPivot:dimFmt','DIM invalid format')
end

% rmPad
if nargin < 3 || isempty(rmPad)
    rmPad = NaN;
elseif ~((isnumeric(rmPad) && isscalar(rmPad)) || (ischar(rmPad) && size(rmPad,1) == 1))
    error('unPivot:dimFmt','RMPAD invalid format')
end

% ------------------------------------------------------------------------
% ENGINE
% ------------------------------------------------------------------------

% Extract main parts
rowHead = In(1,2:end); colHead = In(2:end,1); values = In(2:end,2:end); clear In
sz = size(values);

% Index values to unpivot
IDX = 1:numel(values);

% Flip if sorting by rowHeader
if dim == 2
    IDX = reshape(IDX,sz)';
    values = values';
end

% Row and column indexes
[row, col] = ind2sub(sz,IDX(:));

% Output
Out = [reshape(rowHead(col),[],1), reshape(colHead(row),[],1),values(:)];
clear rowHead colHead values

% Unpad
if cellIn
    Out(cellfun('isempty', Out(:,end)),:) = [];
    IDXc = find(cellfun('isclass', Out(:,end),'char'));
    if ~isempty(IDXc)
        Chars = Out(IDXc,end); Out(IDXc,end) = {NaN};
    else Chars = [];
    end
    IDXp = false;
    if ischar(rmPad)
        IDXc(strcmp(rmPad,Chars)) = [];
        Chars = Chars(IDXc);
    elseif ~isnan(rmPad)
        IDXp = cellfun(@(x) rmPad == x, Out(:,end));
    end
        IDXnan = cellfun(@isnan, Out(:,end));
        IDXnan(IDXc) = false;
        if ~isempty(IDXc); Out(IDXc,end) = Chars;end
        Out(IDXnan | IDXp,:) = [];
    else
    if ~ischar(rmPad)
        if ~isnan(rmPad); Out(Out(:,end) == rmPad,:) = []; end
        Out(isnan(Out(:,end)),:) = [];
    end
end
end


function line = sphere_llq_grid_lines ( nlat, nlong, line_num )

%*****************************************************************************80
%
%% SPHERE_LLQ_GRID_LINES returns lines for an LLQ grid on a sphere.
%
%  Discussion:
%
%    A SPHERE LLQ grid imposes a grid of quadrilaterals on a sphere,
%    using latitude and longitude lines.
%
%    The point numbering system is the same used in SPHERE_LLQ_GRID_POINTS,
%    and that routine may be used to compute the coordinates of the points.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 April 2015
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NLAT, NLONG, the number of latitude and longitude
%    lines to draw.  The latitudes do not include the North and South
%    poles, which will be included automatically, so NLAT = 5, for instance,
%    will result in points along 7 lines of latitude.
%
%    Input, integer LINE_NUM, the number of grid lines.
%
%    Output, integer LINE(LINE_NUM,2), contains pairs of point indices for
%    line segments that make up the grid.
%
  l = 0;
  line = zeros ( line_num, 2 );
%
%  "Vertical" lines.
%
  for j = 0 : nlong - 1

    old = 1;
    new = j + 2;
    l = l + 1;
    line(l,1:2) = [ old, new ];

    for i = 1 : nlat - 1

      old = new;
      new = old + nlong;
      l = l + 1;
      line(l,1:2) = [ old, new ];

    end

    old = new;
    l = l + 1;
    line(l,1:2) = [ old, 1 + nlat * nlong + 1 ];

  end
%
%  "Horizontal" lines.
%
  for i = 1 : nlat

    new = 1 + ( i - 1 ) * nlong + 1;

    for j = 0 : nlong - 2
      old = new;
      new = old + 1;
      l = l + 1;
      line(l,1:2) = [ old, new ];
    end

    old = new;
    new = 1 + ( i - 1 ) * nlong + 1;
    l = l + 1;
    line(l,1:2) = [ old, new ];

  end

  return
end


function r8mat_transpose_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )

%*****************************************************************************80
%
%% R8MAT_TRANSPOSE_PRINT_SOME prints some of an R8MAT, transposed.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 May 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns.
%
%    Input, real A(M,N), an M by N matrix to be printed.
%
%    Input, integer ILO, JLO, the first row and column to print.
%
%    Input, integer IHI, JHI, the last row and column to print.
%
%    Input, string TITLE, an optional title.
%
  incx = 5;

  if ( 0 < s_len_trim ( title ) )
    fprintf ( 1, '\n' );
    fprintf ( 1, '%s\n', title );
  end

  for i2lo = max ( ilo, 1 ) : incx : min ( ihi, m )

    i2hi = i2lo + incx - 1;
    i2hi = min ( i2hi, m );
    i2hi = min ( i2hi, ihi );

    inc = i2hi + 1 - i2lo;

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Row: ' );
    for i = i2lo : i2hi
      fprintf ( 1, '%7d       ', i );
    end
    fprintf ( 1, '\n' );
    fprintf ( 1, '  Col\n' );

    j2lo = max ( jlo, 1 );
    j2hi = min ( jhi, n );

    for j = j2lo : j2hi

      fprintf ( 1, '%5d ', j );
      for i2 = 1 : inc
        i = i2lo - 1 + i2;
        fprintf ( 1, '%12f', a(i,j) );
      end
      fprintf ( 1, '\n' );

    end

  end

  return
end


function hb_header_print ( title, key, totcrd, ptrcrd, indcrd, valcrd, ...
  rhscrd, mxtype, nrow, ncol, nnzero, neltvl, ptrfmt, indfmt, valfmt, ...
  rhsfmt, rhstyp, nrhs, nrhsix )

%*****************************************************************************80
%
%% HB_HEADER_PRINT prints the header of an HB file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 November 2003
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Iain Duff, Roger Grimes, John Lewis,
%    User's Guide for the Harwell-Boeing Sparse Matrix Collection,
%    October 1992.
%
%  Parameters:
%
%    Input, character ( len = 72 ) TITLE, a title for the matrix.
%
%    Input, character ( len = 8 ) KEY, an identifier for the matrix.
%
%    Input, integer TOTCRD, the total number of lines of data.
%
%    Input, integer PTRCRD, the number of input lines for pointers.
%
%    Input, integer INDCRD, the number of input lines for row indices.
%
%    Input, integer VALCRD, the number of input lines for numerical values.
%
%    Input, integer RHSCRD, the number of input lines for right hand sides.
%
%    Input, character ( len = 3 ) MXTYPE, the matrix type.
%    First character is R for Real, C for complex, P for pattern only.
%    Second character is S for symmetric, U for unsymmetric, H for
%      Hermitian, Z for skew symmetric, R for rectangular.
%    Third character is A for assembled and E for unassembled
%      finite element matrices.
%
%    Input, integer NROW, the number of rows or variables.
%
%    Input, integer NCOL, the number of columns or elements.
%
%    Input, integer NNZERO.  In the case of assembled sparse matrices,
%    this is the number of nonzeroes.  In the case of unassembled finite
%    element matrices, in which the right hand side vectors are also
%    stored as unassembled finite element vectors, this is the total
%    number of entries in a single unassembled right hand side vector.
%
%    Input, integer NELTVL, the number of finite element matrix entries,
%    set to 0 in the case of assembled matrices.
%
%    Input, character ( len = 16 ) PTRFMT, the format for reading pointers.
%
%    Input, character ( len = 16 ) INDFMT, the format for reading indices.
%
%    Input, character ( len = 20 ) VALFMT, the format for reading values.
%
%    Input, character ( len = 20 ) RHSFMT, the format for reading values
%    of the right hand side.
%
%    Input, character ( len = 3 ) RHSTYP, the right hand side type.
%    First character is F for full storage or M for same as matrix.
%    Second character is G if starting "guess" vectors are supplied.
%    Third character is X if exact solution vectors are supplied.
%
%    Input, integer NRHS, the number of right hand sides.
%
%    Input, integer NRHSIX, the number of entries of storage for right
%    hand side values, in the case where RHSTYP(1:1) = 'M' and
%    MXTYPE(3:3) = 'A'.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '%s\n', title );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  TOTCRD = %6d\n', totcrd );
  fprintf ( 1, '  PTRCRD = %6d\n', ptrcrd );
  fprintf ( 1, '  INDCRD = %6d\n', indcrd );
  fprintf ( 1, '  VALCRD = %6d\n', valcrd );
  fprintf ( 1, '  RHSCRD = %6d\n', rhscrd );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  KEY =    "%s".\n', key );
  fprintf ( 1, '  MXTYPE = "%s".\n', mxtype );
  fprintf ( 1, '  RHSTYP = "%s".\n', rhstyp );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  NROW   = %6d\n', nrow );
  fprintf ( 1, '  NCOL   = %6d\n', ncol );
  fprintf ( 1, '  NNZERO = %6d\n', nnzero );
  fprintf ( 1, '  NELTVL = %6d\n', neltvl );
  fprintf ( 1, '  NRHS   = %6d\n', nrhs );
  fprintf ( 1, '  NRHSIX = %6d\n', nrhsix );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  PTRFMT =    "%s".\n', ptrfmt );
  fprintf ( 1, '  INDFMT =    "%s".\n', indfmt );
  fprintf ( 1, '  VALFMT =    "%s".\n', valfmt );
  fprintf ( 1, '  RHSFMT =    "%s".\n', rhsfmt );

  return
end


function p27_default ( dim_num )

%*****************************************************************************80
%
%% P27_DEFAULT sets default values for problem 27.
%
%  Discussion:
%
%    If a problem uses vector parameters, then the spatial dimension
%    DIM_NUM is needed as input, so that the vector parameters can be
%    properly dimensioned.
%
%    Every problem keeps a count of the number of function calls.  Calling
%    this routine causes that count to be reset to 0.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer DIM_NUM, the dimension of the problem.
%
  i4 = 0;
  p27_i4 ( 'D', '*', i4 );

  r8 = 0.0;
  p27_r8 ( 'D', '*', r8 );

  r8vec = [];
  p27_r8vec ( 'D', '*', dim_num, r8vec );

  return
end


function i4mat_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )

%*****************************************************************************80
%
%% I4MAT_PRINT_SOME prints out a portion of an I4MAT.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns of the matrix.
%
%    Input, integer A(M,N), an M by N matrix to be printed.
%
%    Input, integer ILO, JLO, the first row and column to print.
%
%    Input, integer IHI, JHI, the last row and column to print.
%
%    Input, string TITLE, a title.
%
  incx = 10;

  fprintf ( 1, '\n' );
  fprintf ( 1, '%s\n', title );

  if ( m <= 0 || n <= 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, '  (None)\n' );
    return
  end

  for j2lo = max ( jlo, 1 ): incx : min ( jhi, n )

    j2hi = j2lo + incx - 1;
    j2hi = min ( j2hi, n );
    j2hi = min ( j2hi, jhi );

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Col: ' );

    for j = j2lo : j2hi
      fprintf ( 1, '%7d  ', j );
    end

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Row\n' );
    fprintf ( 1, '\n' );

    i2lo = max ( ilo, 1 );
    i2hi = min ( ihi, m );

    for i = i2lo : i2hi

      fprintf ( 1, '%5d: ', i );
      for j = j2lo : j2hi
        fprintf ( 1, '%7d  ', a(i,j) );
      end

      fprintf ( 1, '\n' );

    end

  end

  return
end


function neqn = p11_neqn ( )

%*****************************************************************************80
%
%% P11_NEQN returns the number of equations for problem P11.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer NEQN, the number of equations.
%
  neqn = 10;

  return
end


 function ir_display_struct(ob, varargin)
%function ir_display_struct(ob, varargin)
%|
%| display a structure concisely
%|
%| option
%|	'pre'		prefix
%|
%| Jeff Fessler, University of Michigan

if nargin < 1, ir_usage, end
if streq(ob, 'test'), ir_display_struct_test, return, end

arg.pre = ' ';
arg = vararg_pair(arg, varargin);

%pn = jf_protected_names;
% display(struct(pn))
% tmp = pn.struct_recurse(ob);

if ~isstruct(ob)
	fail('%s not a struct', class(ob))
end

printf([inputname(1) ':'])
%printf('pre = "%s"', arg.pre)
ir_display_struct_do(ob, arg.pre)

% ir_display_struct_do()
function ir_display_struct_do(ob, pre)

fnames = fieldnames(ob);

nmax = 1; % find max length field name
for ii=1:length(fnames)
	nmax = max(nmax, length(fnames{ii}));
end
%nmax = min(nmax, 40);

format = sprintf('%d', nmax);
format = [pre '%' format 's: %s'];

for ii=1:length(fnames)
	fname = fnames{ii};
	tmp = ob.(fname);

	if isempty(tmp)
		str = sprintf('[] (%s)', class(tmp));
	else
		switch class(tmp)
		case 'function_handle'
			str = func2str(tmp);
			if (str(1) ~= '@')
				str = ['@' str];
			end
		case 'char'
			str = ['"' tmp '"'];
		case 'struct'
			str = '(struct)';
		case 'cell'
			str = ['{' num2str(size(tmp)) '}'];
		case {'double', 'single', 'logical'}
			if numel(tmp) == 1
				str = num2str(tmp);
			else
				str = ['[' num2str(size(tmp)) ']'];
				if numel(tmp) < 5
					str = [str ' : ' num2str(tmp(:)')];
				end
			end
			str = [str sprintf(' (%s)', class(tmp))];
		otherwise
			str = sprintf('? (%s)', class(tmp));
		end
	end

	printf(format, fname, str)
	if isstruct(tmp)
		white = sprintf('%d', nmax+2); % 1 more because of ':'
		white = [pre '%' white 's'];
		white = sprintf(white, ' ');
		ir_display_struct_do(tmp, white);
	end
end

function ir_display_struct_test
s.a = 'a';
s.b = 2;
s.c = {1,2,3};
s.d = ones(3);
s.e = 1+2i;
s.f1 = @(x) x+1;
s.f2 = @ir_display_struct;
s.g = complex(1);
t.s = 'sub';
u.v = 'subsub';
t.u = u;
s.t = t;
ir_display_struct(s)


function [ fx, fy ] = f11_f1 ( n, x, y )

%*****************************************************************************80
%
%% F11_F1 returns first derivatives of function f11.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 August 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of evaluation points.
%
%    Input, real X(N,1), Y(N,1), the evalution points.
%
%    Output, real FX(N,1), FY(N,1), the derivative values.
%
  fx(1:n,1) = y(1:n,1) + 1.0;
  fy(1:n,1) = x(1:n,1);

  return
end


function matRad_progress(currentIndex, totalNumberOfEvaluations)
% matRad progress bar
%
% call
%   matRad_progress(currentIndex, totalNumberOfEvaluations)
%
% input
%   currentIndex:               current iteration index
%   totalNumberOfEvaluations:   maximum iteration index
%
% output
%   graphical display of progess. make sure there is no other output
%   written during the loop to prevent confusion
%
% References
%   -
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright 2015 the matRad development team.
%
% This file is part of the matRad project. It is subject to the license
% terms in the LICENSE file found in the top-level directory of this
% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part
% of the matRad project, including this file, may be copied, modified,
% propagated, or distributed except according to the terms contained in the
% LICENSE file.
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% If it's not the first step, erase the stuff printed before
if (currentIndex == 1 || nargin > 2)
    fprintf('Progress: ');
end

if (currentIndex > 1 && nargin < 3)
  Length = numel(sprintf('%3.2f %%',(currentIndex-1)/totalNumberOfEvaluations*100));
  fprintf(repmat('\b',1,Length));
end

% Print the progress tool
fprintf('%3.2f %%',currentIndex/totalNumberOfEvaluations*100);

% After the last iteration print a newline command
if (currentIndex == totalNumberOfEvaluations)
    fprintf('\n');
end

end


function title = p13_title ( )

%*****************************************************************************80
%
%% P13_TITLE returns a title for problem 13.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 March 2000
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string TITLE, a title for the problem.
%
  title = 'The Trigonometric Function.';

  return
end