function [ know, x ] = p07_sol ( )

%*****************************************************************************80
%
%% P07_SOL returns the solution for problem 7.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 February 2002
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer KNOW.
%    If KNOW is 0, then the solution is not known.
%    If KNOW is positive, then the solution is known, and is returned in X.
%
%    Output, real X, the solution, if known.
%
  know = 1;

  x = -0.6795786599525;

  return
end


%  Script file: test_preallocate.m
%
%  Purpose:
%    This program tests the creation of cell arrays with and
%    without preallocation.
%
%  Record of revisions:
%      Date       Programmer          Description of change
%      ====       ==========          =====================
%    03/04/07    S. J. Chapman        Original code
%
% Define variables:
%   a            -- Cell array
%   maxvals      -- Maximum values in cell array

% Create array without preallocation
clear all
maxvals = 50000;
tic
for ii = 1:maxvals
   a{ii} = ['Element ' int2str(ii)];
end
disp( ['Elapsed time without preallocation = ' num2str(toc)] );

% Create array with preallocation
clear all
maxvals = 50000;
tic
a = cell(1,maxvals);
for ii = 1:maxvals
   a{ii} = ['Element ' int2str(ii)];
end
disp( ['Elapsed time with preallocation    = ' num2str(toc)] );


function value = year_length_months_ethiopian ( y )

%*****************************************************************************80
%
%% YEAR_LENGTH_MONTHS_ETHIOPIAN returns the number of months in an Ethiopian year.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 September 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, the year to be checked.
%
%    Output, integer VALUE, the number of months in the year.
%
  value = 13;

  return
end


function OUT = cell2num(datacell)
% =======================================================================
% Convert a cell array (of numbers) into a double array. If the cell arrqay
% does not include a number returns NaN
% =======================================================================
% OUT = cell2num(datacell)
% -----------------------------------------------------------------------
% INPUTS
%	- datacell: a (m x n) cell array with numbers
% -----------------------------------------------------------------------
% OUTPUT
%	- OUT: a (m x n) matrix with numbers
% =========================================================================
% Ambrogio Cesa Bianchi, March 2015
% ambrogiocesabianchi@gmail.com
%-------------------------------------------------------------------------

if ~iscell(datacell)
    error('Input has to be a cell array')
end

% Initialize
OUT = zeros(size(datacell));

% Convert
for c=1:size(datacell,2)
    for r=1:size(datacell,1)
        if isnumeric(datacell{r,c})
            OUT(r,c)=datacell{r,c};
        else
            OUT(r,c)=NaN;
        end
    end
end


function [B]=ceven(C)
%these function choice element of vector with even indices of column
k=1;
for i=2:2:length(C)
    B(1,k)=C(1,i);
    k=k+1;
end


function table = r8mat_data_read ( input_filename, m, n )

%*****************************************************************************80
%
%% R8MAT_DATA_READ reads data from an R8MAT file.
%
%  Discussion:
%
%    An R8MAT is an array of R8's.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string INPUT_FILENAME, the name of the input file.
%
%    Input, integer M, N, the number of rows and columns of data.
%
%    Output, real TABLE(M,N), the point coordinates.
%

%
%  Build up the format string for reading M real numbers.
%
  string = ' ';

  for i = 0 : m
    string = strcat ( string, ' %f' );
  end

  input_unit = fopen ( input_filename );

  if ( input_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8MAT_DATA_READ - Error!\n' );
    fprintf ( 1, '  Could not open the file.\n' );
    error ( 'R8MAT_DATA_READ - Error!' );
  end

  table = zeros(m,n);

  i = 0;

  while ( i < n )

    line = fgets ( input_unit );

    if ( line == -1 )
      break;
    end

    if ( line(1) == '#' )

    elseif ( s_len_trim ( line ) == 0 )

    else

      [ x, count ] = sscanf ( line, string );

      if ( count == m )
        i = i + 1;
        table(1:m,i) = x(1:m);
      end

    end

  end

  fclose ( input_unit );

  return
end


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

% Copyright 2002-2003 The MathWorks, Inc.

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

% Last Modified by GUIDE v2.5 02-Dec-2005 23:18:34

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

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

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

% Choose default command line output for Lotka_VolterraGUI
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Lotka_VolterraGUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);

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

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
x0=[0.85 3.2];
[t,x]=ode45(@LV,[0 10],x0);
axes(handles.axes1);
plot(t,x(:,1),'r');hold on
plot(t,x(:,2),'g');
axis([0,10,0,5]);
Xlabel('temps');
Ylabel('X et Y');
hold off
axes(handles.axes2);
plot(x(:,1),x(:,2),'b');hold on
axis([0.5,1,2.5,3.5]);
Xlabel('X');
Ylabel('Y');
hold off


function [ a, b ] = p33_lim ( )

%*****************************************************************************80
%
%% P33_LIM returns the integration limits for problem 33.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 November 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real A, B, the limits of integration.
%
  a = 0.0;
  b = 1.0;

  return
end


function c8vec_print_some ( n, x, max_print, title )

%*****************************************************************************80
%
%% C8VEC_PRINT_SOME prints some of a C8VEC.
%
%  Discussion:
%
%    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 September 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of entries of the vector.
%
%    Input, complex X(N), 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, '  %6d:  %s\n', i, num2str ( x(i) ) );
    end

  elseif ( 3 <= max_print )

    for i = 1 : max_print-2
      fprintf ( 1, '  %6d: %s\n', i, num2str ( x(i) ) );
    end
    fprintf ( 1, '  ......  ..............\n' );
    i = n;
    fprintf ( 1, '  %6d: %s\n', i, num2str ( x(i) ) );

  else

    for i = 1 : max_print - 1;
      fprintf ( 1, '  %6d: %s\n', i, num2str ( x(i) ) );
    end
    i = max_print;
    fprintf ( 1, '  %6d: %s  ...more entries...\n', i, num2str ( x(i) ) );

  end

  return
end


function r82row_print_part_test ( )

%*****************************************************************************80
%
%% R82ROW_PRINT_PART_TEST tests R82ROW_PRINT_PART.
%
%  Discussion:
%
%    An R82ROW is a (2,N) array of R8's.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 April 2015
%
%  Author:
%
%    John Burkardt
%
  n = 10;
%
%  Set up the array by rows.
%
  v = [ ...
    11.0,  12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0; ...
    21.0,  22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0 ];

  fprintf ( 1, '\n' );
  fprintf ( 1, 'R82ROW_PRINT_PART_TEST\n' );
  fprintf ( 1, '  R82ROW_PRINT_PART prints part of an R82ROW.\n' );

  max_print = 2;
  r82row_print_part ( n, v, max_print, '  Output with MAX_PRINT = 2' );

  max_print = 5;
  r82row_print_part ( n, v, max_print, '  Output with MAX_PRINT = 5' );

  max_print = 25;
  r82row_print_part ( n, v, max_print, '  Output with MAX_PRINT = 25' );

  return
end


function c8vec_uniform_01_test ( )

%*****************************************************************************80
%
%% C8VEC_UNIFORM_01_TEST tests C8VEC_UNIFORM_01;
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 February 2015
%
%  Author:
%
%    John Burkardt
%
  n = 5;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'C8VEC_UNIFORM_01_TEST\n' );
  fprintf ( 1, '  C8VEC_UNIFORM_01_TEST returns a random C8VEC\n' );

  seed = 123456789;

  [ a, seed ] = c8vec_uniform_01 ( n, seed );

  c8vec_print ( n, a, '  The random C8VEC:' );

  return
end


function value = i4_sign ( i )

%*****************************************************************************80
%
%% I4_SIGN returns the sign of an I4.
%
%  Discussion:
%
%    The value is +1 if the number is positive or zero, and it is -1 otherwise.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 September 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer I, the number whose sign is desired.
%
%    Output, integer VALUE, the sign of I.
%
  if ( i < 0 )
    value = -1;
  else
    value = +1;
  end

  return
end


function y= unique_unsort(x, n)
%UNIQUE - Like MATLAB's unique, but without sorting
%
%Synopsis:
%  Y= union_unsort(X, N)
%
%Description:
%  Returns the first N unique elements of X.
%
%Arguments:
%  X - can be a vector or a cell array of strings
%
%% TODO: should be written more generally for matrices

if nargin<2,
  n= inf;
end

y= x([]);  %% empty matrix or empty cell
ii= 0;
while ii<length(x) & length(y)<n,
  ii= ii + 1;
  if ~ismember(x(ii), y,'legacy'),
    y= [y, x(ii)];
  end
end


% csv2cell() - Imports the contents of a character delimited spreadsheet
%              text file as a 2D cell array, csv_matrix.
%
% Usage:
%  >> csv_matrix=csv2cell(csv_fname,delimiter);
%
% Required Input:
%   csv_fname - The name of the text file to import.  If a path is not
%               included in the name, the current working directory will
%               be used.
%
% Optional Input:
%   delimiter - The character that marks cell boundaries in the text file.
%               {default: ','}
%
% Output:
%   csv_matrix - 2D cell array of strings. csv_matrix{x,y} corresponds to
%                the cell in the xth row and yth column in the spreadsheet.
%
% Note, be sure not to use the delimiting character in the text file as
% anything but a cell boundary marker.
%
% Example:
%  >> demo_dat=round(rand(5,3)*10);
%  >> fid=fopen('demo.csv','w');
%  >> for a=1:5, for b=1:3, fprintf(fid,'%d,',demo_dat(a,b)); end; fprintf(fid,'\n'); end;
%  >> fclose(fid);
%  >> csv_matrix=csv2cell('demo.csv',',');
%
% Author:
%  David Groppe
%  9/3/2011
%  Mehtalab
%  Cushing Neuroscience Institutes
%  New Hyde Park, New York

function csv_matrix=csv2cell(csv_fname,delimiter)

if nargin<1,
    help csv2cell
end

if nargin<2,
    delimiter=',';
else
    if ~ischar(delimiter)
        error('Specified delimiter needs to be a character.');
    elseif length(delimiter)>1
        error('Delimiter needs to be a single character.');
    end
end

[fid, msg]=fopen(csv_fname,'r');
if fid==-1,
   error('Cannot open %s because: %s.\n',csv_fname,msg);
end

csv_matrix=cell(1,1);
row_ct=1;
col_ct=1;
while 1
    tline = fgetl(fid);
    if ~ischar(tline), break, end

    while ~isempty(tline),
        [t, tline]=parse_by_char(tline,delimiter);
        csv_matrix{row_ct,col_ct}=t;
        col_ct=col_ct+1;
    end
    col_ct=1;
    row_ct=row_ct+1;
end
fclose(fid);

function [pre, post]=parse_by_char(str,delimiter)

char_ids=find(str==delimiter);
if isempty(char_ids),
    pre=str;
    post=[];
else
    pre=str(1:char_ids(1)-1);
    post=str(char_ids(1)+1:end);
end


function r4lib_test023 ( )

%*****************************************************************************80
%
%% R4LIB_TEST023 tests R4_SIGN and R4_SIGN3.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 September 2014
%
%  Author:
%
%    John Burkardt
%
  test_num = 5;

  r4_test = [ -1.25, -0.25, 0.0, +0.5, +9.0 ];

  fprintf ( 1, '\n' );
  fprintf ( 1, 'R4LIB_TEST023\n' );
  fprintf ( 1, '  R4_SIGN returns the sign of a number.\n' );
  fprintf ( 1, '  R4_SIGN3 returns the three-way sign of a number.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '    R4  R4_SIGN(R4)  R4_SIGN3(R4)\n' );
  fprintf ( 1, '\n' );

  for test = 1 : test_num
    r4 = r4_test(test);
    s1 = r4_sign ( r4 );
    s2 = r4_sign3 ( r4 );
    fprintf ( 1, '  %8f  %8f  %8f\n', r4, s1, s2 );
  end

  return
end


% CVX: Keywords for declaring variables and objectives
%   dual      - Declares one or more dual variables.
%   epigraph  - Declares an epigraph variable.
%   hypograph - Declares a hypograph variable.
%   maximize  - Specifies a concave (or affine) objective to be maximized.
%   minimize  - Specifies a convex (or affine) objective to be maximized.
%   subject   - Implements the "subject to" keyword.
%   variable  - Declares a single CVX variable with optional matrix structure.
%   variables - Declares one or more CVX variables.

% 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 s = frac_to_s ( f )

%*****************************************************************************80
%
%% FRAC_TO_S writes a positive fraction into a left justified character string.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 June 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real F, the number to be written into the string.
%    F should be between 0.0 and 1.0.
%
%    Output, string S, a representation of F.
%
  if ( f < 0.0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'FRAC_TO_S - Fatal error!\n' );
    fprintf ( 1, '  The input fraction F was negative:\n', f );
    error (  'FRAC_TO_S - Fatal error!' );
  elseif ( 1.0 <= f )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'FRAC_TO_S - Fatal error!\n' );
    fprintf ( 1, '  The input fraction F = %g was 1 or more:\n', f );
    error (  'FRAC_TO_S - Fatal error!' );
  end

  s2 = sprintf ( '%f', f );

  s = s2[2:];

  return
end


function s = weekday_to_name_islamic ( w )

%*****************************************************************************80
%
%% WEEKDAY_TO_NAME_ISLAMIC returns the name of an Islamic weekday.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 April 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer W, the weekday index.
%
%    Output, string S, the weekday name.
%
  weekday_name = [ ...
    'Yom ilHadd   '; ...
    'Yom litneen  '; ...
    'Yom ittalat  '; ...
    'Yom larba    '; ...
    'Yom ilkhamiis'; ...
    'Yom ilguma   '; ...
    'Yom issabt   '];
%
%  Make a local copy of the weekday number.
%
  w2 = w;
%
%  Check the weekday number.
%
  weekday_check_common ( w2 );
%
%  Return the weekday name.
%
  s = weekday_name(w2,:);

  return
end


function value = r8_huge ( )

%*****************************************************************************80
%
%% R8_HUGE returns a "huge" real number.
%
%  Discussion:
%
%    The value returned by this function is NOT required to be the
%    maximum representable R8.  This value varies from machine to machine,
%    from compiler to compiler, and may cause problems when being printed.
%    We simply want a "very large" but non-infinite number.
%
%    MATLAB provides a built-in symbolic constant "inf" that can be used
%    if a huge number is really what you want!
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 January 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real VALUE, a huge number.
%
  value = 1.0E+30;

  return
end


function I = make_odd_by_odd(I)
%MAKE_ODD_BY_ODD strips a row and or a column so that it will be
%an odd number of pixels in each dimension.

if ~isodd(size(I,1))
    I = I(1:end -1,:,:);
end

if ~isodd(size(I,2))
    I = I(:, 1:end -1,:);
end
% Copyright 2002 - 2009 The MathWorks, Inc.


function x = p20_start ( n )

%*****************************************************************************80
%
%% P20_START returns a starting point for optimization for problem 20.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 March 2000
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of variables X.
%
%    Output, real X(N), a starting point for the optimization.
%
  x = zeros ( n, 1 );

  return
end


function f2 = p01_f2 ( x )

%*****************************************************************************80
%
%% P01_F2 evaluates the second derivative for problem 1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 February 2002
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X, the values of the variables.
%
%    Output, real F2, the second derivative.
%
  f2 = 2.0;

  return
end


function blas0_test01 ( )

%******************************************************************************/
%
%% BLAS0_TEST01 tests R4_ABS.
%
%  Licensing:
%
%   This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 June 2008
%
%  Author:
%
%    John Burkardt
%
  r4_hi = 5.0;
  r4_lo = -3.0;
  test_num = 10;
  seed = 123456789;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'BLAS0_TEST01\n' );
  fprintf ( 1, '  R4_ABS returns the absolute value of an R4.\n' );
  fprintf ( 1, '\n' );

  for test = 1 : test_num
    [ r4, seed ] = r4_uniform_ab ( r4_lo, r4_hi, seed );
    r4_absolute = r4_abs ( r4 );
    fprintf ( 1, '  %10.6f  %10.6f\n', r4, r4_absolute );
  end

  return
end


function title = p43_title ( )

%*****************************************************************************80
%
%% P43_TITLE returns a title for problem 43.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 January 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string TITLE, a title for the problem.
%
  title = 'The Himmelblau function.';

  return
end


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

%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @defmethod  @@sym isAlways (@var{eq})
%% @defmethodx @@sym isAlways (@var{eq}, 'Unknown', 'false')
%% @defmethodx @@sym isAlways (@var{eq}, 'Unknown', 'true')
%% @defmethodx @@sym isAlways (@var{eq}, 'Unknown', 'error')
%% Test if expression is mathematically true.
%%
%% Example:
%% @example
%% @group
%% syms x y
%% isAlways(x*(1+y) == x+x*y)
%%   @result{} 1
%% @end group
%% @end example
%% Contrast this with a test for “structural equality“:
%% @example
%% @group
%% logical(x*(1+y) == x+x*y)
%%   @result{} 0
%% @end group
%% @end example
%%
%% The optional keyword argument @qcode{'Unknown'} specifies that happens
%% for expressions that cannot simplify.  By default these return
%% false (that is, cannot verify it is always true).  Pass the
%% strings @qcode{'true'}, @qcode{'false'} or @qcode{'error'} to change the behaviour.  You
%% can also pass logical true/false.
%%
%% If @code{isAlways} is called on expressions without relationals,
%% it will return true for non-zero numbers:
%% @example
%% @group
%% isAlways (sym (10))
%%   @result{} 1
%% @end group
%% @end example
%%
%% It is safe to use @code{isAlways} even when the expression does not
%% require simplifying:
%% @example
%% syms x
%% isAlways (sin(x) - sin(x) == 0)
%%   @result{} 1
%% @end example
%% In practice, @code{isAlways} might get called on a simple
%% boolean variable, so this package implements @code{@@logical/isAlways}
%% (which is essentially a no-op).
%%
%% @seealso{@@sym/logical, @@sym/isequal, @@sym/eq, @@logical/isAlways}
%% @end defmethod

function r = isAlways(p, varargin)

  if (~ ((nargin == 1) || (nargin == 3)))
    print_usage ();
  end

  if (nargin == 3)
    assert(strcmpi(varargin{1}, 'unknown'))
    cant = varargin{2};
    if islogical(cant)
      % SMT doesn't allow nonstring but it seems reasonable
    elseif strcmpi(cant, 'true')
      cant = true;
    elseif strcmpi(cant, 'false')
      cant = false;
    elseif strcmpi(cant, 'error')
      % no-op
    else
      error('isAlways: invalid argument for "unknown" keyword')
    end
  else
    cant = false;
  end

  cmd = {
    'def simplify_tfn(p):'
    '    if p in (S.true, S.false):'
    '        return bool(p)'
    '    r = simplify(p)'
    '    #FIXME; Boolean, simplify more than once?'
    '    if r in (S.true, S.false):'
    '        return bool(r)'
    '    # FIXME: hopefully we get sympy patched for some of this'
    '    #ver = sympy.__version__'
    '    #if ver == "0.7.5" or ver.startswith("0.7.6") or ver.startswith("0.7.7"):'
    '    if True:'
    '        if isinstance(p, Equality):'
    '            r = Eq(sp.simplify(p.lhs - p.rhs), 0)'
    '            r = simplify(r)'
    '            if r in (S.true, S.false):'
    '                 return bool(r)'
    '        if isinstance(p, Unequality):'
    '            r = Eq(sp.simplify(p.lhs - p.rhs), 0)'
    '            r = simplify(r)'
    '            if r in (S.true, S.false):'
    '                 return not bool(r)'
    '        if isinstance(p, (Lt, Gt, Le, Ge)):'
    '            r = p._eval_relation(sp.simplify(p.lhs - p.rhs), sp.S(0))'
    '            r = simplify(r)'
    '            if r in (S.true, S.false):'
    '                 return bool(r)'
    '    # for SMT compat'
    '    if p.is_number:'
    '        r = p.is_zero'  % FIXME: return bool(r)?
    '        if r in (S.true, S.false):'
    '            return not bool(r)'
    '    return None' };
  % could distinguish b/w None and return a string for this last case

  cmd = vertcat(cmd, {
    '(x, unknown) = _ins'
    'if x is not None and x.is_Matrix:'
    '    r = [a for a in x.T]' % note transpose
    'else:'
    '    r = [x,]'
    'r = [simplify_tfn(a) for a in r]'
    'r = [unknown if a is None else a for a in r]'
    'flag = True'
    'if r.count("error") > 0:'
    '    flag = False'
    '    r = "cannot reliably convert sym to bool"'
    'return (flag, r)' });

  [flag, r] = pycall_sympy__ (cmd, p, cant);

  if (~flag)
    assert (ischar (r), 'isAlways: programming error?')
    error(['isAlways: ' r])
  end

  r = cell2mat(r);
  r = reshape(r, size(p));

end

%!test
%! % basics
%! assert(isAlways(true))
%! assert(isAlways(1==1))
%! assert(isAlways(sym(1)==sym(1)))
%! assert(isAlways(sym(1)==1))

%!test
%! % numbers to logic?
%! assert (isAlways(sym(1)))
%! assert (isAlways(sym(-1)))
%! assert (~isAlways(sym(0)))

%!shared x
%! syms x

%!test
%! % in this case it is boolean
%! expr = x - x == 0;
%! assert (logical(expr))
%! assert (isAlways(expr))
%! % and both are logical type
%! assert (islogical(logical(expr)))
%! assert (islogical(isAlways(expr)))

%!test
%! % structurally same and mathematically true
%! % (here expr should be sym, non-boolean)
%! expr = x == x;
%! assert (logical(expr))
%! assert (isAlways(expr))
%! %assert (~islogical(expr))   % FIXME: Issue #56
%! %assert (isa(expr, 'sym))

%!test
%! % structurally same and mathematically true
%! % (here expr should be sym, non-boolean)
%! expr = 1 + x == x + 1;
%! assert (logical(expr))
%! assert (isAlways(expr))

%!test
%! % non-zero numbers are true
%! assert (isAlways(sym(1)))
%! assert (isAlways(sym(-10)))
%! assert (~isAlways(sym(0)))

% FIXME: should we support implicit == 0 like sympy?  SMT does oppositve, plus it ignores assumptions?  SMT behaviour is probably meant to mimic matlab doubles,
%expr = x - x;
%c=c+1; r(c) = logical(expr);
%c=c+1; r(c) = isAlways(expr);

%!shared x, y
%! syms x y

%!test
%! % structurally same and mathematically true
%! % (here expr should be sym, non-boolean)
%! expr = x*(1+y) == x*(y+1);
%! assert (logical(expr))
%! assert (isAlways(expr))
%! assert (islogical(isAlways(expr)))

%!test
%! % Now for some differences
%! % simplest example from SymPy FAQ
%! expr = x*(1+y) == x+x*y;
%! assert (~logical(expr))
%! assert (isAlways(expr))

%!test
%! % more differences 1, these don't simplify in sympy (as of 2016-01)
%! expr = (x+1)^2 == x*x + 2*x + 1;
%! assert (~logical(expr))
%! assert (isAlways(expr))

%!test
%! % more differences 2
%! expr = sin(2*x) == 2*sin(x)*cos(x);
%! assert (~logical(expr))
%! assert (isAlways(expr))

%!test
%! % more differences 3, false
%! expr =  x*(x+y) == x^2 + x*y + 1;
%! assert (~logical(expr))
%! assert (~isAlways(expr))
%! assert (~isAlways(expr, 'unknown', 'error'))

%!test
%! % logically not equal, math equal
%! exprn =  x*(x+y) ~= x^2 + x*y;
%! assert (logical(exprn))
%! assert (~isAlways(exprn))
%!test
%! % logically not equal, math not equal
%! exprn =  x*(x+y) ~= x^2 + x*y + 1;
%! assert (logical(exprn))
%! assert (isAlways(exprn))

%!test
%! % equal and not equal
%! e1 = sin(x)^2 + cos(x)^2 == 1;
%! e2 = sin(x)^2 + cos(x)^2 == 2;
%! assert (~logical(e1))
%! assert (isAlways(e1))
%! assert (~logical(e2))
%! assert (~isAlways(e2))
%! assert (~isAlways(e2, 'unknown', 'error'))

%!error <invalid argument .* keyword> isAlways(x, 'unknown', 'kevin')
%!error <Invalid call> isAlways(x, 'unknown')
%!error <assert .* failed> isAlways(x, 'kevin', 'true')

%!error <isAlways: cannot reliably convert sym to bool>
%! a = [x*(x+y)==x^2+x*y  x==y];
%! b = isAlways(a, 'unknown', 'error');

%!error <isAlways: cannot reliably convert sym to bool>
%! a = x==y;
%! b = isAlways(a, 'unknown', 'error');

%!test
%! % array, unknown keyword
%! a = [x==x x==x+1 x==y x*(x+y)==x^2+x*y cos(x)^2+sin(x)^2==2];
%! b = isAlways(a, 'unknown', false);
%! c = isAlways(a, 'unknown', 'false');
%! expect = [true false false true false];
%! assert (islogical(b))
%! assert (isequal (b, expect))
%! assert (isequal (c, expect))
%! b = isAlways(a, 'unknown', true);
%! c = isAlways(a, 'unknown', 'true');
%! expect = [true false true true false];
%! assert (islogical(b))
%! assert (isequal (b, expect))
%! assert (isequal (c, expect))

%!test
%! % ineq
%! e =  x*(x+y) <= x^2 + x*y + 1;
%! assert (~logical(e))
%! assert (isAlways(e))
%! e =  x*(x+y) <= x^2 + x*y;
%! assert (~logical(e))
%! assert (isAlways(e))

%test
% % FIXME; booleans
% e1 = x*(x+1) == x*x+x
% e2 = x*(x+1)+2 == x*x+x+2
% b = e1 & e2
% assert isAlways(b)


function [ t_start, y_start ] = p27_start ( neqn )

%*****************************************************************************80
%
%% P27_START returns the starting point for problem p27.
%
%  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_START, Y_START(NEQN,1), the initial data.
%
  y_start = zeros ( neqn, 1 );

  t_start = 0.0;
  y_start = 110.0;

  return
end


function ans = is_row (v);
% ans = is_row (v);
%returns 1 if v is a row vector
%returns 0 if v is a column vector
%returns -1 if v is a matrix
%
% Ziad Saad July 20 97

if (size (v,1) ~= 1 & size (v,2) ~= 1),
	ans = -1;
end;

if (size (v,1) == 1),
	ans = 1;
	elseif (size (v,2) == 1),
		ans = 0;
end;

return;


function j = countJumps( f )
%COUNTJUMPS Counts the jumps of a vector f
j = sum( diff(f) ~= 0);

end


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

%% -*- texinfo -*-
%% @defmethod  @@symfun private_disp_name (@var{f}, @var{name})
%% A string appropriate for representing the name of this symfun.
%%
%% Private method: this is not the method you are looking for.
%%
%% @end defmethod

function s = private_disp_name(f, input_name)

  if (isempty(input_name))
    s = input_name;
    return
  end

  vars = f.vars;
  if length(vars) == 0
    varstr = '';
  else
    v = vars{1};
    varstr = v.flat;
  end
  for i = 2:length(vars);
    v = vars{i};
    varstr = [varstr ', ' v.flat];
  end
  s = [input_name, '(', varstr, ')'];

end

%!test
%! syms f(x)
%! s = private_disp_name(f, 'f');
%! assert (strcmp (s, 'f(x)'))

%!test
%! syms x y
%! g(y, x) = x + y;
%! s = private_disp_name(g, 'g');
%! assert (strcmp (s, 'g(y, x)'))

%!test
%! syms f(x)
%! assert (isempty (private_disp_name(f, '')))


function [ node_num, node_dim, node_att_num, node_marker_num ] = ...
  triangle_node_size_example ( )

%*****************************************************************************80
%
%% TRIANGLE_NODE_SIZE_EXAMPLE returns the sizes of node information for the example.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 October 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer NODE_NUM, the number of nodes.
%
%    Output, integer NODE_DIM, the spatial dimension.
%
%    Output, integer NODE_ATT_NUM, number of node attributes
%    listed on each node record.
%
%    Output, integer NODE_MARKER_NUM, 1 if every node record
%    includes a final boundary marker value.
%
  node_num = 21;
  node_dim = 2;
  node_att_num = 0;
  node_marker_num = 1;

  return
end


function bool=sde_issquare(V)
%SDE_ISSQUARE  True for square matrices.
%
%   See also: SDE_ISMATRIX, SDE_ISDIAG

%   Andrew D. Horchler, horchler @ gmail . com, Created 4-30-13
%   Revision: 1.2, 5-4-13

bool = (ndims(V) == 2 && size(V,1) == size(V,2));	%#ok<ISMAT>


% isPalindromeNumber: returns true if the given number are a palindrome
%                     otherwise false.
% assumes: the given number is positive
function ans = isPalindromeNumber(number)
  % precondition
  assert(number >= 0,'number must be positive')
  ans = false;
  strNumber = num2str(number); % convert the given number to character array
  if (strNumber == flip(strNumber))
    ans = true;
  endif
endfunction


function r8vec_mask_print ( n, a, mask_num, mask, title )

%*****************************************************************************80
%
%% R8VEC_MASK_PRINT prints a masked R8VEC.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 November 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of components of the vector.
%
%    Input, real A(N), the vector to be printed.
%
%    Input, integer MASK_NUM, the number of masked elements.
%
%    Input, integer MASK(MASK_NUM), the indices of the vector to be printed.
%
%    Input, string TITLE, a title.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Masked vector printout:\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '%s\n', title );
  fprintf ( 1, '\n' );

  for i = 1 : mask_num
    fprintf ( 1, '  %6d: %6d  %14g\n', i, mask(i), a(mask(i)) );
  end

  return
end


function grid_print ( element_order, element_num, element_node )

%*****************************************************************************80
%
%% GRID_PRINT prints the elements that form a grid.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 June 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer ELEMENT_ORDER, the order of the elements.
%
%    Input, integer ELEMENT_NUM, the number of elements.
%
%    Input, integer ELEMENT_NODE(ELEMENT_ORDER,ELEMENT_NUM), the nodes that form
%    each element.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  GRID_PRINT: Element -> Node table.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Element order = %d\n', element_order );
  fprintf ( 1, '  Number of elements = %d\n', element_num );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  #   ' );
  for i = 1 : element_order
    fprintf ( 1, '%3d', i );
  end
  fprintf ( 1, '\n' );
  fprintf ( 1, '\n' );

  for element = 1 : element_num
    fprintf ( 1, '  %3d   ', element );
    for i = 1 : element_order
      fprintf ( 1, '%3d', element_node(i,element) );
    end
    fprintf ( 1, '\n' );
  end

  return
end


function boundary_segment_num = p06_boundary_segment_num ( )

%*****************************************************************************80
%
%% P06_BOUNDARY_SEGMENT_NUM counts the boundary segments in problem 06.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Per-Olof Persson and Gilbert Strang,
%    A Simple Mesh Generator in MATLAB,
%    SIAM Review,
%    Volume 46, Number 2, June 2004, pages 329-345.
%
%  Parameters:
%
%    Output, integer BOUNDARY_SEGMENT_NUM, the number of boundary segments.
%
  boundary_segment_num = 2;

  return
end


%% Advanced Morphology Transformations Demo
%
% In this sample you will learn how to use the OpenCV function
% <matlab:doc('cv.morphologyEx') cv.morphologyEx> to apply
% Morphological Transformation such as:
%
% * Opening
% * Closing
% * Morphological Gradient
% * Top Hat
% * Black Hat
%
% Sources:
%
% * <https://docs.opencv.org/3.2.0/d3/dbe/tutorial_opening_closing_hats.html>
% * <https://github.com/opencv/opencv/blob/3.2.0/samples/cpp/tutorial_code/ImgProc/Morphology_2.cpp>
% * <https://github.com/opencv/opencv/blob/3.2.0/samples/cpp/morphology2.cpp>
% * <https://github.com/opencv/opencv/blob/3.2.0/samples/python/morphology.py>
%

%% Theory
%
% We previously covered two basic Morphology operations:
%
% * Erosion
% * Dilation
%
% Based on these two we can effectuate more sophisticated transformations to
% our images. Here we discuss briefly 5 operations offered by OpenCV.
%
%% 1) Opening
%
% It is obtained by the erosion of an image followed by a dilation.
%
% $$dst = open( src, element) = dilate( erode( src, element ) )$$
%
% Useful for removing small objects (it is assumed that the objects are bright
% on a dark foreground). For instance, check out the example below. The image
% at the left is the original and the image at the right is the result after
% applying the opening transformation. We can observe that the small spaces in
% the corners of the letter tend to disappear.
%
% <<https://docs.opencv.org/3.2.0/Morphology_2_Tutorial_Theory_Opening.png>>
%
% For the sake of clarity, we have performed the opening operation (|7x7|
% rectangular structuring element) on the same original image but inverted
% such as the object in white is now the letter.
%
% <<https://docs.opencv.org/3.2.0/Morphology_2_Tutorial_Theory_Opening_2.png>>
%
% (Left image: original image inverted, right image: resulting opening).
%
%% 2) Closing
%
% It is obtained by the dilation of an image followed by an erosion.
%
% $$dst = close( src, element ) = erode( dilate( src, element ) )$$
%
% Useful to remove small holes (dark regions).
%
% <<https://docs.opencv.org/3.2.0/Morphology_2_Tutorial_Theory_Closing.png>>
%
% On the inverted image, we have performed the closing operation (|7x7|
% rectangular structuring element):
%
% <<https://docs.opencv.org/3.2.0/Morphology_2_Tutorial_Theory_Closing_2.png>>
%
% (Left image: original image inverted, right image: resulting closing).
%
%% 3) Morphological Gradient
%
% It is the difference between the dilation and the erosion of an image.
%
% $$dst = morph_{grad}( src, element )
%       = dilate( src, element ) - erode( src, element )$$
%
% It is useful for finding the outline of an object as can be seen below:
%
% <<https://docs.opencv.org/3.2.0/Morphology_2_Tutorial_Theory_Gradient.png>>
%
%% 4) Top Hat
%
% It is the difference between an input image and its opening.
%
% $$dst = tophat( src, element ) = src - open( src, element )$$
%
% <<https://docs.opencv.org/3.2.0/Morphology_2_Tutorial_Theory_TopHat.png>>
%
%% 5) Black Hat
%
% It is the difference between the closing and its input image
%
% $$dst = blackhat( src, element ) = close( src, element ) - src$$
%
% <<https://docs.opencv.org/3.2.0/Morphology_2_Tutorial_Theory_BlackHat.png>>
%
%% References
%
% * "Learning OpenCV" by Bradski and Kaehler.
%

function varargout = morphology_demo_gui2(im)
    % load source image
    if nargin < 1
        src = imread(fullfile(mexopencv.root(),'test','img001.jpg'));
    elseif ischar(im)
        src = imread(im);
    else
        src = im;
    end

    % create the UI
    h = buildGUI(src);
    if nargout > 0, varargout{1} = h; end
end

function onChange(~,~,h)
    %ONCHANGE  Event handler for UI controls

    % retrieve current values from UI controls
    ksize = round(get(h.slid, 'Value'));
    opIdx = get(h.pop(1), 'Value');
    shapeIdx = get(h.pop(2), 'Value');
    set(h.txt, 'String',sprintf('%2d',ksize));

    % options (structuring element shape and morphological operation)
    shapes = {'Rect', 'Cross', 'Ellipse'};
    types = {'Erode', 'Dilate', 'Open', 'Close', 'Gradient', 'Tophat', ...
        'Blackhat', ''};

    % apply the specified morphology operation
    elem = cv.getStructuringElement('Shape',shapes{shapeIdx}, ...
        'KSize',[ksize ksize]*2+1, 'Anchor',[ksize ksize]);
    if ~isempty(types{opIdx})
        dst = cv.morphologyEx(h.src, types{opIdx}, 'Element',elem);
    else
        dst = h.src;
    end

    % show result
    set(h.img, 'CData',dst);
    drawnow;
end

function h = buildGUI(img)
    %BUILDGUI  Creates the UI

    % parameters
    ksize = 3;
    max_ksize = 21;
    sz = size(img);
    sz(2) = max(sz(2), 250);  % minimum figure width

    % build the user interface (no resizing to keep it simple)
    h = struct();
    h.src = img;
    h.fig = figure('Name','Morphology Transformations Demo', ...
        'NumberTitle','off', 'Menubar','none', 'Resize','off', ...
        'Position',[200 200 sz(2) sz(1)+29]);
    if ~mexopencv.isOctave()
        %HACK: not implemented in Octave
        movegui(h.fig, 'center');
    end
    h.ax = axes('Parent',h.fig, 'Units','pixels', 'Position',[1 30 sz(2) sz(1)]);
    if ~mexopencv.isOctave()
        h.img = imshow(img, 'Parent',h.ax);
    else
        %HACK: https://savannah.gnu.org/bugs/index.php?45473
        axes(h.ax);
        h.img = imshow(img);
    end
    h.pop(1) = uicontrol('Parent',h.fig, 'Style','popupmenu', ...
       'Position',[5 5 70 20], 'Value',3, ...
       'String', {'Erosion','Dilation','Opening','Closing','Gradient',...
            'Top Hat','Black Hat','-None-'});
    h.pop(2) = uicontrol('Parent',h.fig, 'Style','popupmenu', ...
       'Position',[75 5 70 20], 'String',{'Rect','Cross','Ellipse'});
    h.slid = uicontrol('Parent',h.fig, 'Style','slider', 'Value',ksize, ...
        'Min',1, 'Max',max_ksize, 'SliderStep',[1 5]./(max_ksize-1), ...
        'Position',[150 5 sz(2)-150-20-5 20]);
    h.txt = uicontrol('Parent',h.fig, 'Style','text', 'FontSize',11, ...
        'Position',[sz(2)-20-5 5 20 20], 'String',num2str(ksize));

    % hook event handlers, and trigger default start
    set([h.slid, h.pop], 'Callback',{@onChange,h}, ...
        'Interruptible','off', 'BusyAction','cancel');
    onChange([],[],h);
end


function exact = p48_exact ( )

%*****************************************************************************80
%
%% P48_EXACT returns the exact integral for problem 48.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 November 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real EXACT, the value of the integral.
%
  exact = -4.0;

  return
end


function r8vec_permute_uniform_test ( )

%*****************************************************************************80
%
%% R8VEC_PERMUTE_UNIFORM_TEST tests R8VEC_PERMUTE_UNIFORM.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 May 2015
%
%  Author:
%
%    John Burkardt
%
  n = 12;
  seed = 123456789;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'R8VEC_PERMUTE_UNIFORM_TEST\n' );
  fprintf ( 1, '  R8VEC_PERMUTE_UNIFORM randomly reorders an R8VEC.\n' );

  a = 100 + ( 1 : n );

  r8vec_print ( n, a, '  A, before rearrangement:' );

  [ a, seed ] = r8vec_permute_uniform ( n, a, seed );

  r8vec_print ( n, a, '  A, after rearrangement:' );

  return
end


function title = p01_title ( )

%*****************************************************************************80
%
%% P01_TITLE returns a title for problem 1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 October 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string TITLE, a title for the problem.
%
  title = 'The Fletcher-Powell helical valley function.';

  return
end


function varargout=sigstar(groups,stats,nosort)
    % sigstar - Add significance stars to bar charts, boxplots, line charts, etc,
    %
    % H = sigstar(groups,stats,nsort)
    %
    % Purpose
    % Add stars and lines highlighting significant differences between pairs of groups.
    % The user specifies the groups and associated p-values. The function handles much of
    % the placement and drawing of the highlighting. Stars are drawn according to:
    %   * represents p<=0.05
    %  ** represents p<=1E-2
    % *** represents p<=1E-3
    %
    %
    % Inputs
    % groups - a cell array defining the pairs of groups to compare. Groups defined
    %          either as pairs of scalars indicating locations along the X axis or as
    %          strings corresponding to X-tick labels. Groups can be a mixture of both
    %          definition types.
    % stats -  a vector of p-values the same length as groups. If empty or missing it's
    %          assumed to be a vector of 0.05s the same length as groups. Nans are treated
    %          as indicating non-significance.
    % nsort -  optional, 0 by default. If 1, then significance markers are plotted in
    %          the order found in groups. If 0, then they're sorted by the length of the
    %          bar.
    %
    % Outputs
    % H - optionally return handles for significance highlights. Each row is a different
    %     highlight bar. The first column is the line. The second column is the text (stars).
    %
    %
    % Examples
    % 1.
    % bar([5,2,1.5])
    % sigstar({[1,2], [1,3]})
    %
    % 2.
    % bar([5,2,1.5])
    % sigstar({[2,3],[1,2], [1,3]},[nan,0.05,0.05])
    %
    % 3.  **DOESN'T WORK IN 2014b**
    % R=randn(30,2);
    % R(:,1)=R(:,1)+3;
    % boxplot(R)
    % set(gca,'XTick',1:2,'XTickLabel',{'A','B'})
    % H=sigstar({{'A','B'}},0.01);
    % ylim([-3,6.5])
    % set(H,'color','r')
    %
    % 4. Note the difference in the order with which we define the groups in the
    %    following two cases.
    % x=[1,2,3,2,1];
    % subplot(1,2,1)
    % bar(x)
    % sigstar({[1,2], [2,3], [4,5]})
    % subplot(1,2,2)
    % bar(x)
    % sigstar({[2,3],[1,2], [4,5]})
    %
    % ALSO SEE: demo_sigstar
    %
    % KNOWN ISSUES:
    % 1. Algorithm for identifying whether significance bar will overlap with
    %    existing plot elements may not work in some cases (see line 277)
    % 2. Bars may not look good on exported graphics with small page sizes.
    %    Simply increasing the width and height of the graph with the
    %    PaperPosition property of the current figure should fix things.
    %
    % Rob Campbell - CSHL 2013

    %Input argument error checking

    %If the user entered just one group pair and forgot to wrap it in a cell array
    %then we'll go easy on them and wrap it here rather then generate an error
    if ~iscell(groups) & length(groups)==2
        groups={groups};
    end

    if nargin<2
        stats=repmat(0.05,1,length(groups));
    end
    if isempty(stats)
        stats=repmat(0.05,1,length(groups));
    end
    if nargin<3
        nosort=0;
    end

    %Check the inputs are of the right sort
    if ~iscell(groups)
        error('groups must be a cell array')
    end

    if ~isvector(stats)
        error('stats must be a vector')
    end

    if length(stats)~=length(groups)
        error('groups and stats must be the same length')
    end

    %Each member of the cell array groups may be one of three things:
    %1. A pair of indices.
    %2. A pair of strings (in cell array) referring to X-Tick labels
    %3. A cell array containing one index and one string
    %
    % For our function to run, we will need to convert all of these into pairs of
    % indices. Here we loop through groups and do this.

    xlocs=nan(length(groups),2); %matrix that will store the indices
    xtl=get(gca,'XTickLabel');

    for ii=1:length(groups)
        grp=groups{ii};

        if isnumeric(grp)
            xlocs(ii,:)=grp; %Just store the indices if they're the right format already

        elseif iscell(grp) %Handle string pairs or string/index pairs

            if isstr(grp{1})
                a=strmatch(grp{1},xtl);
            elseif isnumeric(grp{1})
                a=grp{1};
            end
            if isstr(grp{2})
                b=strmatch(grp{2},xtl);
            elseif isnumeric(grp{2})
                b=grp{2};
            end

            xlocs(ii,:)=[a,b];
        end

        %Ensure that the first column is always smaller number than the second
        xlocs(ii,:)=sort(xlocs(ii,:));

    end

    %If there are any NaNs we have messed up.
    if any(isnan(xlocs(:)))
        error('Some groups were not found')
    end

    %Optionally sort sig bars from shortest to longest so we plot the shorter ones first
    %in the loop below. Usually this will result in the neatest plot. If we waned to
    %optimise the order the sig bars are plotted to produce the neatest plot, then this
    %is where we'd do it. Not really worth the effort, though, as few plots are complicated
    %enough to need this and the user can define the order very easily at the command line.
    if ~nosort
        [~,ind]=sort(xlocs(:,2)-xlocs(:,1),'ascend');
        xlocs=xlocs(ind,:);groups=groups(ind);
        stats=stats(ind);
    end

    %-----------------------------------------------------
    %Add the sig bar lines and asterisks
    holdstate=ishold;
    hold on

    H=ones(length(groups),2); %The handles will be stored here

    y=ylim;
    yd=myRange(y)*0.05; %separate sig bars vertically by 5%

    for ii=1:length(groups)
        thisY=findMinY(xlocs(ii,:))+yd;
        H(ii,:)=makeSignificanceBar(xlocs(ii,:),thisY,stats(ii));
    end
    %-----------------------------------------------------

    %Now we can add the little downward ticks on the ends of each line. We are
    %being extra cautious and leaving this it to the end just in case the y limits
    %of the graph have changed as we add the highlights. The ticks are set as a
    %proportion of the y axis range and we want them all to be the same the same
    %for all bars.
    yd=myRange(ylim)*0.01; %Ticks are 1% of the y axis range
    for ii=1:length(groups)
        y=get(H(ii,1),'YData');
        y(1)=y(1)-yd;
        y(4)=y(4)-yd;
        set(H(ii,1),'YData',y)
    end

    %Be neat and return hold state to whatever it was before we started
    if ~holdstate
        hold off
    elseif holdstate
        hold on
    end

    %Optionally return the handles to the plotted significance bars (first column of H)
    %and asterisks (second column of H).
    if nargout>0
        varargout{1}=H;
    end

end %close sigstar

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Internal functions

function H=makeSignificanceBar(x,y,p)
    %makeSignificanceBar produces the bar and defines how many asterisks we get for a
    %given p-value

    if p<=1E-3
        stars='***';
    elseif p<=1E-2
        stars='**';
    elseif p<=0.05
        stars='*';
    elseif isnan(p)
        stars='n.s.';
    else
        stars='';
    end

    x=repmat(x,2,1);
    y=repmat(y,4,1);

    H(1)=plot(x(:),y,'-k','LineWidth',3,'Tag','sigstar_bar');

    %Increase offset between line and text if we will print "n.s."
    %instead of a star.
    if ~isnan(p)
        offset=0.005;
    else
        offset=0.02;
    end

    starY=mean(y)+myRange(ylim)*offset;
    H(2)=text(mean(x(:)),starY,stars,...
        'HorizontalAlignment','Center',...
        'BackGroundColor','none',...
        'Tag','sigstar_stars');

    Y=ylim;
    if Y(2)<starY
        ylim([Y(1),starY+myRange(Y)*0.05])
    end

end %close makeSignificanceBar

function Y=findMinY(x)
    % The significance bar needs to be plotted a reasonable distance above all the data points
    % found over a particular range of X values. So we need to find these data and calculat the
    % the minimum y value needed to clear all the plotted data present over this given range of
    % x values.
    %
    % This version of the function is a fix from Evan Remington
    oldXLim = get(gca,'XLim');
    oldYLim = get(gca,'YLim');

    axis(gca,'tight')
    set(gca,'xlim',x) %Matlab automatically re-tightens y-axis

    yLim = get(gca,'YLim'); %Now have max y value of all elements within range.
    Y = max(yLim);

    axis(gca,'normal')
    set(gca,'XLim',oldXLim,'YLim',oldYLim)

end %close findMinY

function rng=myRange(x)
    %replacement for stats toolbox range function
    rng = max(x) - min(x);
end %close myRange


function chrpak_test057 ( )

%*****************************************************************************80
%
%% TEST057 tests OCT_TO_I4 and I4_TO_OCT.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 June 2007
%
%  Author:
%
%    John Burkardt
%
  test_num = 3;

  i4_test = [ 21, -32, 1776 ];

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST057\n' );
  fprintf ( 1, '  OCT_TO_I4, octal->integer.\n' );
  fprintf ( 1, '  I4_TO_OCT, integer->octal\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '        I4       OCT        I4\n' );
  fprintf ( 1, '\n' );

  for test = 1 : test_num

    i4 = i4_test(test);
    oct = i4_to_oct ( i4 );
    j4 = oct_to_i4 ( oct );

    fprintf ( 1, '  %8d  %8s  %8d\n', i4, oct, j4 );

  end

  return
end


function sequence_streak_display ( file_name, direction )

%*****************************************************************************80
%
%% SEQUENCE_STREAK_DISPLAY makes a "streak plot" of a sequence.
%
%  Discussion:
%
%    The sequence information is assumed to be available in
%    a text file, with one sequence entry per line.
%
%    One reason for making plots this way is to try to
%    see the "fill in" pattern of a sequence.  For instance,
%    the van der Corput sequence has the property that all
%    entries lie in [0,1], and that it first eliminates all
%    gaps of size 1/2, then of size 1/4, then 1/8 and so on.
%
%    Perhaps a second reason for looking at plots this way
%    is to notice patterns of convergence in a sequence.
%
%  Example:
%
%    The sequence 1, 3, 5, 7, 6, 2, 4 would plot as
%
%       *---
%        *--
%      *----
%          *
%     *-----
%         *-
%    *------
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 May 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string FILE_NAME, the name of a text file containing
%    the sequence.
%
%    Input, character DIRECTION, defines the direction of the sequence.
%    'R', goes to the right;
%    'L', goes to the left;
%    'U', goes up;
%    'D', goes down.
%
  timestamp ( );

  fprintf ( 1, '\n' );
  fprintf ( 1, 'SEQUENCE_STREAK_DISPLAY\n' );
  fprintf ( 1, '  MATLAB version\n' );

  y = load ( file_name );

  n = length ( y );
  x(1:n) = 1:n;

  if ( direction == 'R' | direction == 'r' )

    plot ( x, y, '*' );

    for i = 1 : n
      line ( [x(i), n], [y(i), y(i) ] )
    end

    xlabel ( 'Sequence Direction--->', ...
      'FontName', 'Helvetica', 'FontWeight', 'bold', ...
      'FontSize', 16  )

    ylabel ( 'Sequence Value', ...
      'FontName', 'Helvetica', 'FontWeight', 'bold', ...
      'FontSize', 16, 'Rotation', 90 );

    title ( 'Sequence "Streak" Plot', ...
      'FontName', 'Helvetica', 'FontWeight', ...
      'bold', 'FontSize', 16 );

  elseif ( direction == 'L' | direction == 'l' )

    plot ( x, y, '*' );

    for i = 1 : n
      line ( [1, x(i)], [y(i), y(i) ] )
    end

    xlabel ( 'Sequence Direction--->', ...
      'FontName', 'Helvetica', 'FontWeight', 'bold', ...
      'FontSize', 16  )

    ylabel ( 'Sequence Value', ...
      'FontName', 'Helvetica', 'FontWeight', 'bold', ...
      'FontSize', 16, 'Rotation', 90 );

    title ( 'Sequence "Streak" Plot', ...
      'FontName', 'Helvetica', 'FontWeight', ...
      'bold', 'FontSize', 16 );

  elseif ( direction == 'U' | direction == 'u' )

    plot ( y, x, '*' );

    for i = 1 : n
      line ( [y(i), y(i) ], [x(i), n] )
    end

    xlabel ( 'Sequence Value', ...
      'FontName', 'Helvetica', 'FontWeight', 'bold', ...
      'FontSize', 16  )

    ylabel ( 'Sequence Direction--->', ...
      'FontName', 'Helvetica', 'FontWeight', 'bold', ...
      'FontSize', 16, 'Rotation', 90 );

    title ( 'Sequence "Streak" Plot', ...
      'FontName', 'Helvetica', 'FontWeight', ...
      'bold', 'FontSize', 16 );

  elseif ( direction == 'D' | direction == 'd' )

    plot ( y, x, '*' );

    for i = 1 : n
      line ( [y(i), y(i) ], [1, x(i)] )
    end

    xlabel ( 'Sequence Value', ...
      'FontName', 'Helvetica', 'FontWeight', 'bold', ...
      'FontSize', 16  )

    ylabel ( 'Sequence Direction--->', ...
      'FontName', 'Helvetica', 'FontWeight', 'bold', ...
      'FontSize', 16, 'Rotation', 90 );

    title ( 'Sequence Streak Plot', ...
      'FontName', 'Helvetica', 'FontWeight', ...
      'bold', 'FontSize', 16 );
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, 'SEQUENCE_STREAK_DISPLAY\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1,'\n' );
  timestamp ( );

  return
end
function timestamp ( )

%*****************************************************************************80
%
%% TIMESTAMP prints the current YMDHMS date as a timestamp.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  t = now;
  c = datevec ( t );
  s = datestr ( c, 0 );
  fprintf ( 1, '%s\n', s );

  return
end


function p = patchline(xs,ys,varargin)
% Plot lines as patches (efficiently)
%
% SYNTAX:
%     patchline(xs,ys)
%     patchline(xs,ys,zs,...)
%     patchline(xs,ys,zs,'PropertyName',propertyvalue,...)
%     p = patchline(...)
%
% PROPERTIES:
%     Accepts all parameter-values accepted by PATCH.
%
% DESCRIPTION:
%     p = patchline(xs,ys,zs,'PropertyName',propertyvalue,...)
%         Takes a vector of x-values (xs) and a same-sized
%         vector of y-values (ys). z-values (zs) are
%         supported, but optional; if specified, zs must
%         occupy the third input position. Takes all P-V
%         pairs supported by PATCH. Returns in p the handle
%         to the resulting patch object.
%
% NOTES:
%     Note that we are drawing 0-thickness patches here,
%     represented only by their edges. FACE PROPERTIES WILL
%     NOT NOTICEABLY AFFECT THESE OBJECTS! (Modify the
%     properties of the edges instead.)
%
%     LINUX (UNIX) USERS: One test-user found that this code
%     worked well on his Windows machine, but crashed his
%     Linux box. We traced the problem to an openGL issue;
%     the problem can be fixed by calling 'opengl software'
%     in your <http://www.mathworks.com/help/techdoc/ref/startup.html startup.m>.
%     (That command is valid at startup, but not at runtime,
%     on a unix machine.)
%
% EXAMPLES:
%%% Example 1:
%
% n = 10;
% xs = rand(n,1);
% ys = rand(n,1);
% zs = rand(n,1)*3;
% plot3(xs,ys,zs,'r.')
% xlabel('x');ylabel('y');zlabel('z');
% p  = patchline(xs,ys,zs,'linestyle','--','edgecolor','g',...
%     'linewidth',3,'edgealpha',0.2);
%
%%% Example 2: (Note "hold on" not necessary here!)
%
% t = 0:pi/64:4*pi;
% p(1) = patchline(t,sin(t),'edgecolor','b','linewidth',2,'edgealpha',0.5);
% p(2) = patchline(t,cos(t),'edgecolor','r','linewidth',2,'edgealpha',0.5);
% l = legend('sine(t)','cosine(t)');
% tmp = sort(findobj(l,'type','patch'));
% for ii = 1:numel(tmp)
%     set(tmp(ii),'facecolor',get(p(ii),'edgecolor'),'facealpha',get(p(ii),'edgealpha'),'edgecolor','none')
% end
%
%%% Example 3 (requires Image Processing Toolbox):
%%%   (NOTE that this is NOT the same as showing a transparent image on
%%%         of the existing image. (That functionality is
%%%         available using showMaskAsOverlay or imoverlay).
%%%         Instead, patchline plots transparent lines over
%%%         the image.)
%
% img = imread('rice.png');
% imshow(img)
% img = imtophat(img,strel('disk',15));
% grains = im2bw(img,graythresh(img));
% grains = bwareaopen(grains,10);
% edges = edge(grains,'canny');
% boundaries = bwboundaries(edges,'noholes');
% cmap = jet(numel(boundaries));
% ind = randperm(numel(boundaries));
% for ii = 1:numel(boundaries)
% patchline(boundaries{ii}(:,2),boundaries{ii}(:,1),...
%     'edgealpha',0.2,'edgecolor',cmap(ind(ii),:),'linewidth',3);
% end
%
% Written by Brett Shoelson, PhD
% brett.shoelson@mathworks.com
% 5/31/2012
%
% Revisions:
% 6/26 Improved rice.png example, modified FEX image.
%
% Copyright 2012 MathWorks, Inc.
%
% See also: patch, line, plot

[zs,PVs] = parseInputs(varargin{:});
if rem(numel(PVs),2) ~= 0
    % Odd number of inputs!
    error('patchline: Parameter-Values must be entered in valid pairs')
end

% Facecolor = 'k' is (essentially) ignored here, but syntactically necessary
if isempty(zs)
    p = patch([xs(:);NaN],[ys(:);NaN],'k');
else
    p = patch([xs(:);NaN],[ys(:);NaN],[zs(:);NaN],'k');
end

% Apply PV pairs
for ii = 1:2:numel(PVs)
    set(p,PVs{ii},PVs{ii+1})
end
if nargout == 0
    clear p
end

function [zs,PVs] = parseInputs(varargin)
if isnumeric(varargin{1})
    zs = varargin{1};
    PVs = varargin(2:end);
else
    PVs = varargin;
    zs = [];
end


function i4vec_transpose_print ( n, a, title )

%*****************************************************************************80
%
%% I4VEC_TRANSPOSE_PRINT prints an I4VEC "transposed".
%
%  Example:
%
%    A = (/ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 /)
%    TITLE = 'My vector:  '
%
%    My vector:
%
%       1    2    3    4    5
%       6    7    8    9   10
%      11
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 April 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of components of the vector.
%
%    Input, integer A(N), the vector to be printed.
%
%    Input, string TITLE, a title.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '%s\n', title );
  fprintf ( 1, '\n' );

  for ilo = 1 : 5 : n
    ihi = min ( ilo + 5 - 1, n );
    for i = ilo : ihi
      fprintf ( 1, '  %4d', a(i) );
    end
    fprintf ( 1, '\n' );
  end

  return
end


function graph_arc_print ( nedge, inode, jnode, title )

%*****************************************************************************80
%
%% GRAPH_ARC_PRINT prints out a graph from an edge list.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 June 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NEDGE, the number of edges.
%
%    Input, integer INODE(NEDGE), JNODE(NEDGE), the beginning
%    and end nodes of the edges.
%
%    Input, string TITLE, a title.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '%s\n', title );
  fprintf ( 1, '\n' );

  for i = 1 : nedge
    fprintf ( 1, '  %2d  %4d  %4d\n', i, inode(i), jnode(i) );
  end

  return
end


%% Lists and Indexing
%
%%
%
% <https://de.mathworks.com/help/matlab/learn_matlab/matrices-and-arrays.html
% Matlab documentation>


% [MIN, MAX] = range2(MTX)
%
% Compute minimum and maximum values of MTX, returning them as a 2-vector.

% Eero Simoncelli, 3/97.

function [mn, mx] = range2(mtx)

%% NOTE: THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD)

fprintf(1,'WARNING: You should compile the MEX code for "range2", found in the MEX subdirectory.  It is MUCH faster.\n');

if (~isreal(mtx))
  error('MTX must be real-valued');
end

mn = min(min(mtx));
mx = max(max(mtx));


function r83row_print_part_test ( )

%*****************************************************************************80
%
%% R83ROW_PRINT_PART_TEST tests R83ROW_PRINT_PART.
%
%  Discussion:
%
%    An R83ROW is a (3,N) array of R8's.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2015
%
%  Author:
%
%    John Burkardt
%
  n = 10;
%
%  Set up the array by rows.
%
  v = [ ...
    11.0,  12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0; ...
    21.0,  22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0; ...
    31.0,  32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0  ];

  fprintf ( 1, '\n' );
  fprintf ( 1, 'R83ROW_PRINT_PART_TEST\n' );
  fprintf ( 1, '  R83ROW_PRINT_PART prints part of an R83ROW.\n' );

  max_print = 2;
  r83row_print_part ( n, v, max_print, '  Output with MAX_PRINT = 2' );

  max_print = 5;
  r83row_print_part ( n, v, max_print, '  Output with MAX_PRINT = 5' );

  max_print = 25;
  r83row_print_part ( n, v, max_print, '  Output with MAX_PRINT = 25' );

  return
end


function [ h, hmin, hmax ] = p13_stepsize ( option )

%*****************************************************************************80
%
%% P13_STEPSIZE returns step sizes for problem 13.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 September 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer OPTION, the option index.
%
%    Output, real H, HMIN, HMAX, suggested values for the
%    initial step, the minimum step, and the maximum step.
%
  h =     2.000;
  hmin =  0.001;
  hmax = 10.000;

  return
end


function x = p17_root ( i )

%*****************************************************************************80
%
%% P17_ROOT returns a root for problem 17.
%
%  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 = 2.0945514815423265;
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'P17_ROOT - Fatal error!\n' );
    fprintf ( 1, '  Illegal root index = %d\n', i );
    error ( 'P17_ROOT - Fatal error!' );
  end

  return
end


function exact = p05_exact ( )

%*****************************************************************************80
%
%% P05_EXACT returns the estimated integral for problem 5.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 November 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real EXACT, the estimated value of the integral.
%
  exact = 1.5822329637296729331;

  return
end


function r = isempty(a)
%ISEMPTY      Returns 1 if input is empty, i.e. [], in the sense of Matlab
%
%   r = isempty(a)
%
%There are no empty intervals in the mathematical sense in INTLAB. For details,
%  please see Readme.txt
%

% written  09/29/02     S.M. Rump
% modified 04/04/04     S.M. Rump  set round to nearest for safety
% modified 04/06/05     S.M. Rump  rounding unchanged
% modified 10/12/05     S.M. Rump  functionality exchanged with @long\isempty_
% modified 04/22/09     S.M. Rump  isempty_ removed
%

  r = isempty(a.sign) | isempty(a.mantissa) | isempty(a.exponent);


function s = ymd_to_s_julian ( y, m, d )

%*****************************************************************************80
%
%% YMD_TO_S_JULIAN writes a Julian YMD date into a string.
%
%  Format:
%
%    AD YYYY/MM/DD
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    13 March 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, M, D, the YMD date.
%
%    Output, string S, a representation of the date.
%
  if ( y < 0 )
    s = sprintf ( 'BC %d/%02d/%02d', -y, m, d );
  else
    s = sprintf ( 'AD %d/%02d/%02d', y, m, d );
  end

  return
end


function x = p11_start ( )

%*****************************************************************************80
%
%% P11_START returns a starting point for optimization for problem 11.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 February 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real X, a starting point for the optimization.
%
  x = 0.75;

  return
end


function[b]=allall(x)
%ALLALL  ALLALL(X)=ALL(X(:))
%   _________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2004 J.M. Lilly --- type 'help jlab_license' for details
b=all(x(:));


function i4vec_decrement_test ( )

%*****************************************************************************80
%
%% I4VEC_DECREMENT_TEST tests I4VEC_DECREMENT.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 January 2015
%
%  Author:
%
%    John Burkardt
%
  n = 4;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'I4VEC_DECREMENT_TEST\n' );
  fprintf ( 1, '  I4VEC_DECREMENT decrements an I4VEC.\n' );

  v_lo = -5;
  v_hi = 10;
  seed = 123456789;
  [ v, seed ] = i4vec_uniform_ab ( n, v_lo, v_hi, seed );
  i4vec_print ( n, v, '  The I4VEC:' );
  v = i4vec_decrement ( n, v );
  i4vec_print ( n, v, '  The I4VEC after decrementing:' );

  return
end


function [ know, x ] = p01_sol ( m, know )

%*****************************************************************************80
%
%% P01_SOL returns the solution for problem 01.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 February 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the spatial dimension.
%
%    Input/output, integer KNOW.
%    On input, KNOW is 0, or the index of the previously returned solution.
%    On output, KNOW is 0 if there are no more solutions, or it is the
%    index of the next solution.
%
%    Output, real X(M,1), the solution, if known.
%
  if ( know == 0 )
    know = 1;
    x(1:m,1) = 1.0;
  else
    know = 0;
    x(1:m,1) = 0.0;
  end

  return
end


function title = p03_title ( )

%*****************************************************************************80
%
%% P03_TITLE returns a title for problem 3.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 January 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string TITLE, a title for the problem.
%
  title = 'The gaussian function';

  return
end


function [data, count] = freadbkj(infile, lines, bkformat, machinefmt ,r0, rN, c0, cN)
% FREADBK  --  Read binary data file.
%
%   DATA = FREADBK pops up a menu to select a filename, asks for the number
%   of lines and format of the input file, and reads in the data (double).
%
%   DATA = FREADBK(FILENAME) fopens the specified file with read permission and
%   returns a row vector DATA.  Format is assumed to be float32 format.
%
%   [DATA, COUNT] = FREADBK(FILENAME) optionally returns the number of elements
%   successfully read.
%
%   [DATA, COUNT] = FREADBK(FILENAME, NUMLINES) includes an optional NUMLINES
%   argument for the number of lines in the file.  Matrix DATA is returned of
%   size NUMLINES rows and the appropriate number of columns.
%
%   [DATA, COUNT] = FREADBK(FILENAME, NUMLINES, BKFORMAT) reads in a file in
%   the format BKFORMAT.  Which is one of the formats specified in FREAD (see
%   help fread), or one of these with a prepended 'cpx' for complex data types.
%   (DATA must be stored major row order, pixel interleaved):
%	'cpxfloat32'	complex floating point, 32 bits.
%	'cpxint16'	complex signed 16 bit short integers, ...
%	'cpx...'	...
%      ('mph'           format: use 'cpxfloat32')
%      ('hgt'           format: use 'freadhgt' function)
%
%   [DATA, COUNT] = FREADBK(FILENAME, NUMLINES, BKFORMAT, MACHINEFMT) additionally
%   specifies the order for reading or writing bytes or bits in the file using the machinefmt argument
%   MACHINEFMT:
%   'n' or 'native'         Your system byte ordering (default)
%   'b' or 'ieee-be'        Big-endian ordering (GAMMA software, for example)
%   'l' or 'ieee-le'        Little-endian ordering
%   's' or 'ieee-be.l64'    Big-endian ordering, 64-bit long data type
%   'a' or 'ieee-le.l64'    Little-endian ordering, 64-bit long data type
%
%   [DATA, COUNT] = FREADBK(FILENAME, NUMLINES, BKFORMAT, r0, rN, c0, cN) only
%   read in the part between: row r0 to row rN, and between column c0 to cN.
%   Indexes start at 1, stop at numlines/width. r0=0 all rows, c0=0 means all
%   columns.
%
%   Examples:
%     To read in a file with 2 channels (complex), stored pixel interleaved, ie,
%     (row1: RE1 - IM1 - RE2 - IM2 - RE3 - ...)
%     (row2: RE1 - IM1 - RE2 - IM2 - RE3 - ...)
%     (      ...                              )
%     in float32 format, which has a height of 100 lines, and a width of 250
%     complex pixels, use:
%       D = freadbk('filename',100,'cpxfloat32');
%
%     To crop this file while reading, between rows 1:10, columns 101:110, use:
%       D = freadbk('filename',100,'cpxfloat32','n',1, 10, 101, 110);
%
%   See also FWRITEBK, FOPEN, FREAD, FWRITE, LOAD, SAVE, FPRINTF,
%   FSEEK, FTELL, FREADHGT, FWRITEHGT
%

% $Revision: 1.12 $  $Date: 2001/09/28 14:24:32 $
% Bert Kampes, 04-Mar-2000

%   ======================================================================
%   04/2009 MJ add machinefmt
%   ======================================================================

%%% Handle input. (varargin?)
%if (nargin >  3) error('working on this... not yet ok, sorry.'); end;
false=0; true=1;
complextype=false; readwholefile=false;%		defaults

if (nargin <  8) cN = 0; end;%				fall through (not...)
if (nargin <  7) c0 = 0; end;%				fall through
if (nargin <  6) rN = 0; end;%				fall through
if (nargin <  5) r0 = 0; readwholefile=true; end;%	fall through
if (nargin <  4) machinefmt = 'n'; end;%	fall through
if (nargin <  3) bkformat='float32'; end;%		fall through
if (nargin <  2) lines=1; end;%				fall through
if (nargin <  1)
    [infile, inpath] = uigetfile('*', 'Select binary input float file', 0,0);
    infile   = [inpath,infile];
    lines    = input('Enter number of lines in file: ');
    bkformat = input('Format (enter between single quotes): ');% make a gui...
end;
%%% Check if whole file should be read regardless of r0,rNc0,cN.
if (c0==1 & r0==1 & rN==lines)
  bytesperelem = datatypesize(bkformat);%	in bytes
  filesize     = fsize(infile);%		in bytes
  filewidth    = filesize/(bytesperelem*lines);%ok for complex
  if (cN==filewidth)
    readwholefile=true;
  end;
end
% if (readwholefile==true)
%   disp(['% Reading whole file: ', infile]);
% end;

%%% Check bkformat for complex type: 'cpx*'
if (~ischar(bkformat)) error('FREADBK: bkformat must be string.'); end;
if (~ischar(infile))   error('FREADBK: infile must be string.'); end;
if (length(bkformat)==3)
  if (bkformat=='mph')
    disp('changing mph format to cpxfloat32');
    bkformat='cpxfloat32';
  end
  if (bkformat=='hgt')
    error('please use freadhgt for hgt format.');
  end
end
%%% complex types defined as prepended 'cpx'
if (length(bkformat)>6)
  if (bkformat(1:3)=='cpx')
    complextype = true;
    bkformat=bkformat(4:length(bkformat));
  end;
end;

%%% Read from file in column vector.
fid = fopen(infile,'r',machinefmt);
if (fid<0)%						try one more time
  [infile, inpath] = uigetfile('*', 'Select binary input file', 0,0);
  infile = [inpath,infile];
  fid    = fopen(infile,'r',machinefmt);
  if (fid<0) error(ferror(fid)); end;
end;

if (readwholefile==true)
  [data,count]=fread(fid,bkformat);%		read data in column vector
				%		count is number of elements, not bytes...
else
  bytesperelem = datatypesize(bkformat);%	in bytes
  filesize     = fsize(fid);%			in bytes
  filewidth    = filesize/(bytesperelem*lines);%ok for complex
  if (r0 > rN) error('r0 > rN'); end;
  if (c0 > cN) error('c0 > cN'); end;
  if (c0==0) c0=1; cN=filewidth; end;
  if (r0==0) r0=1; rN=lines; end;
  if (r0 < 1)            error('r0 < 1'); end;
  if (rN > lines)        error('rN > lines'); end;
  if (c0 < 1)            error('c0 < 1'); end;
  if (cN > filewidth)    error('cN > width'); end;
  if (~isint(filewidth)) error('numlines file seems to be wrong(?)'); end;

  data    = [];
  count   = 0;
  offset  = bytesperelem*(c0-1);%		in bytes
  mywidth = cN-c0+1;%				number of elems 2b read
  lines   = rN-r0+1;%				number of lines in matrix
  if (complextype==true)
    mywidth=mywidth*2;%				correction for pix interleaved complex
    offset =offset*2;%				correction for pix interleaved complex
  end;
  for ii=r0-1:rN-1
    start   = ii*filewidth*bytesperelem+offset;
    status  = fseek(fid,start,'bof');%			beginning of file
    if (status ~= 0)
      disp(['r0 rN c0 cN: ',num2str(r0),' ',num2str(rN),...
			' ',num2str(c0),' ',num2str(cN)]);
      disp(['ii offset start: ',...
	     num2str(ii),' ',num2str(offset),' ',num2str(start)]);
      error(ferror(fid));
    end;
    [d cnt] = fread(fid,mywidth,bkformat);%		column vector
    count   = count+cnt;
    data    = [data;d];%				augment column vector
  end;
end;
fclose(fid);

if (complextype==true)
  % should be possible by something like, but for speed makes no big diff.
  %data = reshape(data,width,2*lines);%		transpose band interleaved if complex
  %data = complex(data(:,1:lines),data(:,lines+1:2*lines)).';
  data = complex(data(1:2:count),data(2:2:count));
  count=count/2;%					correction for complex types
end;

width = count/lines;%
data  = reshape(data,width,lines).';

%%% Export to type if requested
% data = int8(data) ...

%%% EOF


 function h = ir_str2func(string)
%function h = ir_str2func(string)
%|
%| wrapper around str2func() for octave / matlab compatability
%|
%| Background: matlab is phasing out inline
%| http://www.mathworks.com/help/matlab/ref/inline.html
%|
%| So given a string like 'x^2' the way to make it function is
%| str2func('@(x) x^2')
%|
%| Unfortunately, octave 3.8.2 does not support that syntax,
%| so this is the work around.

if nargin < 1, ir_usage, end
if streq(string, 'test') ir_str2func_test, return, end

if ir_is_octave
	h = eval(string);
else
	h = str2func(string);
end

% ir_str2func_test()
% test routine (that is longer than the actual function)
function ir_str2func_test
s = '@(x) x.^2';
f = ir_str2func(s);
g = @(x) x.^2;
jf_equal(f, g)
x = 1:5;
y = f(x);
jf_equal(y, x.^2)


function y2 = y_astronomical_to_common ( y )

%*****************************************************************************80
%
%% Y_ASTRONOMICAL_TO_COMMON converts an Astronomical year to a Common year.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 December 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, the astronomical year.
%
%    Output, integer Y2, the Common year.
%
  if ( y <= 0 )
    y2 = y - 1;
  else
    y2 = y;
  end

  return
end


function [ h, hmin, hmax ] = p12_stepsize ( option )

%*****************************************************************************80
%
%% P12_STEPSIZE returns step sizes for problem 12.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 September 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer OPTION, the option index.
%
%    Output, real H, HMIN, HMAX, suggested values for the
%    initial step, the minimum step, and the maximum step.
%
  h =     2.000;
  hmin =  0.001;
  hmax = 10.000;

  return
end


function test_suite = test_distancePointPolyline
%TESTDISTANCEPOINTEDGE  Test suite for function distancePointPolyline
%   output = test_distancePointPolyline(input)
%
%   Example
%   testDistancePointPolyline
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2009-04-22,    using Matlab 7.7.0.471 (R2008b)
% Copyright 2009 INRA - Cepia Software Platform.

test_suite = functiontests(localfunctions);

function testPointOnPolyline(testCase) %#ok<*DEFNU>
% test if the distance betwwen polyline and a point on polyline is 0

% create polyline
poly = [0 0;10 0;10 10;0 10];

p1 = [0 0];
d = distancePointPolyline(p1, poly);
testCase.assertEqual(0, d, 'AbsTol', .01);

p1 = [10 0];
d = distancePointPolyline(p1, poly);
testCase.assertEqual(0, d, 'AbsTol', .01);

p1 = [5 10];
d = distancePointPolyline(p1, poly);
testCase.assertEqual(0, d, 'AbsTol', .01);

p1 = [10 5];
d = distancePointPolyline(p1, poly);
testCase.assertEqual(0, d, 'AbsTol', .01);

function testPointNotOnPolyline(testCase)

% test various points

% create polyline
poly = [0 0;10 0;10 10;0 10];

p1 = [0 -10];
d = distancePointPolyline(p1, poly);
testCase.assertEqual(10, d, 'AbsTol', .01);

p1 = [20 0];
d = distancePointPolyline(p1, poly);
testCase.assertEqual(10, d, 'AbsTol', .01);

p1 = [0 5];
d = distancePointPolyline(p1, poly);
testCase.assertEqual(5, d, 'AbsTol', .01);

p1 = [5 5];
d = distancePointPolyline(p1, poly);
testCase.assertEqual(5, d, 'AbsTol', .01);

function testManyPoints(testCase)

% test several points in one call...

% create polyline
poly = [0 0;10 0;10 10;0 10];

pts = [0 -10;20 0;0 5; 5 5];
dist = distancePointPolyline(pts, poly);
exp = [10 10 5 5]';

testCase.assertEqual(exp, dist, 'AbsTol', .01);


function [out1,out2,out3] = UserInputFunction(x,y)
if nargin==0; x = 0;y = 0; end
%[-------------------------------------]%
% EDIT THE FUNCTION TO YOUR OWN CHOICE%
  G = x + y;
%[-------------------------------------]%
if nargout==2,
   out1 = x; out2 = y;  out3 = G;
else
   out1 = G;
end


function c8_i_test ( )

%*****************************************************************************80
%
%% C8_I_TEST tests C8_I.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    13 February 2015
%
%  Author:
%
%    John Burkardt
%
  seed = 123456678;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'C8_I_TEST\n' );
  fprintf ( 1, '  C8_I computes the imaginary unit I.\n' );
  fprintf ( 1, '\n' );
  c1 = c8_i ( );
  fprintf ( 1, '  C1 = C8_I ( ) = (%g,%g)\n', real ( c1 ), imag ( c1 ) );

  c2 = c1 * c1;
  fprintf ( 1, '  C2 = C1 * C1 = (%g,%g)\n', real ( c2 ), imag ( c2 ) );

  return
end


function title = p34_title ( )

%*****************************************************************************80
%
%% P34_TITLE returns a title for problem 34.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 January 2001
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string TITLE, a title for the problem.
%
  title = 'The Six-Hump Camel-Back Polynomial';

  return
end


function a = mag(a)
%MAG          Absolute value for non-intervals, same as abs (for completeness)
%
%  c = mag(a);
%
%Replaces abss. Thanks to Arnold for pointing to better name.
%

% written  01/04/05     S.M. Rump
% modified 04/06/05     S.M. Rump  rounding unchanged
%

  a = abs(a);


function calpak_test535 ( )

%*****************************************************************************80
%
%% CALPAK_TEST535 tests YEAR_IS_LEAP_GREEK.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2013
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CALPAK_TEST535\n' );
  fprintf ( 1, '  For the Greek calendar:\n' );
  fprintf ( 1, '  YEAR_IS_LEAP_GREEK reports leap years.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Year  Leap?\n' );
  fprintf ( 1, '\n' );

  for y = 1 : 10
    sy = y_to_s_greek ( y );
    fprintf ( 1, '  %10s  %d\n', sy, year_is_leap_greek ( y ) );
  end

  return
end


function y2 = y_astronomical_to_common ( y )

%*****************************************************************************80
%
%% Y_ASTRONOMICAL_TO_COMMON converts an Astronomical year to a Common year.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 April 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, the astronomical year.
%
%    Output, integer Y2, the Common year.
%
  if ( y <= 0 )
    y2 = y - 1;
  else
    y2 = y;
  end

  return
end


function exact = p19_exact ( )

%*****************************************************************************80
%
%% P19_EXACT returns the exact integral for problem 19.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 November 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real EXACT, the value of the integral.
%
  exact = - 1.0;

  return
end


function y=Afun1(x);
if x<1
      y=x+1;
else
      y=1+1/x;
end


function n = dim(A)
%DIM          Dimension of a square matrix
%
%    n = dim(A)
%

% written  05/21/09     S.M. Rump
%

  n = A.size(1);
  if ( length(A.size)~=2 ) | ( n ~= A.size(2) )
    error('function dim called with non-square matrix')
  end;


function i4_bit_hi1_test ( )

%*****************************************************************************80
%
%% I4_BIT_HI1_TEST tests I4_BIT_HI1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 April 2009
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'I4_BIT_HI1_TEST\n' );
  fprintf ( 1, '  I4_BIT_HI1 returns the location of the high 1 bit.\n' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '     I     I4_BIT_HI1(I)\n' );
  fprintf ( 1, '\n' );

  seed = 123456789;

  for test = 1 : 10

    [ i, seed ] = i4_uniform_ab ( 0, 100, seed );

    j = i4_bit_hi1 ( i );

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

  end

  return
end


function y=flip(x)
%   function y=flip(x)
%   reverses the order of the elements of a vector, first->last, etc.
%   ddj 02 08 26
n=length(x);
for i=1:n
  y(i)=x(n+1-i);
end


function fixed_num = p01_fixed_num ( )

%*****************************************************************************80
%
%% P01_FIXED_NUM returns the number of fixed points in problem 01.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Per-Olof Persson and Gilbert Strang,
%    A Simple Mesh Generator in MATLAB,
%    SIAM Review,
%    Volume 46, Number 2, June 2004, pages 329-345.
%
%  Parameters:
%
%    Output, integer FIXED_NUM, the number of fixed points.
%
  fixed_num = 0;

  return
end


function value = r4_sign ( x )

%*****************************************************************************80
%
%% R4_SIGN returns the sign of an R4.
%
%  Discussion:
%
%    The value is +1 if the number is positive or zero, and it is -1 otherwise.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 March 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X, the number whose sign is desired.
%
%    Output, real VALUE, the sign of X.
%
  if ( 0 <= x )
    value = +1.0;
  else
    value = -1.0;
  end

  return
end


function scale = p25_scale ( neqn )

%*****************************************************************************80
%
%% P25_SCALE returns scale factors for problem p25.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NEQN, the number of equations.
%
%    Output, real SCALE(NEQN), the scaling factors.
%
  scale(1:neqn,1) = [ 1.0; 1.0 ];

  return
end


function re=rev(x);
% REV
% REV(x) reverses the elements of x
d=size(x); li=d(1,1);
ind=li:-1:1;
re=x(ind,:);


function data_num = p06_data_num ( )

%*****************************************************************************80
%
%% P06_DATA_NUM returns the dimension of the data vector for problem 6.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 August 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer DATA_NUM, the dimension of the data vector.
%
  num_int = 5;

  data_num = 1 + num_int * ( num_int + 1 );

  return
end


function [map] = data2map(data)
%
%  Convert a data item (a cell or a vec) into a map by mapping values into their indices
%  Thang Luong @ 2013, 2015 <lmthang@stanford.edu>
%
  if isempty(data)
    map = containers.Map();
  else
    if iscell(data)
      map = containers.Map(data, 1:length(data));
    else
      map = containers.Map(num2cell(data), 1:length(data));
    end
  end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%  out.m           1993-12-28  %       FORMATED OUTPUT OF MATRICES
%%    (c)           M. Balda    %          updated on 2005-12-18
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%          updated on 2006-02-10
%
% The function out.m outputs its first argument to screen or a file in a
% default or required format. The argument can be either empty or a string,
% integer, real or complex numbers or matrices. The format can be either
% user defined or from a previous call of the function, or a default one.
%
% Prerequisity:
% ~~~~~~~~~~~~~
%   function inp.m from  http://www.mathworks.com/matlabcentral/
%
% Forms of calls:
% ~~~~~~~~~~~~~~
%
%   out;        %   Clear the format and close output file if any
%
%   out(arg);   %   Display arg in formats '%s or '%e' or '%d'
%               %   or any other used in the last call of out.m
%       arg   = an argument
%
%   out(arg,form);      %   Display arg in the format form
%       form  = required format of the output (see help to fprintf).
%               A format for complex numbers is generated internally using
%               format for real numbers,
%       fid   = file identifier - handle of the output file
%
%   out(arg,fid);       %   Append arg to the open file of fid handle
%
%   fid = out(arg,form,fname);  % Open file, get handle fid, and write arg
%       fname = name of output file
%       fid   = handle of the file if successfully opened,
%              -1 if not opened,
%               0 if closed.
%
%   out(arg,form,fid);  %   Append arg to fid file
%
% Examples:
% ~~~~~~~~
%  out(rand(2,3));              % display matrix in the '%15.6e' format
%  Z = rand(3,2)+i*rand(3,2);   % create complex matrix Z
%  h = out(Z,'','cmplxZ.dat');  % write Z in '%15.6e' format to the file
%  out('','%s\n',h);            % append new line into the file
%  out(Z,'%8.4f',h);            % append Z once more in '%8.4f' format
%  out;                         % close the file 'cmplxZ.dat'
%  lf = char(10);               % new line character
%  out(['This is a string' lf]);% display a string ending with new line
%  out(1:5,'%4i\n');            % display a column of integers
%  out(char('='*ones(1,50)),'%s\n');% display a line of 50 characters '='
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function fid = out(arg,form,fname)
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
persistent fid_ frm_

if nargin<1                     %   Close file & return
    fid = 0;
    if ~isempty(fid_) && fid_~=1
        fid  = fclose(fid_);
    end
    frm_ = [];
    return
end

%                               %   Format test & reconstruction
S = isempty(findstr('s',frm_));
if (ischar(arg) && S) || (isnumeric(arg) && ~S)
    frm_ = [];
end

%                               %   OUTPUT DESTINATION
fid_ = 1;                       %   screen
if nargin>2                     %   write in a file?
    if ischar(fname)             %   file name
        if exist(fname,'file')
            if strcmp(inp(['Overwrite ' fname '?'],'no'),'no')
                fid=-1;
                return          %   without overwriting
            end
        end
        fid_ = fopen(fname, 'w+');% open file
        fid  = fid_;
        if fid_<0, return, end
    else
        if isreal(fname)        %   file identifier
            fid_ = fname;
        end
    end
end

%                               %   OUTPUT FORMAT
if nargin>1
    if isempty(form)
        frm_ = [];
    elseif ischar(form)          %   format
        if isnumeric(arg)       %   for numeric arg
            if isempty(findstr(form,'-') + findstr(form,'+'))
                frmR_ = ['% ' form(2:end)]; %   real
                frmI_ = ['%+' form(2:end)]; %   imag
            else
                frmR_ = ['% ' form(3:end)]; %   real
                frmI_ = ['%+' form(3:end)]; %   imag
            end
            if ~isreal(arg)
                frm_ = [frmR_ frmI_ 'i  '];  %  complex
            else
                frm_ = frmR_;
            end
        else
            frm_ = form;        %   for string arg
        end
    else
        fid_ = form;            %   file identifier
    end
end

if isempty(frm_)
    if ischar(arg),        frm_ = '%s  ';
    elseif isinteger(arg), frm_ = '% d  ';
    elseif isreal(arg),    frm_ = '% e  ';
    else                   frm_ = '% e %+ei  ';
    end
end
%   disp({arg, frm_, fid_})

%                               %   OUTPUT arg
if ischar(arg)
    fprintf(fid_,frm_,arg);     %   text argument
else
    [m,n] = size(arg);
    if isreal(arg)              %   integer or real arg
        for k = 1:m
            for j = 1:n
                fprintf(fid_, frm_, arg(k,j));
            end
            fprintf(fid_,'\n');
        end
    else                        %   complex arg
        for k = 1:m
            Rc = real(arg(k,:));
            Ic = imag(arg(k,:));
            for j = 1:n
                fprintf(fid_, frm_, Rc(j), Ic(j));
            end
            fprintf(fid_,'\n');
        end
    end
end
fid = fid_;


function title = p07_title ( title )

%*****************************************************************************80
%
%% P07_TITLE returns the title of problem 7.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 May 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string TITLE, the title of the problem.
%
  title = 'F(X) = X**3, only linear Newton convergence.';

  return
end


function s=pval_to_star(p)
if p<0.001
    s='***';
elseif p<0.01
    s='**';
elseif p<0.05
    s='*';
else
    s='';
end
end


function haveNewerRelease = tapas_compare_versions(online_version,offline_version)
    %% Check if online_version is higher.
    %
    % Input
    %       online_version      -- Online version as string of numbers separated
    %                               by dots, i.e. '3.3.0'
    %       offline_version     -- Online version as string of numbers separated
    %                               by dots, i.e. '2.7.0.3'
    %
    % Output
    %       haveNewerRelease    -- true if version number of online_version is
    %                               higher than that of offline_version

    % muellmat@ethz.ch
    % copyright (C) 2020
    %

    haveNewerRelease = false; % If both releases are the same, return false
    online_numbers = str2double(strsplit(online_version,'.'));
    offline_numbers = str2double(strsplit(offline_version,'.'));
    % Check whether they have the same lenght (oterwise fill with zeros)
    n_online = numel(online_numbers);
    n_offline = numel(offline_numbers);
    if n_online > n_offline
        offline_numbers(n_online) = 0; % matlab fills rest with zeros
    elseif n_online < n_offline
        online_numbers(n_offline) = 0; % matlab fills rest with zeros
    end
    % Now that they have the same length, compare them number by number.
    %   Return at the first difference.
    for ind = 1:max(n_online,n_offline)
        if online_numbers(ind) > offline_numbers(ind)
            haveNewerRelease = true;
            return;
        elseif online_numbers(ind) < offline_numbers(ind)
            haveNewerRelease = false;
            return;
        end
    end

end