function [ a, b ] = p00_lim ( prob )

%*****************************************************************************80
%
%% P00_LIM returns the integration limits for any problem.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 November 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer PROB, the number of the desired test problem.
%
%    Output, real A, B, the limits of integration.
%
  if ( prob == 1 )
    [ a, b ] = p01_lim ( );
  elseif ( prob == 2 )
    [ a, b ] = p02_lim ( );
  elseif ( prob == 3 )
    [ a, b ] = p03_lim ( );
  elseif ( prob == 4 )
    [ a, b ] = p04_lim ( );
  elseif ( prob == 5 )
    [ a, b ] = p05_lim ( );
  elseif ( prob == 6 )
    [ a, b ] = p06_lim ( );
  elseif ( prob == 7 )
    [ a, b ] = p07_lim ( );
  elseif ( prob == 8 )
    [ a, b ] = p08_lim ( );
  elseif ( prob == 9 )
    [ a, b ] = p09_lim ( );
  elseif ( prob == 10 )
    [ a, b ] = p10_lim ( );
  elseif ( prob == 11 )
    [ a, b ] = p11_lim ( );
  elseif ( prob == 12 )
    [ a, b ] = p12_lim ( );
  elseif ( prob == 13 )
    [ a, b ] = p13_lim ( );
  elseif ( prob == 14 )
    [ a, b ] = p14_lim ( );
  elseif ( prob == 15 )
    [ a, b ] = p15_lim ( );
  elseif ( prob == 16 )
    [ a, b ] = p16_lim ( );
  elseif ( prob == 17 )
    [ a, b ] = p17_lim ( );
  elseif ( prob == 18 )
    [ a, b ] = p18_lim ( );
  elseif ( prob == 19 )
    [ a, b ] = p19_lim ( );
  elseif ( prob == 20 )
    [ a, b ] = p20_lim ( );
  elseif ( prob == 21 )
    [ a, b ] = p21_lim ( );
  elseif ( prob == 22 )
    [ a, b ] = p22_lim ( );
  elseif ( prob == 23 )
    [ a, b ] = p23_lim ( );
  elseif ( prob == 24 )
    [ a, b ] = p24_lim ( );
  elseif ( prob == 25 )
    [ a, b ] = p25_lim ( );
  elseif ( prob == 26 )
    [ a, b ] = p26_lim ( );
  elseif ( prob == 27 )
    [ a, b ] = p27_lim ( );
  elseif ( prob == 28 )
    [ a, b ] = p28_lim ( );
  elseif ( prob == 29 )
    [ a, b ] = p29_lim ( );
  elseif ( prob == 30 )
    [ a, b ] = p30_lim ( );
  elseif ( prob == 31 )
    [ a, b ] = p31_lim ( );
  elseif ( prob == 32 )
    [ a, b ] = p32_lim ( );
  elseif ( prob == 33 )
    [ a, b ] = p33_lim ( );
  elseif ( prob == 34 )
    [ a, b ] = p34_lim ( );
  elseif ( prob == 35 )
    [ a, b ] = p35_lim ( );
  elseif ( prob == 36 )
    [ a, b ] = p36_lim ( );
  elseif ( prob == 37 )
    [ a, b ] = p37_lim ( );
  elseif ( prob == 38 )
    [ a, b ] = p38_lim ( );
  elseif ( prob == 39 )
    [ a, b ] = p39_lim ( );
  elseif ( prob == 40 )
    [ a, b ] = p40_lim ( );
  elseif ( prob == 41 )
    [ a, b ] = p41_lim ( );
  elseif ( prob == 42 )
    [ a, b ] = p42_lim ( );
  elseif ( prob == 43 )
    [ a, b ] = p43_lim ( );
  elseif ( prob == 44 )
    [ a, b ] = p44_lim ( );
  elseif ( prob == 45 )
    [ a, b ] = p45_lim ( );
  elseif ( prob == 46 )
    [ a, b ] = p46_lim ( );
  elseif ( prob == 47 )
    [ a, b ] = p47_lim ( );
  elseif ( prob == 48 )
    [ a, b ] = p48_lim ( );
  elseif ( prob == 49 )
    [ a, b ] = p49_lim ( );
  elseif ( prob == 50 )
    [ a, b ] = p50_lim ( );
  elseif ( prob == 51 )
    [ a, b ] = p51_lim ( );
  elseif ( prob == 52 )
    [ a, b ] = p52_lim ( );
  elseif ( prob == 53 )
    [ a, b ] = p53_lim ( );
  elseif ( prob == 54 )
    [ a, b ] = p54_lim ( );
  elseif ( prob == 55 )
    [ a, b ] = p55_lim ( );
  elseif ( prob == 56 )
    [ a, b ] = p56_lim ( );
  elseif ( prob == 57 )
    [ a, b ] = p57_lim ( );
  elseif ( prob == 58 )
    [ a, b ] = p58_lim ( );
  elseif ( prob == 59 )
    [ a, b ] = p59_lim ( );
  elseif ( prob == 60 )
    [ a, b ] = p60_lim ( );
  elseif ( prob == 61 )
    [ a, b ] = p61_lim ( );
  elseif ( prob == 62 )
    [ a, b ] = p62_lim ( );
  elseif ( prob == 63 )
    [ a, b ] = p63_lim ( );
  elseif ( prob == 64 )
    [ a, b ] = p64_lim ( );
  elseif ( prob == 65 )
    [ a, b ] = p65_lim ( );
  elseif ( prob == 66 )
    [ a, b ] = p66_lim ( );
  elseif ( prob == 67 )
    [ a, b ] = p67_lim ( );
  elseif ( prob == 68 )
    [ a, b ] = p68_lim ( );
  elseif ( prob == 69 )
    [ a, b ] = p69_lim ( );
  elseif ( prob == 70 )
    [ a, b ] = p70_lim ( );
  elseif ( prob == 71 )
    [ a, b ] = p71_lim ( );
  elseif ( prob == 72 )
    [ a, b ] = p72_lim ( );
  elseif ( prob == 73 )
    [ a, b ] = p73_lim ( );
  elseif ( prob == 74 )
    [ a, b ] = p74_lim ( );
  elseif ( prob == 75 )
    [ a, b ] = p75_lim ( );
  elseif ( prob == 76 )
    [ a, b ] = p76_lim ( );
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'P00_LIM - Fatal error!\n' );
    fprintf ( 1, '  Illegal problem number = %d\n', prob );
    error ( 'P00_LIM - Fatal error!' );
  end

  return
end


function boundary_segment_num = p07_boundary_segment_num ( )

%*****************************************************************************80
%
%% P07_BOUNDARY_SEGMENT_NUM counts the boundary segments in problem 07.
%
%  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 = 1;

  return
end


function value = gpl_dimension ( filename )

%*****************************************************************************80
%
%% GPL_DIMENSION determines the "dimension" of the data in a GPL file.
%
%  Discussion:
%
%    A satisfactory GPL file contains only three kinds of records:
%    * comment lines begin with a "#" and are ignored;
%    * blank lines;
%    * lines with exactly N numeric values;
%
%    This function attempts to determine the value of N.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 May 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string FILENAME, the name of the file.
%
%    Output, integer VALUE, the "dimension" of the data.
%    -2, inconsistent data was found.
%    -1, no data was found at all.
%     0, only empty lines were read.
%     n, every nonempy line contains N values.
%
  file = fopen ( filename, 'rt' );

  d = -1;

  while ( 1 )

    s = fgetl ( file );

    if ( ~ ischar ( s ) )
      break
    end

    if ( length ( s ) < 1 )
      continue
    end

    if ( s(1) == '#' )
      continue;
    end

    d2 = s_word_count ( s );

    if ( d == -1 )
      d = d2;
    elseif ( d == d2 )

    elseif ( d == 0 )
      d = d2;
    else
      d = -2;
      break
    end

  end

  fclose ( file );

  value = d;

  return
end


function hhh=vline(x,in1,in2)
% function h=vline(x, linetype, label)
%
% Draws a vertical line on the current axes at the location specified by 'x'.  Optional arguments are
% 'linetype' (default is 'r:') and 'label', which applies a text label to the graph near the line.  The
% label appears in the same color as the line.
%
% The line is held on the current axes, and after plotting the line, the function returns the axes to
% its prior hold state.
%
% The HandleVisibility property of the line object is set to "off", so not only does it not appear on
% legends, but it is not findable by using findobj.  Specifying an output argument causes the function to
% return a handle to the line, so it can be manipulated or deleted.  Also, the HandleVisibility can be
% overridden by setting the root's ShowHiddenHandles property to on.
%
% h = vline(42,'g','The Answer')
%
% returns a handle to a green vertical line on the current axes at x=42, and creates a text object on
% the current axes, close to the line, which reads "The Answer".
%
% vline also supports vector inputs to draw multiple lines at once.  For example,
%
% vline([4 8 12],{'g','r','b'},{'l1','lab2','LABELC'})
%
% draws three lines with the appropriate labels and colors.
%
% By Brandon Kuczenski for Kensington Labs.
% brandon_kuczenski@kensingtonlabs.com
% 8 November 2001

if length(x)>1  % vector input
    for I=1:length(x)
        switch nargin
        case 1
            linetype='r:';
            label='';
        case 2
            if ~iscell(in1)
                in1={in1};
            end
            if I>length(in1)
                linetype=in1{end};
            else
                linetype=in1{I};
            end
            label='';
        case 3
            if ~iscell(in1)
                in1={in1};
            end
            if ~iscell(in2)
                in2={in2};
            end
            if I>length(in1)
                linetype=in1{end};
            else
                linetype=in1{I};
            end
            if I>length(in2)
                label=in2{end};
            else
                label=in2{I};
            end
        end
        h(I)=vline(x(I),linetype,label);
    end
else
    switch nargin
    case 1
        linetype='r:';
        label='';
    case 2
        linetype=in1;
        label='';
    case 3
        linetype=in1;
        label=in2;
    end

    g=ishold(gca);
    hold on

    y=get(gca,'ylim');
    h=plot([x x],y,linetype);
    if length(label)
        xx=get(gca,'xlim');
        xrange=xx(2)-xx(1);
        xunit=(x-xx(1))/xrange;
        if xunit<0.8
            text(x+0.01*xrange,y(1)+0.1*(y(2)-y(1)),label,'color',get(h,'color'))
        else
            text(x-.05*xrange,y(1)+0.1*(y(2)-y(1)),label,'color',get(h,'color'))
        end
    end

    if g==0
    hold off
    end
    set(h,'tag','vline','handlevisibility','off')
end % else

if nargout
    hhh=h;
end


function lobatto_polynomial_test ( )

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

  lobatto_polynomial_value_test ( );
  lobatto_polynomial_derivative_test ( );
  lobatto_polynomial_plot_test ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'LOBATTO_POLYNOMIAL_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function [ node_num, element_num, hole_num ] = example1_q4_mesh_size ( )

%*****************************************************************************80
%
%% EXAMPLE1_Q4_MESH_SIZE sets sizes for example #1 Q4 mesh.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 February 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer NODE_NUM, the number of nodes.
%
%    Output, integer ELEMENT_NUM, the number of elements.
%
%    Output, integer HOLE_NUM, the number of holes.
%
  element_num = 17;
  hole_num = 1;
  node_num = 28;

  return
end


function out = mkconstarray(class, value, size)
%MKCONSTARRAY creates a constant array of a specified numeric class.
%   A = MKCONSTARRAY(CLASS, VALUE, SIZE) creates a constant array
%   of value VALUE and of size SIZE.

%   Copyright 1993-2003 The MathWorks, Inc.
%   $Revision: 1.8.4.1 $  $Date: 2003/01/26 06:00:35 $

out = repmat(feval(class, value), size);


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

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

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

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

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

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

    inc = i2hi + 1 - i2lo;

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

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

    for j = j2lo : j2hi

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

    end

  end

  return
end


function dim_num = p03_dim_num ( )

%*****************************************************************************80
%
%% P03_DIM_NUM returns the spatial dimension for problem p03.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 August 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer DIM_NUM, the spatial dimension of the
%    dependent variables.
%
  dim_num = 2;

  return
end


function out = equal(A,dim)
% check all elements of A to be equal

if nargin == 1
  out = isempty(A) || all(A == A(1));
  return;
end

%make dim first dimension
A = shiftdim(A,dim-1);
A = reshape(A,size(A,1),[]);

B = repmat(A(1,:),size(A,1),1);

out = all(A == B);


function column_num = file_column_count ( input_file_name )

%*****************************************************************************80
%
%% FILE_COLUMN_COUNT counts the columns in the first line of a file.
%
%  Discussion:
%
%    The file is assumed to be a simple text file.
%
%    Most lines of the file are presumed to consist of COLUMN_NUM words,
%    separated by spaces.  There may also be some blank lines, and some
%    comment lines, which have a "#" in column 1.
%
%    The routine tries to find the first non-comment non-blank line and
%    counts the number of words in that line.
%
%    If all lines are blanks or comments, it goes back and tries to analyze
%    a comment line.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 February 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string INPUT_FILE_NAME, the name of the file.
%
%    Output, integer COLUMN_NUM, the number of columns in the file.
%
  FALSE = 0;
  TRUE = 1;
%
%  Open the file.
%
  input_unit = fopen ( input_file_name );

  if ( input_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'FILE_COLUMN_COUNT - Error!\n' );
    fprintf ( 1, '  Could not open the file "%s".\n', input_file_name );
    error ( 'FILE_COLUMN_COUNT - Error!' );
    column_num = -1;
    return;
  end
%
%  Read one line, but skip blank lines and comment lines.
%  Use FGETL so we drop the newline character!
%
  got_one = FALSE;

  while ( 1 )

    line = fgetl ( input_unit );

    if ( line == -1 )
      break;
    end

    if ( s_len_trim ( line ) == 0 )

    elseif ( line(1) == '#' )

    else
      got_one = TRUE;
      break;
    end

  end

  fclose ( input_unit );

  if ( got_one == FALSE )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'FILE_COLUMN_COUNT - Warning!\n' );
    fprintf ( 1, '  The file does not seem to contain any data.\n' );
    column_num = -1;
    return;
  end

  column_num = s_word_count ( line );

  return
end


%EXPORT_PLY Export geometry in PLY format.
%
%   EXPORT_PLY( FILE_NAME, GEOM ) Export of 3D CAD geometries in ASCII
%   Polygon File Format/Stanford Triangle Format. FILE_NAME is a
%   string which specifies the file name to process. GEOM is the
%   geometry to export.

% Copyright 2013-2022 Precise Simulation, Ltd.


function [no,el]=removeisolatednode(node,elem)
%
% [no,el]=removeisolatednode(node,elem)
%
% remove isolated nodes: nodes that are not included in any element
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
%
% input:
%     node: list of node coordinates
%     elem: list of elements of the mesh
%
% output:
%     no: node coordinates after removing the isolated nodes
%     el: element list of the resulting mesh
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

oid=1:size(node,1);       % old node index
idx=setdiff(oid,elem(:)); % indices to the isolated nodes
idx=sort(idx);
delta=zeros(size(oid));
delta(idx)=1;
delta=-cumsum(delta);     % calculate the new node index after removing the isolated nodes
oid=oid+delta;            % map to new index
el=oid(elem);             % element list in the new index
no=node;
no(idx,:)=[];             % remove the isolated nodes


function [ t_stop, y_stop ] = p09_stop ( neqn )

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

  t_stop = 20.0;
  y_stop = [ ...
    9.826950928005993e-01; ...
    2.198447081694832; ...
    9.129452507276399e-01 ];

  return
end


function x=SeamPlot(x,SeamVector)
% SEAMPLOT takes as input an image and the SeamVector array and produces
% an image with the seam line superimposed upon the input image, x, for
% display purposes.
%
% Author: Danny Luong
%         http://danluong.com
%
% Last updated: 12/20/07

value=1.5*max(x(:));
for i=1:size(SeamVector,1)
    x(i,SeamVector(i))=value;
end


function [ str2 ] = newstr( str, pos )
% Function to a new string by flipping a single bit
% By Kyriakos Tsourapas
% You may contact me through the Mathworks site
% University of Essex 2002

str2 = str;

% FLIP THE POSITION
if str2(pos) == 0
    str2(pos) = 1;
else
    str2(pos) = 0;
end


%APPLYCOLORMAP  Applies a GNU Octave/MATLAB equivalent colormap on a given image
%
%     dst = cv.applyColorMap(src, colormap)
%     dst = cv.applyColorMap(src, userColor)
%     dst = cv.applyColorMap(..., 'OptionName',optionValue, ...)
%
% ## Input
% * __src__ The source image, grayscale or color of type `uint8`.
% * __colormap__ The colormap to apply. A string, one of:
%   * __Autumn__ Shades of red and yellow color map.
%   * __Bone__ Gray-scale with a tinge of blue color map.
%   * __Jet__ Variant of HSV.
%   * __Winter__ Shades of blue and green color map.
%   * __Rainbow__ Red-orange-yellow-green-blue-violet color map.
%   * __Ocean__ Black to white with shades of blue color map.
%   * __Summer__ Shades of green and yellow colormap.
%   * __Spring__ Shades of magenta and yellow color map.
%   * __Cool__ Shades of cyan and magenta color map.
%   * __HSV__ Hue-saturation-value color map.
%   * __Pink__ Pastel shades of pink color map.
%   * __Hot__ Black-red-yellow-white color map.
%   * __Parula__ Blue-green-orange-yellow color map.
% * __userColor__ The colormap to apply of type `uint8` (1 or 3 channels) and
%   length 256.
%
% ## Output
% * __dst__ The result is the colormapped source image. Same row/column size
%   and same type as `src`.
%
% ## Options
% * __FlipChannels__ whether to flip the order of color channels in output
%   `dst`, from OpenCV's BGR to between MATLAB's RGB. default true
%
% The human perception isn't built for observing fine changes in grayscale
% images. Human eyes are more sensitive to observing changes between colors,
% so you often need to recolor your grayscale images to get a clue about them.
% OpenCV now comes with various colormaps to enhance the visualization in your
% computer vision application.
%
% The second variant of the function applies a user-defined colormap on the
% given image.
%
% ## Example
%
% In OpenCV you only need cv.applyColorMap to apply a colormap on a given
% image. The following sample code takes an image and applies a Jet colormap
% on it and shows the result:
%
%     % We need an input image. (can be grayscale or color)
%     img_in = im2uint8(mat2gray(peaks(500)));
%
%     % Apply the colormap
%     %img_color2 = im2uint8(ind2rgb(img_in, jet(256)));
%     img_color = cv.applyColorMap(img_in, 'Jet');
%
%     % Show the result
%     imshow(img_color)
%
% ## Example
%
%     cmaps = {'Autumn', 'Bone', 'Jet', 'Winter', 'Rainbow', 'Ocean', ...
%         'Summer', 'Spring', 'Cool', 'HSV', 'Pink', 'Hot', 'Parula'};
%     img = cell2mat(cellfun(@(cmap) ...
%         cv.applyColorMap(repmat(uint8(0:255), 20, 1), cmap), cmaps(:), ...
%         'UniformOutput',false));
%     image(img)
%     set(gca, 'YTick', 10:20:20*numel(cmaps), 'YTickLabel',cmaps)
%     title('Colormaps')
%
% See also: cv.LUT, ind2rgb, colormap, autumn, bone, jet, winter, summer,
%  spring, cool, hsv, pink, hot, parula
%


%kGenRecMat 'generates a matrix, counting peaks from left to right '
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros GenRecMat.pane file
%
% Parameters:
% Integer: sx 'Pattern steps X', default: 5: 'number of equally devided steps the pattern was shifted along X'
% Integer: sy 'Pattern steps Y', default: 1: 'number of equally devided steps the pattern was shifted along Y'
% Integer: nx 'Recon Orders X', default: 1: 'number of orders to be included (in + and - direction)'
% Integer: ny 'Recon Orders Y', default: 0: 'number of orders to be included (in + and - direction)'
% Toggle: diagscan 'Diagonal Scan', default: 0: 'For scans without the zero-order, this has to be active'
% Toggle: nozeroorder 'Zero Order Blocked', default: 0: 'If selected, the zero order is assumed to not be present. One full pattern movement corresponds now to two unit cells.'
% OutputFile: o 'Output', required: 'Resulting output data object'
%
% Example: o = kGenRecMat( {'sx',5;'sy',1;'nx',1;'ny',0;'diagscan',0;'nozeroorder',0;'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% GenRecMat - generates a matrix, counting peaks from left to right
%
%  DESCRIPTION
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1996-2003, Rainer Heintzmann,  All rights reserved.
%

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

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


function t_test_fcns(quiet)
%T_TEST_FCNS  Test T_OK and T_IS and manually check output of failed tests.

%   MP-Test
%   Copyright (c) 2015, 2022, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MP-Test.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://github.com/MATPOWER/mptest for more info.

if nargin < 1
    quiet = 0;
end

ntests = 5;
npass = 29;
nfail = 18;

g = [];
e = [];

tol = 12;
k = 0;
str = {'EXPECT FAIL'; 'EXPECT PASS'};
f = @(s) str{s+1};

t_begin(npass+nfail, quiet);

%% t_ok
k = k + 1; e(k) = 1;
t = sprintf('%s : t_ok(1, ...)', f(e(k)));
g(k) = t_ok(1, t);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_ok(0, ...)', f(e(k)));
g(k) = t_ok(0, t);

%% t_is
k = k + 1; e(k) = 1;
t = sprintf('%s : t_is([], [], ...)', f(e(k)));
expected = [];
got = [];
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_is(1, [], ...)', f(e(k)));
expected = [];
got = 1;
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 1;
t = sprintf('%s : t_is(3, 3, ...)', f(e(k)));
expected = 3;
got = 3;
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_is(1, 3, ...)', f(e(k)));
expected = 3;
got = 1;
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 1;
t = sprintf('%s : t_is([3 3; 3 3], 3, ...)', f(e(k)));
expected = 3;
got = [3 3; 3 3];
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_is([3 4; 3 3], 3, ...)', f(e(k)));
expected = 3;
got = [3 4; 3 3];
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 1;
t = sprintf('%s : t_is([3 3; 4 3], [3 3; 4 3], ...)', f(e(k)));
expected = [3 3; 4 3];
got = [3 3; 4 3];
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_is([3 4; 3 3], [3 3; 4 3], ...)', f(e(k)));
expected = [3 3; 4 3];
got = [3 4; 3 3];
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 1;
t = sprintf('%s : t_is(ones(2,4,3), ones(2,4,3), ...)', f(e(k)));
expected = ones(2,4,3);
got = ones(2,4,3);
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_is(ones(2,4), ones(2,4,3), ...)', f(e(k)));
expected = ones(2,4,3);
got = ones(2,4);
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_is(ones(2,4,3), <one-elem-different> > tol, ...)', f(e(k)));
expected = ones(2,4,3);
got = ones(2,4,3);
got(2,3,2) = 1.0005;
g(k) = t_is(got, expected, 4, t);

k = k + 1; e(k) = 1;
t = sprintf('%s : t_is(ones(2,4,3), <one-elem-different> < tol, ...)', f(e(k)));
expected = ones(2,4,3);
got = ones(2,4,3);
got(2,3,2) = 1.0005;
g(k) = t_is(got, expected, 3, t);

k = k + 1; e(k) = 1;
t = sprintf('%s : t_is(NaN, NaN, ...)', f(e(k)));
expected = NaN;
got = NaN;
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_is([], NaN, ...)', f(e(k)));
expected = NaN;
got = [];
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_is(NaN, [], ...)', f(e(k)));
expected = [];
got = NaN;
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_is(1, NaN, ...)', f(e(k)));
expected = NaN;
got = 1;
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_is(NaN, 3, ...)', f(e(k)));
expected = 3;
got = NaN;
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 1;
t = sprintf('%s : t_is(NaN(3,2), NaN, ...)', f(e(k)));
expected = NaN;
got = NaN(3,2);
g(k) = t_is(got, expected, tol, t);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_is(int32(0.6), 1.0, ...)', f(e(k)));
expected = 0.6;
got = int32(1.0);
g(k) = t_is(got, expected, tol, t);

%% t_str_match
k = k + 1; e(k) = 1;
t = sprintf('%s : t_str_match(got, expected, ...)', f(e(k)));
expected = 'hello t_str_match';
got = 'hello t_str_match';
g(k) = t_str_match(got, expected, t);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_str_match(got, expected, ...)', f(e(k)));
expected = 'hello t_str_match';
got = 'herro t_str_match';
g(k) = t_str_match(got, expected, t);

k = k + 1; e(k) = 1;
t = sprintf('%s : t_str_match(... reps[re])', f(e(k)));
expected = 'hello t_str_match';
got = 'herro t_str_match';
reps = {{'r{2}', 'll'}};
g(k) = t_str_match(got, expected, t, reps);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_str_match(... reps[re])', f(e(k)));
expected = 'hello t_str_match';
got = 'herro t_str_match';
reps = {{'r{2}', 'LL'}};
g(k) = t_str_match(got, expected, t, reps);

k = k + 1; e(k) = 1;
t = sprintf('%s : t_str_match(... reps[!re])', f(e(k)));
expected = 'hello t_str_match';
got = 'herro t_str_match';
reps = {{'rr', 'll', 0}};
g(k) = t_str_match(got, expected, t, reps);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_str_match(... reps[!re])', f(e(k)));
expected = 'hello t_str_match';
got = 'herro t_str_match';
reps = {{'r{2}', 'll', 0}};
g(k) = t_str_match(got, expected, t, reps);

k = k + 1; e(k) = 1;
t = sprintf('%s : t_str_match(... reps[both])', f(e(k)));
expected = 'hel4o t_str_match';
got = 'he56o t_str_match';
reps = {{'\d', 'l', 1, 1}};
g(k) = t_str_match(got, expected, t, reps);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_str_match(... reps[both])', f(e(k)));
expected = 'heL4o t_str_match';
got = 'he56o t_str_match';
reps = {{'\d', 'l', 1, 1}};
g(k) = t_str_match(got, expected, t, reps);

%% t_file_match
[twd, n, ext] = fileparts(which('t_test_fcns'));
exp_fname = fullfile(twd, 't_have_feature', 'rithmaticker.m');
num = fix(1e7*rand);
fname1 = sprintf('test-output-1-%d.txt', num);
fname2 = sprintf('test-output-2-%d.txt', num);
fname3 = sprintf('test-output-3-%d.txt', num);
ex = fileread(exp_fname);
if isempty(strfind(ex, char([13 10])))
    ex2 = strrep(ex, char(10), char([13 10]));
else
    ex2 = strrep(ex, char([13 10]), char(10));
end
ex3 = regexprep(ex2, '\d', 'N');

k = k + 1; e(k) = 1;
t = sprintf('%s : fileread', f(e(k)));
g(k) = t_str_match(ex(1:8), 'function', t);

%% write files
filewrite(fname1, ex);
filewrite(fname2, ex2);
filewrite(fname3, ex3);

k = k + 1; e(k) = 1;
t = sprintf('%s : filewrite 1', f(e(k)));
ok = exist(fname1, 'file') == 2 && strcmp(ex, fileread(fname1));
g(k) = t_ok(ok, t);

k = k + 1; e(k) = 1;
t = sprintf('%s : filewrite 2', f(e(k)));
ok = exist(fname2, 'file') == 2 && ~strcmp(ex, fileread(fname2));
g(k) = t_ok(ok, t);

k = k + 1; e(k) = 1;
t = sprintf('%s : filewrite 3', f(e(k)));
ok = exist(fname3, 'file') == 2 && ~strcmp(ex, fileread(fname3));
g(k) = t_ok(ok, t);

%% t_file_match
k = k + 1; e(k) = 1;
t = sprintf('%s : t_file_match 1', f(e(k)));
g(k) = t_file_match(fname1, exp_fname, t);
k = k + 1; e(k) = 1;
g(k) = t_ok(exist(fname1, 'file') == 2, [t ' : file not deleted']);

k = k + 1; e(k) = 1;
t = sprintf('%s : t_file_match 1 (del)', f(e(k)));
g(k) = t_file_match(fname1, exp_fname, t, {}, 1);
k = k + 1; e(k) = 1;
g(k) = t_ok(exist(fname1, 'file') == 0, [t ' : file deleted']);

k = k + 1; e(k) = 1;
t = sprintf('%s : t_file_match 2', f(e(k)));
g(k) = t_file_match(fname2, exp_fname, t);
k = k + 1; e(k) = 1;
g(k) = t_ok(exist(fname2, 'file') == 2, [t ' : file not deleted']);

k = k + 1; e(k) = 1;
t = sprintf('%s : t_file_match 2 (del)', f(e(k)));
g(k) = t_file_match(fname2, exp_fname, t, {}, 1);
k = k + 1; e(k) = 1;
g(k) = t_ok(exist(fname2, 'file') == 0, [t ' : file deleted']);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_file_match 3 (del)', f(e(k)));
g(k) = t_file_match(fname3, exp_fname, t, {}, 1);
k = k + 1; e(k) = 1;
g(k) = t_ok(exist(fname3, 'file') == 2, [t ' : file not deleted']);

k = k + 1; e(k) = 0;
t = sprintf('%s : t_file_match 3 (reps,del)', f(e(k)));
reps = {{'\d', 'N', 1}};
g(k) = t_file_match(fname3, exp_fname, t, reps);
k = k + 1; e(k) = 1;
g(k) = t_ok(exist(fname3, 'file') == 2, [t ' : file not deleted']);

k = k + 1; e(k) = 1;
t = sprintf('%s : t_file_match 3 (both,del)', f(e(k)));
reps = {{'[\dN]', 'M', 1, 1}};
g(k) = t_file_match(fname3, exp_fname, t, reps, 1);
k = k + 1; e(k) = 1;
g(k) = t_ok(exist(fname3, 'file') == 0, [t ' : file deleted']);

%%-----  reset tests, if this test passes, everything is as expected  -----
t_begin(ntests, quiet);

t = 'number of tests as expected';
t_is(length(g), npass+nfail, tol, t);
t_is(length(e), npass+nfail, tol, t);

t = 'verify test consistency';
t_is(sum( e), npass, tol, t);
t_is(sum(~e), nfail, tol, t);

t = 'passes and fails all as expected';
t_is(g, e, tol, t);

t_end;

function filewrite(fname, content)
[fid, msg] = fopen(fname, 'w');
if fid == -1
    error('%s\nt_test_fcns/filewrite: could not write file ''%s''', msg, fname);
end
fprintf(fid, '%s', content);
fclose(fid);


function n = p32_n ( )

%*****************************************************************************80
%
%% P32_N returns the number of variables for problem 32.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 January 2001
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer N.  If N is positive, N represents the
%    only legal value for N for this problem.  If N is
%    negative, the absolute value of N is the least legal
%    value of N, but other values are allowable.
%
  n = 4;

  return
end


function a2 = r8vec_copy ( n, a1 )

%*****************************************************************************80
%
%% R8VEC_COPY copies an R8VEC.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    31 October 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the length of the vectors.
%
%    Input, real A1(N), the vector to be copied.
%
%    Output, real A2(N), a copy of A1.
%
  a2(1:n) = a1(1:n);

  return
end


function h=myarrow()

    %  [handle]=myarrow
    %
    %  Draws an arrow  by clicking between two points (tail, head)
    %  on the current figure, and returns the arrow's handle.
    %  Uses ARROW.
    %
    %  Richard G. Cobb 3/96

    axis(axis)
    [x,y]=ginput(2);
    start=[x(1),y(1)];
    stop=[x(2),y(2)];

    h=arrow(start,stop);
    %eof


function fixed = p02_fixed_points ( m, fixed_num )

%*****************************************************************************80
%
%% P02_FIXED_POINTS returns the fixed points in problem 02.
%
%  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:
%
%    Input, integer M, the spatial dimension.
%
%    Input, integer FIXED_NUM, the number of fixed points.
%
%    Output, real FIXED(M,FIXED_NUM), the fixed points.
%
  fixed = [];

  return
end


function fixed_num = p09_fixed_num ( )

%*****************************************************************************80
%
%% P09_FIXED_NUM returns the number of fixed points in problem 09.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer FIXED_NUM, the number of fixed points.
%
  fixed_num = 16;

  return
end


function value = rhs_test01 ( x_num, x, t )

%*****************************************************************************80
%
%% RHS_TEST01 evaluates the right hand side for problem 1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 January 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer X_NUM, the number of nodes.
%
%    Input, real X(X_NUM,1), the node coordinates.
%
%    Input, real T, the current time.
%
%    Output, real VALUE(X_NUM,1), the source term.
%
  value(1:x_num,1) = 0.0;

  return
end


function ffmsh_2d_size_print ( title, v_num, e_num, t_num )

%*****************************************************************************80
%
%% FFMSH_2D_SIZE_PRINT prints the sizes of an FFMSH.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 December 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string TITLE, a title.
%
%    Input, integer V_NUM, the number of vertices.
%
%    Input, integer E_NUM, the number of boundary edges.
%
%    Input, integer T_NUM, the number of triangles.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '%s\n', title );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of vertices = %d\n', v_num );
  fprintf ( 1, '  Number of boundary edges = %d\n', e_num );
  fprintf ( 1, '  Number of triangles = %d\n', t_num );

  return
end


function value = rhs_test03 ( x_num, x, t )

%*****************************************************************************80
%
%% RHS_TEST03 evaluates the right hand side for problem 3.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 January 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer X_NUM, the number of nodes.
%
%    Input, real X(X_NUM,1), the node coordinates.
%
%    Input, real T, the current time.
%
%    Output, real VALUE(X_NUM,1), the source term.
%
  value(1:x_num,1) = 0.0;

  return
end


function value = year_length_months_republican ( y )

%*****************************************************************************80
%
%% YEAR_LENGTH_MONTHS_REPUBLICAN returns the number of months in a Republican 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 toolboxSfmCompile(doSba,gccVer)
% Compiles all the private routines
%
% This function can recompile all that you need for the toolbox to run.
% That includes:
%  - the SBA static library that is needed to build the ...
%  - ... SBA mex file
%  - 3 normal mex files
% By default, the toolbox comes with precompiled binaries for windows 32
% It is easy to compile on Linux and I am developing on Linux so it works
% for sure there.
%
% USAGE
%  toolboxCompile()
%
% INPUTS
%  doSba      - [false] if true, it will compile the dll projection files
%               for SBA and that requires matlab to be launched from the
%               visual c++ terminal on Windows
%  gccVer     - on Linux, specify your gcc version here (e.g. 4.2 if
%               gcc-4.2 is a supported compiler on Matlab), which can be
%               useful if matlab thinks your gcc is too old/new
%
% OUTPUTS
%
% EXAMPLE
%
% See also
%
% Vincent's Structure From Motion Toolbox      Version 3.1
% Copyright (C) 2008-2011 Vincent Rabaud.  [vrabaud-at-cs.ucsd.edu]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the GPL [see external/gpl.txt]

if nargin==0; doSba=false; end
if nargin<=1; gccVer=num2str(4.2); else gccVer=num2str(gccVer); end

if strcmp(computer,'GLNX86') || strcmp(computer,'GLNXA64')
  gcc_extra = [ 'CXX=g++-' gccVer ' CC=g++-' gccVer ' LD=g++-' gccVer ];
end

disp('Compiling.......................................');
disp('sba');
savepwd=pwd; cd(fileparts(mfilename('fullpath'))); cd('../');

dir_external = [ pwd '/external/' ];
dir_sba = [ dir_external 'sba/'];

% build the SBA mex file
cd(dir_sba);
% delete previous object files
fileList = {'sba_levmar.o', 'sba_levmar_wrap.o', 'sba_lapack.o', ...
  'sba_crsm.o', 'sba_chkjac.o', 'libsba.a', 'sba.lib'};
for i=1:length(fileList)
  if exist([dir_sba, '/', fileList{i}], 'file'), delete(fileList{i}); end
end

sba_files = [ 'sba.c ../sba_chkjac.c ../sba_levmar_wrap.c ../sba_levmar.c ' ...
  '../sba_lapack.c ../sba_crsm.c' ];

cd matlab
switch computer
  case {'PCWIN','PCWIN64'},
    ext = mexext;
    ext = ext(5:6);
    library_flags = [ '-D_WIN32 -I' dir_sba ' -L' dir_sba ...
      ' -L' dir_external 'blasLapack/win' ext ' -output sba.' mexext ' '];
    % Matlab on Windows 32/64
    if strcmp(computer, 'PCWIN')
      eval([ 'mex LINKFLAGS="$LINKFLAGS /NODEFAULTLIB:libcmt.lib" ' ...
        library_flags '-lclapack -lblas -llibF77 -llibI77 ' sba_files ]);
    else
      eval([ 'mex LINKFLAGS="$LINKFLAGS /NODEFAULTLIB:libcmt.lib" ' ...
        library_flags '-lclapack_nowrap -lf2c -lBLAS_nowrap ' sba_files ]);
    end
  case {'GLNX86'},
    % Matlab on Linux
    eval([ 'mex ' gcc_extra ' -I../ -O -ldl ' sba_files ...
      ' /usr/lib/liblapack.a /usr/lib/atlas/libblas.a ' ...
      '/usr/lib/libgfortran.so.3' ]);
  case {'GLNXA64'},
    % Matlab on Linux 64
    cd ../
    system('make cleanall');
    system('make libsba.a');
    cd matlab
    eval([ 'mex -lgfortran ' gcc_extra ' -I../ -O -ldl sba.c ' ...
      '../libsba.a /usr/lib/liblapack_pic.a ' ...
      '../../blasLapack/linux64/libf77blas.a ' ...
      '../../blasLapack/linux64/libatlas.a '
      ]);
  case {'i686-pc-linux-gnu', 'i686-unknown-linux-gnu', ...
      'x86_64-pc-linux-gnu', 'x86_64-unknown-linux-gnu'},
    % Octave on Linux
    mkoctfile --mex ./sba.c ../sba_chkjac.c ../sba_levmar_wrap.c ../sba_levmar.c ...
    ../sba_lapack.c ../sba_crsm.c -I../
end
cd ../../..

cd sfm/private/sba
disp('sba projection routines');
switch computer
  case {'PCWIN'},
    if doSba
      % Matlab on Windows 32
      system('cl /nologo /O2 sbaProjection.c /link /dll /out:sbaProjection32.dll');
    end
  case {'PCWIN64'},
    if doSba
      % Matlab on Windows 64
      cc = mex.getCompilerConfigurations('C');
      system([ '"' cc.Location '\VC\bin\amd64\cl.exe" /nologo /O2 ' ...
        '/GS- sbaProjection.c /link /dll /NOENTRY ' ...
        '/out:sbaProjection64.dll']);
    end
  case {'GLNX86','GLNXA64','i686-pc-linux-gnu', 'i686-unknown-linux-gnu', ...
      'x86_64-pc-linux-gnu', 'x86_64-unknown-linux-gnu'},
    % Matlab and Octave on Linux
    system('gcc -Wall -fPIC -O3 -shared -o sbaProjection.so sbaProjection.c');
end
cd ../../..

% compile the remaining mex files
rd=fileparts(mfilename('fullpath')); rd=rd(1:end-9);

% general compile options (can make architecture specific)
optsAfter={};
switch computer
  case {'PCWIN','PCWIN64'},
    if strcmp(computer, 'PCWIN')
      win_folder = 'win32';
    else
      win_folder = 'win64';
    end
    % Matlab on Windows
    lapacklib = fullfile(matlabroot, 'extern', 'lib', win_folder, ...
      'microsoft', 'libmwlapack.lib');
    blaslib = fullfile(matlabroot, 'extern', 'lib', win_folder, ...
      'microsoft', 'libmwblas.lib');
    opts={'-output'};
    optsAfter = {lapacklib, blaslib};
  case {'GLNX86', 'GLNXA64'},
    % Matlab on Linux
    opts = { ['CXX=g++-' gccVer] ['CC=g++-' gccVer] ['LD=g++-' ...
      gccVer] '-largeArrayDims' '-l' 'mwlapack' '-l' 'mwblas' '-output'};
  case {'i686-pc-linux-gnu', 'i686-unknown-linux-gnu', ...
      'x86_64-pc-linux-gnu', 'x86_64-unknown-linux-gnu'},
    % Octave on Linux
    opts = {'-o'};
end

% general compile options
fs={'computeCsfmInfimumMex','refineExteriorOrientationMex', ...
  'computeH'};%, ...
%  'msfmRotationDerivativeMex'};
ds={'nrsfm/private/', 'sfm/private/', 'external/em-sfm/', ...
  'msfm/private/'};
for i=1:length(fs)
  disp(fs{i});
  mex(opts{:},[rd '/' ds{i} '/' fs{i} '.' mexext], ...
    [rd '/' ds{i} '/' fs{i} '.c'], optsAfter{:});
end

cd(savepwd); disp('..................................Done Compiling');

end


function [njm] = tapas_ti_zeromat(jm)
%% Zeros all but the first entry in each column of jm.
%
% Input
%   jm      -- Matrix.
%
% Output
%   njm     -- Matrix.
%

% aponteeduardo@gmail.com
% copyright (C) 2015
%

njm = zeros(size(jm));

j = 0;
i = 0;

while j < size(jm, 2)
    j = j + 1;
    i = 0;
    while i < size(jm, 1)
        i = i + 1;
        if jm(i, j);
            njm(i, j) = 1;
            break
        end
    end
end

end


function dim_num = p02_dim_num ( )

%*****************************************************************************80
%
%% P02_DIM_NUM returns the spatial dimension for problem p02.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 August 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer DIM_NUM, the spatial dimension of the
%    dependent variables.
%
  dim_num = 2;

  return
end


function neqn = p32_neqn ( )

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

  return
end


function xy_io_test01 ( )

%*****************************************************************************80
%
%% TEST01 tests XY_EXAMPLE, XY_WRITE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 January 2009
%
%  Author:
%
%    John Burkardt
%
  point_num = 300;
  filename = 'xy_io_test01.xy';

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST01\n' );
  fprintf ( 1, '  XY_EXAMPLE sets up sample XY data.\n' );
  fprintf ( 1, '  XY_WRITE writes an XY file.\n' );

  xy = xy_example ( point_num );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  XY_EXAMPLE has created the data.\n' );

  xy_write ( filename, point_num, xy );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  XY_WRITE wrote the header and data for %s\n', filename );
  fprintf ( 1, '  Number of points = %d\n', point_num );

  return
end


function [tri, x, map] = tri_squeeze(tri, x)
% TRI_SQUEEZE  Remove disconnected vertices from triangular mesh
%
% [TRI2, X2, I] = tri_squeeze(TRI, X)
%
%   TRI is a 3-column matrix. Each row contains the 3 nodes that form one
%   triangular facet in the mesh.
%
%   X is a 3-column matrix. X(i, :) contains the xyz-coordinates of the
%   i-th node in the mesh.
%
%   Assuming that TRI, X represents a triangular mesh where some of the
%   vertices in X are not part of any triangle in TRI, this function
%   returns TRI2, X2, that represent the same mesh, but with the
%   disconnected vertices removed.
%
%   I is the mapping of preserved vertices such that X2 = X(I), given as a
%   list of indices.

% Author: Ramon Casero <rcasero@gmail.com>
% Copyright © 2012-2014 University of Oxford
% Version: 0.2.0
%
% University of Oxford means the Chancellor, Masters and Scholars of
% the University of Oxford, having an administrative office at
% Wellington Square, Oxford OX1 2JD, UK.
%
% This file is part of Gerardus.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details. The offer of this
% program under the terms of the License is subject to the License
% being interpreted in accordance with English Law and subject to any
% action against the University of Oxford being under the jurisdiction
% of the English Courts.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see
% <http://www.gnu.org/licenses/>.

% check arguments
narginchk(2, 2);
nargoutchk(0, 3);

% number of vertices
N = size(x, 1);

% list of all vertices that are part of at least a triangle
idx = unique(tri(:));

% vector that will do the mapping
map = zeros(N, 1);
map(idx) = (1:length(idx))';

% rename vertices
tri = map(tri);

% delete disconnected vertices
x(~map, :) = [];

if (nargout > 2)
    % format the mapping of preserved vertices as indices instead of a
    % boolean vector
    map = find(map);
end


function c8_print_test ( )

%*****************************************************************************80
%
%% C8_PRINT_TEST tests C8_PRINT.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    13 February 2015
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'C8_PRINT_TEST\n' );
  fprintf ( 1, '  C8_PRINT prints a C8.\n' );
  fprintf ( 1, '\n' );

  c1 = 0.0 + 0.0 * i;
  c2 = 1.0 + 0.0 * i;
  c3 = 3.141592653589793 + 0.0 * i;
  c4 =  0.0 + 1.0 * i;
  c5 = 1.0 + 2.0 * i;
  c6 = -12.34 + 56.78 * i;
  c7 = 0.001 + 0.000002 * i;
  c8 = 3.0E+08 - 4.5E+09 * i;

  c8_print ( c1, '  Zero:' );
  c8_print ( c2, '  One:' );
  c8_print ( c3, '  Pi:' );
  c8_print ( c4, '  i:' );
  c8_print ( c5, '  1+2i:' );
  c8_print ( c6, ' -12.34 + 56.78i:' );
  c8_print ( c7, '  1E-3 + 2E-6i' );
  c8_print ( c8, '  3E8 - 4.5E9i:' );

  return
end


function problem_num = p00_problem_num ( )

%*****************************************************************************80
%
%% P00_PROBLEM_NUM returns the number of problems available.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 January 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%   Output, integer PROBLEM_NUM, the number of problems available.
%
  problem_num = 12;

  return
end


function twod_to_vtk_test ( )

%*****************************************************************************80
%
%% TWOD_TO_VTK_TEST tests the TWOD_TO_VTK library.
%
%  Discussion:
%
%    The data represents a flow solution in a 10 by 3 channel.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 December 2010
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( '\n' );
  fprintf ( 1, 'TWOD_TO_VTK_TEST:\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the TWOD_TO_VTK library.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Read in TWOD finite element data.\n' );
  fprintf ( 1, '  Write it out as a legacy VTK file.\n' );
%
%  Load the data from text files.
%
  nodes = load ( 'channel_nodes.txt' );
  elements = load ( 'channel_elements.txt' );
  uvp = load ( 'channel_values.txt' );

  output_filename = 'channel.vtk';

  title = 'UVP for 10x3 2D channel problem';
%
%  Have the data written to a file.
%
  twod_to_vtk ( nodes, elements, uvp, output_filename, title );
%
%  Terminate.
%
  fprintf ( '\n' );
  fprintf ( 1, 'TWOD_TO_VTK_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( '\n' );
  timestamp ( );

  return
end


function r83col_print_part_test ( )

%*****************************************************************************80
%
%% R83COL_PRINT_PART_TEST tests R83COL_PRINT_PART.
%
%  Discussion:
%
%    An R82COL is an (N,3) 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; ...
    21.0,  22.0,  23.0; ...
    31.0,  32.0,  33.0; ...
    41.0,  42.0,  43.0; ...
    51.0,  52.0,  53.0; ...
    61.0,  62.0,  63.0; ...
    71.0,  72.0,  73.0; ...
    81.0,  82.0,  83.0; ...
    91.0,  92.0,  93.0; ...
   101.0, 102.0, 103.0 ];

  fprintf ( 1, '\n' );
  fprintf ( 1, 'R83COL_PRINT_PART_TEST\n' );
  fprintf ( 1, '  R83COL_PRINT_PART prints part of an R83COL.\n' );

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

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

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

  return
end


function scale = p26_scale ( neqn )

%*****************************************************************************80
%
%% P26_SCALE returns scale factors for problem p26.
%
%  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 neqn = p16_neqn ( )

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

  return
end


function scale = p15_scale ( neqn )

%*****************************************************************************80
%
%% P15_SCALE returns scale factors for problem p15.
%
%  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;

  return
end


function neqn = p24_neqn ( )

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

  return
end


% ----------------------------------------------------------------------- %
% Function table2latex(T, filename) converts a given MATLAB(R) table into %
% a plain .tex file with LaTeX formatting.                                %
%                                                                         %
%   Input parameters:                                                     %
%       - T:        MATLAB(R) table. The table should contain only the    %
%                   following data types: numeric, boolean, char or string.
%                   Avoid including structs or cells.                     %
%       - filename: (Optional) Output path, including the name of the file.
%                   If not specified, the table will be stored in a       %
%                   './table.tex' file.                                   %
% ----------------------------------------------------------------------- %
%   Example of use:                                                       %
%       LastName = {'Sanchez';'Johnson';'Li';'Diaz';'Brown'};             %
%       Age = [38;43;38;40;49];                                           %
%       Smoker = logical([1;0;1;0;1]);                                    %
%       Height = [71;69;64;67;64];                                        %
%       Weight = [176;163;131;133;119];                                   %
%       T = table(Age,Smoker,Height,Weight);                              %
%       T.Properties.RowNames = LastName;                                 %
%       table2latex(T);                                                   %
% ----------------------------------------------------------------------- %
%   Version: 1.1                                                          %
%   Author:  Victor Martinez Cagigal                                      %
%   Date:    09/10/2018                                                   %
%   E-mail:  vicmarcag (at) gmail (dot) com                               %
% ----------------------------------------------------------------------- %
function table2latex(T, filename)

    % Error detection and default parameters
    if nargin < 2
        filename = 'table.tex';
        fprintf('Output path is not defined. The table will be written in %s.\n', filename);
    elseif ~ischar(filename)
        error('The output file name must be a string.');
    else
        if ~strcmp(filename(end-3:end), '.tex')
            filename = [filename '.tex'];
        end
    end
    if nargin < 1, error('Not enough parameters.'); end
    if ~istable(T), error('Input must be a table.'); end

    % Parameters
    n_col = size(T,2);
    col_spec = [];
    for c = 1:n_col, col_spec = [col_spec 'l']; end
    col_names = strjoin(T.Properties.VariableNames, ' & ');
    row_names = T.Properties.RowNames;
    if ~isempty(row_names)
        col_spec = ['l' col_spec];
        col_names = ['& ' col_names];
    end

    % Writing header
    fileID = fopen(filename, 'w');
    fprintf(fileID, '\\begin{tabular}{%s}\n', col_spec);
    fprintf(fileID, '%s \\\\ \n', col_names);
    fprintf(fileID, '\\hline \n');

    % Writing the data
    try
        for row = 1:size(T,1)
            temp{1,n_col} = [];
            for col = 1:n_col
                value = T{row,col};
                if isstruct(value), error('Table must not contain structs.'); end
                while iscell(value), value = value{1,1}; end
                if isnumeric(value)
                    if isinf(value), value = '$\infty$'; end
                end
                temp{1,col} = num2str(value);
            end
            if ~isempty(row_names)
                temp = [row_names{row}, temp];
            end
            fprintf(fileID, '%s \\\\ \n', strjoin(temp, ' & '));
            clear temp;
        end
    catch ME
        error('Unknown error. Make sure that table only contains chars, strings or numeric values.');
    end

    % Closing the file
    fprintf(fileID, '\\hline \n');
    fprintf(fileID, '\\end{tabular}');
    fclose(fileID);
end


%% Import data from text file.
% Script for importing data from the following text file:
%
%    C:\ArizCU12.5m.dat
%
% To extend the code to different selected data or a different text file,
% generate a function instead of a script.

% Auto-generated by MATLAB on 2013/01/03 09:36:00
% David Willingham February 2013
% Copyright 2013 The MathWorks, Inc
%% Initialize variables.
filename = 'ArizCU12.5m.dat';
delimiter = '\t';
startRow = 7;

%% Format string for each line of text:
%   column1: double (%f)
%	column2: double (%f)
%   column3: double (%f)
%	column4: double (%f)
% For more information, see the TEXTSCAN documentation.
formatSpec = '%f%f%f%f%[^\n\r]';

%% Open the text file.
fileID = fopen(filename,'r');

%% Read columns of data according to format string.
% This call is based on the structure of the file used to generate this
% code. If an error occurs for a different file, try regenerating the code
% from the Import Tool.
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'HeaderLines' ,startRow-1, 'ReturnOnError', false);

%% Close the text file.
fclose(fileID);

%% Post processing for unimportable data.
% No unimportable data rules were applied during the import, so no post
% processing code is included. To generate code which works for
% unimportable data, select unimportable cells in a file and regenerate the
% script.

%% Allocate imported array to column variable names
x = dataArray{:, 1};
y = dataArray{:, 2};
z = dataArray{:, 3};
c = dataArray{:, 4};

%% Clear temporary variables
clearvars filename delimiter startRow formatSpec fileID dataArray ans;


function value = rhs_test02 ( x_num, x, t )

%*****************************************************************************80
%
%% RHS_TEST02 evaluates the right hand side for problem 2.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 January 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer X_NUM, the number of nodes.
%
%    Input, real X(X_NUM,1), the node coordinates.
%
%    Input, real T, the current time.
%
%    Output, real VALUE(X_NUM,1), the source term.
%
  value(1:x_num,1) = 0.0;

  return
end


function title = p07_title ( )

%*****************************************************************************80
%
%% P07_TITLE returns a title for problem 7.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 February 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string TITLE, a title for the problem.
%
  title = 'f(x) = Langerman2 function';

  return
end


function hydro = combineBEM(hydro)
% Combines multiple BEM outputs into one hydrodynamic ‘system.’ This function
% requires that all BEM outputs have the same water depth, wave frequencies,
% and wave headings. This function would be implemented following multiple
% readWAMIT, readNEMOH, readCAPYTAINE, or readAQWA and before radiationIRF,
% radiationIRFSS, excitationIRF, writeBEMIOH5, or plotBEMIO function calls.
%
% See ``WEC-Sim\examples\BEMIO\NEMOH`` for examples of usage.
%
% Parameters
% ----------
%     hydro : [1 x n] struct
%         Structures of hydro data that will be combined into a single
%         structure
%
% Returns
% -------
%     hydro : [1 x 1] struct
%         Combined structure.

p = waitbar(0,'Combining multiple BEM results...');  % Progress bar

[m,n] = size(hydro);
tol = 1e-2;
if n>1
    for i = 2:n
        if max(abs(hydro(i).h-hydro(i-1).h)) > tol
            error('Error: Inconsistent water depth');
        elseif (size(hydro(i).theta) ~= size(hydro(i-1).theta)) | ...
                (max(abs(sort(hydro(i).theta)-sort(hydro(i-1).theta))) > tol)
            error('Error: Inconsistent wave headings');
        elseif (size(hydro(i).T) ~= size(hydro(i-1).T)) | ...
                (max(abs(sort(hydro(i).T)-sort(hydro(i-1).T))) > tol)
            error('Error: Inconsistent wave frequencies');
        end
    end

    n = n+1;
    hydro(n).theta = hydro(1).theta;
    hydro(n).body = [];
    hydro(n).Khs = [];
    hydro(n).cb = [];
    hydro(n).cg = [];
    hydro(n).code = [];
    hydro(n).dof = [];
    hydro(n).ex_im = [];
    hydro(n).ex_ma = [];
    hydro(n).ex_ph = [];
    hydro(n).ex_re = [];
    hydro(n).fk_im = [];
    hydro(n).fk_ma = [];
    hydro(n).fk_ph = [];
    hydro(n).fk_re = [];
    hydro(n).sc_im = [];
    hydro(n).sc_ma = [];
    hydro(n).sc_ph = [];
    hydro(n).sc_re = [];
    hydro(n).file = [];
    hydro(n).g = 9.807;
    hydro(n).h = hydro(1).h;
    hydro(n).Nb = 0;
    hydro(n).Nf = hydro(1).Nf;
    hydro(n).Nh = hydro(1).Nh;
    hydro(n).rho = 1000;
    hydro(n).T = hydro(1).T;
    hydro(n).Vo = [];
    hydro(n).w = hydro(1).w;
    for i = 1:(n-1)
        hydro(n).body = [hydro(n).body, hydro(i).body];
        hydro(n).Khs = cat(3, hydro(n).Khs, hydro(i).Khs);
        hydro(n).cb = [hydro(n).cb, hydro(i).cb];
        hydro(n).cg = [hydro(n).cg, hydro(i).cg];
        hydro(n).code = [hydro(n).code, hydro(i).code];
        hydro(n).dof = [hydro(n).dof, hydro(i).dof];
        hydro(n).ex_im = cat(1, hydro(n).ex_im, hydro(i).ex_im);
        hydro(n).ex_ma = cat(1, hydro(n).ex_ma, hydro(i).ex_ma);
        hydro(n).ex_ph = cat(1, hydro(n).ex_ph, hydro(i).ex_ph);
        hydro(n).ex_re = cat(1, hydro(n).ex_re, hydro(i).ex_re);
        hydro(n).fk_im = cat(1, hydro(n).fk_im, hydro(i).fk_im);
        hydro(n).fk_ma = cat(1, hydro(n).fk_ma, hydro(i).fk_ma);
        hydro(n).fk_ph = cat(1, hydro(n).fk_ph, hydro(i).fk_ph);
        hydro(n).fk_re = cat(1, hydro(n).fk_re, hydro(i).fk_re);
        hydro(n).sc_im = cat(1, hydro(n).sc_im, hydro(i).sc_im);
        hydro(n).sc_ma = cat(1, hydro(n).sc_ma, hydro(i).sc_ma);
        hydro(n).sc_ph = cat(1, hydro(n).sc_ph, hydro(i).sc_ph);
        hydro(n).sc_re = cat(1, hydro(n).sc_re, hydro(i).sc_re);
        hydro(n).file = [hydro(n).file, hydro(i).file];
        hydro(n).Nb = hydro(n).Nb + hydro(i).Nb;
        hydro(n).Vo = [hydro(n).Vo, hydro(i).Vo];
    end
    hydro(n).Ainf = zeros(sum(hydro(n).dof),sum(hydro(n).dof));
    hydro(n).A = zeros(sum(hydro(n).dof),sum(hydro(n).dof),hydro(n).Nf);
    hydro(n).B = zeros(sum(hydro(n).dof),sum(hydro(n).dof),hydro(n).Nf);
    if isfield(hydro,'gbm')==1
        hydro(n).gbm = zeros(sum(hydro(n).dof),sum(hydro(n).dof),4);
    end
    k = 0;
    for i = 1:(n-1)
        j = sum(hydro(i).dof);
        hydro(n).Ainf((k+1):(k+j),(k+1):(k+j)) = hydro(i).Ainf;
        hydro(n).A((k+1):(k+j),(k+1):(k+j),:) = hydro(i).A;
        hydro(n).B((k+1):(k+j),(k+1):(k+j),:) = hydro(i).B;
        if isfield(hydro,'gbm')==1
            hydro(n).gbm((k+1):(k+j),(k+1):(k+j),:) = hydro(i).gbm;
        end
        k = k + j;
    end

    hydro(1) = hydro(n);
    hydro(2:n) = [];

end
close(p);
end


function table_io_test01 ( )

%*****************************************************************************80
%
%% TABLE_IO_TEST01 tests R8MAT_WRITE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 February 2010
%
%  Author:
%
%    John Burkardt
%
  n = 20;
  m = 5;
  output_filename = 'r8mat_05_00020.txt';

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST01\n' );
  fprintf ( 1, '  R8MAT_WRITE writes an R8MAT file.\n' );

  table = r8mat_indicator ( m, n );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Spatial dimension M = %d\n', m );
  fprintf ( 1, '  Number of points N  = %d\n', n );

  r8mat_print_some ( m, n, table, 1, 1, 5, 5, ...
    '  5x5 portion of the data written to file:' );

  r8mat_transpose_print_some ( m, n, table, 1, 1, 5, 5, ...
    '  5x5 portion of the TRANSPOSED data:' );

  r8mat_write ( output_filename, m, n, table );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Wrote the file "%s".\n', output_filename );

  return
end


function conv_nbrhood=cosmo_convert_neighborhood(nbrhood, output_type)
% Converts between cell, matrix and struct representations of neighborhoods
%
% conv_nbrhood=cosmo_convert_neighborhood(nbrhood[, output_type])
%
% Inputs:
%     nbrhood               Either a cell, struct, or matrix with
%                           neighborhood information:
%                           - cell:    Nx1 with nbrhood{k} the indices of
%                                      the k-th neighborhood
%                           - struct:  with field .neighbors, which must
%                                      be a cell
%                           - matrix:  MxN with nbrhood(:,k) the indices of
%                                      the k-th neighborhood (non-positive
%                                      values indicating no index), with M
%                                      the maximum number of features in a
%                                      single neighborhood
%     output_type           Optional, one of 'cell', 'matrix', or
%                           'struct'.
%                           If empty or omitted, then output_type is set to
%                           'matrix', unless nbrhood is a matrix, in
%                           which case it is set to 'cell'.
% Output:
%     conv_nbrhood          Neighborhood information converted to cell,
%                           struct, or matrix (see above)
%
% Example:
%     ds=cosmo_synthetic_dataset();
%     nbrhood=cosmo_spherical_neighborhood(ds,'radius',1,'progress',false);
%     % show the neighbor indices
%     cosmo_disp(nbrhood.neighbors)
%     %|| { [ 1         4         2 ]
%     %||   [ 2         1         5         3 ]
%     %||   [ 3         2         6 ]
%     %||   [ 4         1         5 ]
%     %||   [ 5         4         2         6 ]
%     %||   [ 6         5         3 ]           }
%     %
%     % convert to matrix representation
%     mx=cosmo_convert_neighborhood(nbrhood,'matrix');
%     cosmo_disp(mx)
%     %|| [ 1         2         3         4         5         6
%     %||   4         1         2         1         4         5
%     %||   2         5         6         5         2         3
%     %||   0         3         0         0         6         0 ]
%     %
%     % convert to cell representation
%     neighbors=cosmo_convert_neighborhood(nbrhood,'cell');
%     cosmo_disp(neighbors)
%     %|| { [ 1         4         2 ]
%     %||   [ 2         1         5         3 ]
%     %||   [ 3         2         6 ]
%     %||   [ 4         1         5 ]
%     %||   [ 5         4         2         6 ]
%     %||   [ 6         5         3 ]           }
%
% Notes:
%    - the rationale of this function is that cell or struct
%      representations are more intuitive and possible more space
%      efficient, but also slower to access than matrix representations.
%      This function provides conversion between different representations.
%
% #   For CoSMoMVPA's copyright information and license terms,   #
% #   see the COPYING file distributed with CoSMoMVPA.           #

    if nargin<2, output_type=''; end

    if isnumeric(nbrhood)
        converter=@convert_matrix;
    elseif iscell(nbrhood)
        converter=@convert_cell;
    elseif isstruct(nbrhood)
        converter=@convert_struct;
    else
        error('Expected matrix, cell, or struct input');
    end

    conv_nbrhood=converter(nbrhood, output_type);

function y=convert_cell(x,output_type)
    check_cell(x);
    switch output_type
        case {'','matrix'}
            y=convert_cell2matrix(x);
        case 'struct'
            y=convert_cell2struct(x);
        case {'cell'}
            y=x;
        otherwise
            throw_illegal_output_type_error();
    end

function y=convert_matrix(x,output_type)
    check_matrix(x);
    switch output_type
        case {'','cell'}
            y=convert_matrix2cell(x);
        case 'struct'
            y=convert_matrix2struct(x);
        case 'matrix'
            y=x;
        otherwise
            throw_illegal_output_type_error();
    end

function y=convert_struct(x,output_type)
    check_struct(x);
    switch output_type
        case 'cell'
            y=convert_struct2cell(x);
        case {'','matrix'}
            y=convert_struct2matrix(x);
        case 'struct'
            y=x;
        otherwise
            throw_illegal_output_type_error();
    end

function check_matrix(neighbors)
    if numel(size(neighbors))~=2
        error('input is not a matrix');
    end

    assert(isnumeric(neighbors));

    if ~isequal(round(neighbors),neighbors)
        error('input has non-integer values');
    end

function check_struct(nbrhood)
    cosmo_check_neighborhood(nbrhood,'show_warning',false);

function check_cell(neighbors)
    check_struct(convert_cell2struct(neighbors));

function nbrhood=convert_cell2struct(neighbors)
    nbrhood=struct();
    nbrhood.neighbors=neighbors;
    nbrhood.fa=struct();
    nbrhood.a=struct();

function neighbors=convert_struct2cell(nbrhood)
    neighbors=nbrhood.neighbors;

function neighbor_matrix=convert_cell2matrix(neighbors)
    nfeatures=numel(neighbors);
    nnbrs=cellfun(@numel, neighbors);
    maxn=max(nnbrs);

    neighbor_matrix=zeros(maxn, nfeatures);
    for k=1:nfeatures
        nbrs=neighbors{k};
        neighbor_matrix(1:numel(nbrs),k)=nbrs;
    end

function neighbors=convert_matrix2cell(neighbor_matrix)
    nfeatures=size(neighbor_matrix,2);
    neighbors=cell(nfeatures,1);

    for k=1:nfeatures
        nbrs=neighbor_matrix(:,k);
        neighbors{k}=nbrs(nbrs>0)';
    end

function nbrhood=convert_matrix2struct(neighbor_matrix)
    nbrhood=convert_cell2struct(convert_matrix2cell(neighbor_matrix));

function neighbor_matrix=convert_struct2matrix(nbrhood)
    neighbor_matrix=convert_cell2matrix(convert_struct2cell(nbrhood));

function throw_illegal_output_type_error()
    valid_output_types={'','matrix','struct','cell'};
    error('illegal output type, valid is one of: ''%s''.',...
                cosmo_strjoin(valid_output_types,''', '''));


function n = p37_n ( )

%*****************************************************************************80
%
%% P37_N returns the number of variables for problem 37.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 January 2001
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer N.  If N is positive, N represents the
%    only legal value for N for this problem.  If N is
%    negative, the absolute value of N is the least legal
%    value of N, but other values are allowable.
%
  n = 2;

  return
end


function [modelSize] = modelSizes(model)
%%%
%
% This method prints out detailed sizes of individual matrices and return
% the total model size.
% model is a struct, in which each element could be a matrix or a cell of
% matrices.
%
% Thang Luong @ 2015, <lmthang@stanford.edu>
%
%%%
  fieldNames = fields(model);

  % compute model size
  modelSize = 0;
  for ii=1:length(fieldNames)
    field = fieldNames{ii};
    if iscell(model.(field))
      for jj=1:length(model.(field))
        modelSize = modelSize + numel(model.(field){jj});
        modelSizes.(field){jj} = numel(model.(field){jj});
      end
    else
      modelSize = modelSize + numel(model.(field));
      modelSizes.(field) = numel(model.(field));
    end
  end
  fprintf(2, '  Model size = %d, individual sizes: %s\n', modelSize, wInfo(modelSizes, 0));
end


function value = r8vec_eq ( n, a1, a2 )

%*****************************************************************************80
%
%% R8VEC_EQ is true if two R8VEC's are equal.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 October 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of entries in the vectors.
%
%    Input, real A1(N), A2(N), two vectors to compare.
%
%    Output, logical VALUE, is TRUE if every pair of elements A1(I)
%    and A2(I) are equal, and FALSE otherwise.
%
  value = all ( a1(1:n) == a2(1:n) );

  return
end


function [m,n] = size(a,dim)
%SIZE         Implements  size(a)  for Taylor
%
%   [m,n] = size(a,dim)
%
% functionality as Matlab function size, second argument dim optional
%

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

  if nargout==2
    m = a.size(1);
    n = a.size(2);
  else
    if nargin==1
      m = a.size;
    else
      m = a.size(dim);
    end
  end


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

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

% Last Modified by GUIDE v2.5 09-Sep-2013 22:52:08

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @newton_Raphson_GUI_OpeningFcn, ...
                   'gui_OutputFcn',  @newton_Raphson_GUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin & isstr(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 newton_Raphson_GUI is made visible.
function newton_Raphson_GUI_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 newton_Raphson_GUI (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = newton_Raphson_GUI_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 during object creation, after setting all properties.
function f_CreateFcn(hObject, eventdata, handles)
% hObject    handle to f (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function f_Callback(hObject, eventdata, handles)
% hObject    handle to f (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of f as text
%        str2double(get(hObject,'String')) returns contents of f as a double

% --- Executes on button press in plot.
function plot_Callback(hObject, eventdata, handles)
syms x;
fun=(x.^2)-1;
ezplot(fun);
% hObject    handle to plot (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes during object creation, after setting all properties.
function x0_CreateFcn(hObject, eventdata, handles)
% hObject    handle to x0 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function x0_Callback(hObject, eventdata, handles)
% hObject    handle to x0 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of x0 as text
%        str2double(get(hObject,'String')) returns contents of x0 as a double

% --- Executes during object creation, after setting all properties.
function edit3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function edit3_Callback(hObject, eventdata, handles)
% hObject    handle to edit3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit3 as text
%        str2double(get(hObject,'String')) returns contents of edit3 as a double

% --- Executes during object creation, after setting all properties.
function edit5_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function edit5_Callback(hObject, eventdata, handles)
% hObject    handle to edit5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit5 as text
%        str2double(get(hObject,'String')) returns contents of edit5 as a double

% --- Executes on button press in solve.
function solve_Callback(hObject, eventdata, handles)

xi=str2num(get(handles.x0,'string'));

for i=1:20

xn=xi-(polyval([1 0 -1],[xi])/polyval(polyder([1 0 -1]),[xi]));
disp(xn);
set(handles.r,'string',xn);
xi=xn;
i=i+1;

end
% hObject    handle to solve (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


function value = year_length_months_persian ( y )

%*****************************************************************************80
%
%% YEAR_LENGTH_MONTHS_PERSIAN returns the number of months in a Persian 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 = 12;

  return
end


function n = length( x )
s = size( x );
if any( s == 0 ),
   n = 0;
else
   n = max( s );
end

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


function r8mat_indicator_test ( )

%*****************************************************************************80
%
%% R8MAT_INDICATOR_TEST tests R8MAT_INDICATOR_TEST.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 December 2014
%
%  Author:
%
%    John Burkardt
%
  m = 5;
  n = 4;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'R8MAT_INDICATOR_TEST\n' );
  fprintf ( 1, '  R8MAT_INDICATOR returns an indicator matrix.\n' );

  a = r8mat_indicator ( m, n );

  r8mat_print ( m, n, a, '  Indicator matrix:' );

  return
end


function s = weekday_to_name_republican ( w )

%*****************************************************************************80
%
%% WEEKDAY_TO_NAME_REPUBLICAN returns the name of a Republican weekday.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 September 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer W, the weekday index.
%
%    Output, string S, the weekday name.
%
  weekday_name = [ ...
    'Primedi '; ...
    'Duodi   '; ...
    'Tridi   '; ...
    'Quartidi'; ...
    'Quintidi'; ...
    'Sextidi '; ...
    'Septidi '; ...
    'Octidi  '; ...
    'Nonidi  '; ...
    'Decadi  ' ];

  if ( w < 1 || 10 < w )
    s = '?????';
  else
    s = weekday_name(w,:);
  end

  return
end


function [cMap]=che(varargin)

% function [cMap]=che(n)
% ------------------------------------------------------------------------
% Creates the colormap data for n levels for the che colormap.
%
% Kevin Mattheus Moerman
% gibbon.toolbox@gmail.com
%
% 2016/04/14
%------------------------------------------------------------------------

switch nargin
    case 0
        n=250;
    case 1
        n=varargin{1};
end

%% Define colors
cMap=[122 141 155; 0 49 79; 214 20 28; 254 229 163; ]./255;

%% Resample colormap
[cMap]=resampleColormap(cMap,n);

end

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


function FigSize(xdim,ydim)
% =======================================================================
% Sets the figure window to a desired size. The default is full screen
% =======================================================================
% FigSize(xdim,ydim)
% -----------------------------------------------------------------------
% OPTIONAL INPUT
%   - xdim: horizontal size (in cm)
%   - ydim: vertical size (in cm)
% -----------------------------------------------------------------------
% EXAMPLE
%   FigSize(12,6)
%   plot(1:10)
% =======================================================================
% VAR Toolbox 3.0
% Ambrogio Cesa-Bianchi
% ambrogiocesabianchi@gmail.com
% March 2015. Updated November 2020
% -----------------------------------------------------------------------

if nargin==0
    figure('units','normalized','outerposition',[0 0.1 1 0.9])
else
    % Get the position of the figure
    % [left bottom width height] [standard in px: 403 246   560   420]
    position = get(gcf, 'Position');

    % Place the figure on the south west corner of the screen (in cm)
    position(1) = 1;
    position(2) = 2;

    % xdim dimension in cm
    if exist('xdim','var')
        position(3) = xdim;
    end

    % ydim dimension in cm
    if exist ('ydim','var')
        position(4) = ydim;
    end

    % Apply rescaling
    set(gcf, 'units', 'centimeters', 'Position', position)
end


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


function edges = meshEdges(faces, varargin)
%MESHEDGES Computes array of edge vertex indices from face array.
%
%   EDGES = meshEdges(FACES);
%
%   Example
%     meshEdges
%
%   See also
%     meshes3d, meshEdgeFaces, meshFaceEdges

% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2011-06-28,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2011 INRA - Cepia Software Platform.

%   HISTORY
%   2013-08-22 rename from computeMeshEdges to meshEdges, add more control
%       on inputs

%% Process input arguments

if isstruct(faces) && isfield(faces, 'faces')
    % if input is a mesh structure, extract the 'faces' field
    faces = faces.faces;
elseif nargin > 1
    % if two arguments are given, keep the second one
    faces = varargin{1};
end

if ~iscell(faces)
    %% Process faces given as numeric array
    % all faces have same number of vertices, stored in nVF variable

    % compute total number of edges
    nFaces  = size(faces, 1);
    nVF     = size(faces, 2);
    nEdges  = nFaces * nVF;

    % create all edges (with double ones)
    edges = zeros(nEdges, 2);
    for i = 1:nFaces
        f = faces(i, :);
        edges(((i-1)*nVF+1):i*nVF, :) = [f' f([2:end 1])'];
    end

else
    %% faces are given as a cell array
    % faces may have different number of vertices

    % number of faces
    nFaces  = length(faces);

    % compute the number of edges
    nEdges = 0;
    for i = nFaces
        nEdges = nEdges + length(faces{i});
    end

    % allocate memory
    edges = zeros(nEdges, 2);
    ind = 0;

    % fillup edge array
    for i = 1:nFaces
        % get vertex indices, ensuring horizontal array
        f = faces{i}(:)';
        nVF = length(f);
        edges(ind+1:ind+nVF, :) = [f' f([2:end 1])'];
        ind = ind + nVF;
    end

end

% keep only unique edges, and return sorted result
edges = sortrows(unique(sort(edges, 2), 'rows'));


function [ labels ] = SegmentToLabels( segment )
%SEGMENTTOLABELS Convert output so labels start from 1 and are consecutive

values = unique(segment);
labels = zeros(size(segment));
for i = 1:length(values)
    labels(segment==values(i)) = i;
end


function [x,y,button] = ginput_zoom(n, style)
%  GINPUT_ZOOM Graphical input from mouse with Zoom In/Out function.
%     [X,Y] = GINPUT_ZOOM(N, STYLE) gets N points from the current axes and returns
%     the X- and Y-coordinates in length N vectors X and Y.  The cursor
%     can be positioned using a mouse (or by using the Arrow Keys on some
%     systems).  Data points are entered by pressing a mouse button
%     or any key on the keyboard except carriage return, which terminates
%     the input before N points are entered. The style of cursor can be
%     change by setting STYLE (please reference to "Specifying the Figure
%     Pointer" in the help, default: 'fullcross').
%
%     User can click and drag to Zoom In / Out
%     - Left-Top to Right-Down means Zoom In
%     - Right-Down to left-Top means Zoom Out
%
%     [X,Y] = GINPUT_ZOOM gathers an unlimited number (less then 100000)
%     of points until the return key is pressed.
%
%     [X,Y,BUTTON] = GINPUT_ZOOM(N) returns a third result, BUTTON, that
%     contains a vector of integers specifying which mouse button was
%     used (1,2,3 from left) or ASCII numbers if a key on the keyboard
%     was used.
%
%     Chang Yi-Chung 20091002

ox = xlim;     % get original x limit
oy = ylim;     % get original y limit
xlim('auto');  % zoom out to x max
ylim('auto');  % zoom out to y max
xmax = xlim;   % get max x
ymax = ylim;   % get max y
xlim(ox);      % restore x limit
ylim(oy);      % restore y limit

if exist('style') == 0
    style = 'fullcross';
end

set(gcf,'pointer', style);  % use fullcross, user can change this

if exist('n') == 0
    n = 100000;
end

for i = 1:n
    while 1
        k = waitforbuttonpress;
        point1 = get(gca,'CurrentPoint');    % button down detected
        finalRect = rbbox;                   % return figure units
        point2 = get(gca,'CurrentPoint');    % button up detected
        point1 = point1(1,1:2);              % extract x and y
        point2 = point2(1,1:2);
        if sum(point1 == point2) == 2        % same points
            if  k == 1                       % detects a key press
                x(i) = point1(1);
                y(i) = point1(2);
                button(i) = double(get(gcf,'CurrentCharacter'));   % get keyboad ascii number
                if n == 100000 & button(i) == 13                   % n is not assigned and press Enter(13) -> exit
                    i = n;
                    % compatible with ginput
                    x = x(1:end-1);
                    y = y(1:end-1);
                    button = button(1:end-1);
                end
            else                             % detects a mouse button press
                x(i) = point1(1);
                y(i) = point1(2);
                switch get(gcf,'SelectionType')
                    case 'normal'            % left button
                        button(i) = 1;
                    case 'extend'            % middle button
                        button(i) = 2;
                    case 'alt'               % right button
                        button(i) = 3;
                end
            end
            break;
        end
        offset = (point2-point1);
        if offset(1) > 0 & offset(2) < 0     % drag left-top to right-down -> zoom in
            xlim([point1(1) point2(1)]);
            ylim([point2(2) point1(2)]);
        end
        if offset(1) < 0 & offset(2) > 0     % drag right-down to left-top -> zoom out
            xlim(xmax);
            ylim(ymax);
        end
    end
    if i == n
        break;
    end
end

% compatible with ginput
x = x';
y = y';
button = button';


function scale = p37_scale ( neqn )

%*****************************************************************************80
%
%% P37_SCALE returns scale factors for problem p37.
%
%  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 i = end(x,k,n)
%END          Overloaded functions end, specifies last index
%

% written  10/03/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
%

  % call must be one-dimensional
  i = length(x.sign);


function r8mat_plot ( m, n, a, title )

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

  for jlo = 1 : 70 : n

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

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

  return
end


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

%*****************************************************************************80
%
%% P09_STEPSIZE returns step sizes for problem 9.
%
%  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 =    0.300;
  hmin = 0.001;
  hmax = 0.600;

  return
end


function [ t_start, y_start ] = p25_start ( neqn )

%*****************************************************************************80
%
%% P25_START returns the starting point for problem p25.
%
%  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 = [ 0.0; 0.0 ];

  return
end


%
% Make a string by combining a sequence of
% both strings and numbers (rounded), where each
% number is converted to a string
%
function str = makestr(varargin)

    n = numel(varargin);
    str = [];
    for i=1:n
        A = varargin{i};
        if ischar(A)
            str = [str A];
        elseif isnumeric(A)
            str = [str num2str(A,3)];
        else
            error('invalid input type');
        end
    end

end


function value = p24_exact ( dim_num )

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

  return
end