%kkgrayleigh 'Generate Rayleigh Noise Data'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros kgrayleigh.pane file
%
% Parameters:
% Integer: wsize 'Width ', default: 512: 'Width size of noise value data'
% Integer: hsize 'Height ', default: 512: 'Height size of noise value data'
% Integer: dsize 'Depth ', default: 1: 'Depth size of noise value data'
% Integer: tsize 'Time ', default: 1: 'Time size of noise value data'
% Integer: esize 'Elements ', default: 1: 'Element dimension size of noise data'
% OutputFile: o 'Output File', required: 'Output file containing noise data'
%
% Example: o = kkgrayleigh( {'wsize',512;'hsize',512;'dsize',1;'tsize',1;'esize',1;'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% kgrayleigh - Generate Rayleigh Noise Data
%
%  DESCRIPTION
% "kgrayleigh" generates Rayleigh noise of the specified parameters in the
% output data object (-o). The variance (-rvar) must be
% specified for the Rayleigh distribution to be generated.
%
% The size of all five dimensions of the object can be specified. The data type
% of the output object can also be specified. "kgrayleigh" can also generate
% complex valued Rayleigh noise data.
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
%
%  RESTRICTIONS
% DATAMANIP::kgnoise, DATAMANIP::kgexpon, DATAMANIP::kggauss,
% DATAMANIP::kpoisson, DATAMANIP::kguniform
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kkgrayleigh(varargin)
Inputs={};
if nargin ==0
  arglist={'',''};
elseif nargin ==1
  arglist=varargin{1};
else error('Usage: [out1,..] = kkgrayleigh(arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'wsize', 512;'hsize', 512;'dsize', 1;'tsize', 1;'esize', 1;'o', '__output'};
maxval={2,2,2,2,2,0};
minval={2,2,2,2,2,0};
istoggle=[1,1,1,1,1,0];
was_set=istoggle * 0;
paramtype={'Integer','Integer','Integer','Integer','Integer','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 'kgnoise"  -ray'],Inputs,narglist);


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

%*****************************************************************************80
%
%% P20_STEPSIZE returns step sizes for problem 20.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 October 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.00250;
  hmin = 0.01000;
  hmax = 0.08000;

  return
end


function out=strrel(in1,in2,relop)
% function out=strrel(in1,in2,relop)
%
%  Compares strings according to strcmp and issorted according to relop
%  in1 and in2 can be character arrays or cell arrays
%  relop can be <, <=, >, >=, ==, and ~=, or their string equivalents
%    such as 'ne' or 'gt', etc.
%
%  Examples:
%  c = {'How','much','wood','would','a','woodchuck','chuck?'};
%  s = 'wood';
%  r = strrel(s,c,'<')
%  r = strrel(s,c,'ge')

% Author: Ben Barrowes, barrowes@alum.mit.edu, 10/2007
%
% 2007-10-18 bugfix and vectorization as pointed out by Urs (us) Schwarz

out=[];
% empty out if empty in (like []==3)
if isempty(in1) || isempty(in2), return, end

%doesn't handle numerical inputs
if isnumeric(in1) || isnumeric(in2)
 error('arguments to strrel must be char arrays or cell arrays of strings');
end

%promote char arrays to cell arrays
if ischar(in1), in1={in1}; end
if ischar(in2), in2={in2}; end

%repmat smaller cell array to size of larger if needed
if ~all(size(in1)==size(in2))
 if prod(size(in1))==1
  in1=repmat(in1,size(in2));
 elseif prod(size(in2))==1
  in2=repmat(in2,size(in1));
 else
  error('input array size mismatch in strrel');
 end
end

%should both be the same size cell arrays by now
out=false(size(in1));

% Do the logic
isEqual =strcmp(in1,in2);
for i=1:numel(in1)
 %isSorted=issorted({in1{i},in2{i}});
 isSorted=issortedcellchar({in1{i},in2{i}}); %about 3-4 faster
 switch lower(relop)
   case {'<','lt'}
     out(i)=isSorted & ~isEqual(i);
   case {'<=','le'}
     out(i)=isSorted | isEqual(i);
   case {'==','eq'}
     out(i)=isEqual(i);
   case {'~=','ne','!=','/='}
     out(i)=~isEqual(i);
   case {'>','gt'}
     out(i)=~isSorted & ~isEqual(i);
   case {'>=','ge'}
     out(i)=~isSorted | isEqual(i);
   otherwise
     error(['Relational operator, ',relop,', not recognized in strrel.'])
 end
end

%%%% this handle-vectorized version seemed to be somewhat slower
%%%isSorted=cellfun(@(x,y) issorted({x,y}),in1,in2);
%%%isEqual =strcmp(in1,in2);
%%%switch lower(relop)
%%%  case {'<','lt'}
%%%    out=isSorted & ~isEqual;
%%%  case {'<=','le'}
%%%    out=isSorted | isEqual;
%%%  case {'==','eq'}
%%%    out=isEqual;
%%%  case {'~=','ne','!=','/='}
%%%    out=~isEqual;
%%%  case {'>','gt'}
%%%    out=~isSorted & ~isEqual;
%%%  case {'>=','ge'}
%%%    out=~isSorted | isEqual;
%%%  otherwise
%%%    error(['Relational operator, ',relop,', not recognized in strrel.'])
%%%end


function [y] = gt(x, val)

y = cell(size(x));
for k = 1:numel(x)
  y{k} = x{k}>val;
end


function tet_mesh_tet_neighbors ( prefix )

%*****************************************************************************80
%
%% MAIN is the main program for TET_MESH_TET_NEIGHBORS.
%
%  Discussion:
%
%    TET_MESH_TET_NEIGHBORS manages the tet mesh neighbor calculation.
%
%    A tet mesh of order 4 or order 10 may be used.
%
%  Usage:
%
%    tet_mesh_tet_neighbors ( 'prefix' )
%
%    where
%
%    * 'prefix'_nodes.txt contains nodal coordinates (not used by this function);
%    * 'prefix'_elements.txt the element definitions;
%    * 'prefix'_element_neighbors.txt contains the element neigbhbors.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 February 2010
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  timestamp ( );

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TET_MESH_TET_NEIGHBORS:\n' );
  fprintf ( 1, '  MATLAB version:\n' );
  fprintf ( 1, '  Read a tet mesh dataset of TETRA_NUM\n' );
  fprintf ( 1, '  tetrahedrons, u sing 4 or 10 nodes.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Compute tet mesh neighbors and write this\n' );
  fprintf ( 1, '  information to a file.\n' );
%
%  Argument 1 is the common file prefix.
%
  if ( 1 <= nargin )

  else

    fprintf ( 1, '\n' );
    fprintf ( 1, 'TET_MESH_TET_NEIGHBORS:\n' );
    prefix = input ( '  Please enter the filename prefix:' );

  end
%
%  Create the filenames.
%
  element_filename = strcat ( prefix, '_elements.txt' );
  neighbor_filename = strcat ( prefix, '_element_neighbors.txt' );
%
%  Read the tetra data.
%
  [ tetra_order, tetra_num ] = i4mat_header_read ( element_filename );

  if ( tetra_order ~= 4 && tetra_order ~= 10 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'TET_MESH_TET_NEIGHBORS - Fatal error!\n' );
    fprintf ( 1, '  Data is not for a 4 or 10 node tet mesh.\n' );
    error ( 'TET_MESH_TET_NEIGHBORS - Fatal error!' );
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Read the header of "%s".\n', element_filename );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Tetrahedron order = %d\n', tetra_order );
  fprintf ( 1, '  Number of tetras  = %d\n', tetra_num );

  tetra_node = i4mat_data_read ( element_filename, tetra_order, ...
    tetra_num );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Read the data in "%s".\n', element_filename );
%
%  Detect and correct 0-based indexing.
%
  tetra_node = mesh_base_one ( tetra_order, tetra_num, tetra_node );
%
%  Print first 5.
%
  i4mat_transpose_print_some ( tetra_order, tetra_num, ...
    tetra_node, 1, 1, tetra_order, 5, '  First 5 tetrahedrons:' );
%
%  Compute the neighbor information.
%
  tetra_neighbor = tet_mesh_neighbor_tets ( tetra_order, tetra_num, ...
    tetra_node );

  i4mat_transpose_print_some ( 4, tetra_num, ...
    tetra_neighbor, 1, 1, 4, 5, '  First 5 neighbors:' );
%
%  Write the neighbor information to a file.
%  Create the output file name from the input file name.
%
  i4mat_write ( neighbor_filename, 4, tetra_num, tetra_neighbor );

  fprintf ( 1, '  Wrote the tetrahedron neighbor information to "%s".\n', ...
    neighbor_filename );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TET_MESH_TET_NEIGHBORS:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );

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

  return
end
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!' );
  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
function row_num = file_row_count ( input_file_name )

%*****************************************************************************80
%
%% FILE_ROW_COUNT counts the number of row records in a file.
%
%  Discussion:
%
%    Each input line is a "RECORD".
%
%    The records are divided into three groups:
%
%    * BLANK LINES (nothing but blanks)
%    * COMMENT LINES (begin with a '#')
%    * DATA RECORDS (anything else)
%
%    The value returned by the function is the number of data records.
%
%    By the way, if the MATLAB routine FGETS is used, instead of
%    FGETL, then the variable LINE will include line termination
%    characters, which means that a blank line would not actually
%    have zero characters.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    31 December 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string INPUT_FILE_NAME, the name of the input file.
%
%    Output, integer ROW_NUM, the number of rows found.
%
  input_unit = fopen ( input_file_name );

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

  blank_num = 0;
  comment_num = 0;
  row_num = 0;

  record_num = 0;

  while ( 1 )

    line = fgetl ( input_unit );

    if ( line == -1 )
      break;
    end

    record_num = record_num + 1;
    record_length = s_len_trim ( line );

    if ( record_length <= 0 )
      blank_num = blank_num + 1;
    elseif ( line(1) == '#' )
      comment_num = comment_num + 1;
    else
      row_num = row_num + 1;
    end

  end

  fclose ( input_unit );

  return
end
function isgn = i4col_compare ( m, n, a, i, j )

%*****************************************************************************80
%
%% I4COL_COMPARE compares columns I and J of a integer array.
%
%  Example:
%
%    Input:
%
%      M = 3, N = 4, I = 2, J = 4
%
%      A = (
%        1  2  3  4
%        5  6  7  8
%        9 10 11 12 )
%
%    Output:
%
%      ISGN = -1
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 June 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns.
%
%    Input, integer A(M,N), an array of N columns of vectors of length M.
%
%    Input, integer I, J, the columns to be compared.
%    I and J must be between 1 and N.
%
%    Output, integer ISGN, the results of the comparison:
%    -1, column I < column J,
%     0, column I = column J,
%    +1, column J < column I.
%

%
%  Check.
%
  if ( i < 1)
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4COL_COMPARE - Fatal error!\n' );
    fprintf ( 1, '  Column index I = %d < 1.\n', i );
    error ( 'I4COL_COMPARE - Fatal error!' );
  end

  if ( n < i )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4COL_COMPARE - Fatal error!\n' );
    fprintf ( 1, '  N = %d < column index I = %d.\n', n, i );
    error ( 'I4COL_COMPARE - Fatal error!' );
  end

  if ( j < 1 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4COL_COMPARE - Fatal error!\n' );
    fprintf ( 1, '  Column index J = %d < 1.\n', j );
    error ( 'I4COL_COMPARE - Fatal error!' );
  end

  if ( n < j )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4COL_COMPARE - Fatal error!\n' );
    fprintf ( 1, '  N = %d < column index J = %d.\n', n, j );
    error ( 'I4COL_COMPARE - Fatal error!' );
  end

  isgn = 0;

  if ( i == j )
    return
  end

  k = 1;

  while ( k <= m )

    if ( a(k,i) < a(k,j) )
      isgn = -1;
      return
    elseif ( a(k,j) < a(k,i) )
      isgn = +1;
      return
    end

    k = k + 1;

  end

  return
end
function a = i4col_sort_a ( m, n, a )

%*****************************************************************************80
%
%% I4COL_SORT_A ascending sorts an I4COL.
%
%  Discussion:
%
%    In lexicographic order, the statement "X < Y", applied to two real
%    vectors X and Y of length M, means that there is some index I, with
%    1 <= I <= M, with the property that
%
%      X(J) = Y(J) for J < I,
%    and
%      X(I) < Y(I).
%
%    In other words, the first time they differ, X is smaller.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 February 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the number of rows of A, and the length of
%    a vector of data.
%
%    Input, integer N, the number of columns of A.
%
%    Input, integer A(M,N), the array of N columns of M-vectors.
%
%    Output, integer A(M,N), the columns of A have been sorted in ascending
%    lexicographic order.
%
  if ( m <= 0 )
    return
  end

  if ( n <= 1 )
    return
  end
%
%  Initialize.
%
  indx = 0;
  isgn = 0;
%
%  Call the external heap sorter.
%
  while ( 1 )

    [ indx, i, j ] = sort_heap_external ( n, indx, isgn );
%
%  Interchange the I and J objects.
%
    if ( 0 < indx )

      a = i4col_swap ( m, n, a, i, j );
%
%  Compare the I and J objects.
%
    elseif ( indx < 0 )

      isgn = i4col_compare ( m, n, a, i, j );

    elseif ( indx == 0 )

      break

    end

  end

  return
end
function a = i4col_swap ( m, n, a, i, j )

%*****************************************************************************80
%
%% I4COL_SWAP swaps columns I and J of a integer array of column data.
%
%  Example:
%
%    Input:
%
%      M = 3, N = 4, I = 2, J = 4
%
%      A = (
%        1  2  3  4
%        5  6  7  8
%        9 10 11 12 )
%
%    Output:
%
%      A = (
%        1  4  3  2
%        5  8  7  6
%        9 12 11 10 )
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 February 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns in the array.
%
%    Input, integer A(M,N), an array of N columns of length M.
%
%    Input, integer I, J, the columns to be swapped.
%
%    Output, integer A(M,N), the array, with columns I and J swapped.
%
  if ( i < 1 || n < i || j < 1 || n < j )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4COL_SWAP - Fatal error!\n' );
    fprintf ( 1, '  I or J is out of bounds.\n' );
    fprintf ( 1, '  I =    %d\n', i );
    fprintf ( 1, '  J =    %d\n', j );
    fprintf ( 1, '  N =    %d\n', n );
    error ( 'I4COL_SWAP - Fatal error!' );
  end

  if ( i == j )
    return
  end

  col(1:m) = a(1:m,i)';
  a(1:m,i) = a(1:m,j);
  a(1:m,j) = col(1:m)';

  return
end
function [ j1, j2, j3 ] = i4i4i4_sort_a ( i1, i2, i3 )

%*****************************************************************************80
%
%% I4I4I4_SORT_A ascending sorts a triple of integers.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 October 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer I1, I2, I3, the values to sort.
%
%    Output, integer J1, J2, J3, the sorted values.
%
  j1 = min ( min ( i1, i2 ), min ( i2, i3 ) );
  j2 = min ( max ( i1, i2 ), ...
       min ( max ( i2, i3 ), max ( i3, i1 ) ) );
  j3 = max ( max ( i1, i2 ), max ( i2, i3 ) );

  return
end
function table = i4mat_data_read ( input_filename, m, n )

%*****************************************************************************80
%
%% I4MAT_DATA_READ reads data from an I4MAT file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 January 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string INPUT_FILENAME, the name of the input file.
%
%    Input, integer M, N, the number of rows and columns in the data.
%
%    Output, integer TABLE(M,N), the point coordinates.
%
  table = zeros ( m, n );
%
%  Build up the format string for reading M real numbers.
%
  string = ' ';

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

  input_unit = fopen ( input_filename );

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

  i = 0;

  while ( i < n )

    line = fgets ( input_unit );

    if ( line == -1 )
      fprintf ( 1, '\n' );
      fprintf ( 1, 'I4MAT_DATA_READ - Error!\n' );
      fprintf ( 1, '  End of input while reading data.\n' );
      error ( 'I4MAT_DATA_READ - Error!' );
    end

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

    elseif ( s_len_trim ( line ) == 0 )

    else

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

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

    end

  end

  fclose ( input_unit );

  return
end
function [ m, n ] = i4mat_header_read ( input_filename )

%*****************************************************************************80
%
%% I4MAT_HEADER_READ reads the header from an I4MAT file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 October 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string INPUT_FILENAME, the name of the input file.
%
%    Output, integer M, the spatial dimension.
%
%    Output, integer N, the number of points.
%
  m = file_column_count ( input_filename );

  if ( m <= 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4MAT_HEADER_READ - Fatal error!\n' );
    fprintf ( 1, '  There was some kind of I/O problem while trying\n' );
    fprintf ( 1, '  to count the number of data columns in\n' );
    fprintf ( 1, '  the file %s.\n', input_filename );
  end

  n = file_row_count ( input_filename );

  if ( n <= 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4MAT_HEADER_READ - Fatal error!\n' );
    fprintf ( 1, '  There was some kind of I/O problem while trying\n' );
    fprintf ( 1, '  to count the number of data rows in\n' );
    fprintf ( 1, '  the file %s\n', input_filename );
  end

  return
end
function i4mat_transpose_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )

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

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

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

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

    inc = i2hi + 1 - i2lo;

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Row: ' );
    for i = i2lo : i2hi
      fprintf ( 1, '%7d  ', i );
    end
    fprintf ( 1, '\n' );
    fprintf ( 1, '  Col\n' );
    fprintf ( 1, '\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, '%7d  ', a(i,j) );
      end
      fprintf ( 1, '\n' );

    end

  end

  return
end
function i4mat_write ( output_filename, m, n, table )

%*****************************************************************************80
%
%% I4MAT_WRITE writes an I4MAT file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 July 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string OUTPUT_FILENAME, the output filename.
%
%    Input, integer M, the spatial dimension.
%
%    Input, integer N, the number of points.
%
%    Input, integer TABLE(M,N), the points.
%
%    Input, logical HEADER, is TRUE if the header is to be included.
%

%
%  Open the file.
%
  output_unit = fopen ( output_filename, 'wt' );

  if ( output_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4MAT_WRITE - Error!\n' );
    fprintf ( 1, '  Could not open the output file.\n' );
    error ( 'I4MAT_WRITE - Error!' );
  end
%
%  Write the data.
%
  for j = 1 : n
    for i = 1 : m
      fprintf ( output_unit, '  %12d', round ( table(i,j) ) );
    end
    fprintf ( output_unit, '\n' );
  end
%
%  Close the file.
%
  fclose ( output_unit );

  return
end
function element_node = mesh_base_one ( element_order, element_num, ...
  element_node )

%*****************************************************************************80
%
%% MESH_BASE_ONE ensures that the element definition is one-based.
%
%  Discussion:
%
%    The ELEMENT_NODE array contains nodes indices that form elements.
%    The convention for node indexing might start at 0 or at 1.
%    Since a MATLAB program will naturally assume a 1-based indexing, it is
%    necessary to check a given element definition and, if it is actually
%    0-based, to convert it.
%
%    This function attempts to detect 0-based node indexing and correct it.
%
%    Thanks to Feifei Xu for pointing out that I was subtracting 1 when I
%    should have been adding 1!  29 November 2012.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 November 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer ELEMENT_ORDER, the order of the elements.
%
%    Input, integer ELEMENT_NUM, the number of elements.
%
%    Input/output, integer ELEMENT_NODE(ELEMENT_ORDER,ELEMENT_NUM), the element
%    definitions.
%
  node_min = min ( min ( element_node(1:element_order,1:element_num) ) );

  if ( node_min == 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'MESH_BASE_ONE:\n' );
    fprintf ( 1, '  The element indexing appears to be 0-based!\n' );
    fprintf ( 1, '  This will be converted to 1-based.\n' );
    element_node(1:element_order,1:element_num) = ...
      element_node(1:element_order,1:element_num) + 1;
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'MESH_BASE_ONE:\n' );
    fprintf ( 1, '  The element indexing appears to be 1-based!\n' );
    fprintf ( 1, '  No conversion is necessary.\n' );
  end

  return
end
function len = s_len_trim ( s )

%*****************************************************************************80
%
%% S_LEN_TRIM returns the length of a character string to the last nonblank.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 June 2003
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string S, the string to be measured.
%
%    Output, integer LEN, the length of the string up to the last nonblank.
%
  len = length ( s );

  while ( 0 < len )
    if ( s(len) ~= ' ' )
      return
    end
    len = len - 1;
  end

  return
end
function word_num = s_word_count ( s )

%*****************************************************************************80
%
%% S_WORD_COUNT counts the number of "words" in a string.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 January 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string S, the string to be examined.
%
%    Output, integer WORD_NUM, the number of "words" in the string.
%    Words are presumed to be separated by one or more blanks.
%
  FALSE = 0;
  TRUE = 1;

  word_num = 0;
  s_length = length ( s );

  if ( s_length <= 0 )
    return;
  end

  blank = TRUE;

  for i = 1 : s_length

    if ( s(i) == ' ' )
      blank = TRUE;
    elseif ( blank == TRUE )
      word_num = word_num + 1;
      blank = FALSE;
    end

  end

  return
end
function [ indx, i, j ] = sort_heap_external ( n, indx, isgn )

%*****************************************************************************80
%
%% SORT_HEAP_EXTERNAL externally sorts a list of items into ascending order.
%
%  Discussion:
%
%    The actual list of data is not passed to the routine.  Hence this
%    routine may be used to sort integers, reals, numbers, names,
%    dates, shoe sizes, and so on.  After each call, the routine asks
%    the user to compare or interchange two items, until a special
%    return value signals that the sorting is completed.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    05 February 2004
%
%  Author:
%
%    Original FORTRAN77 version by Albert Nijenhuis, Herbert Wilf.
%    MATLAB version by John Burkardt
%
%  Reference:
%
%    Albert Nijenhuis, Herbert Wilf.
%    Combinatorial Algorithms,
%    Academic Press, 1978, second edition,
%    ISBN 0-12-519260-6.
%
%  Parameters:
%
%    Input, integer N, the number of items to be sorted.
%
%    Input, integer INDX, the main communication signal.
%    The user must set INDX to 0 before the first call.
%    Thereafter, the user should set the input value of INDX
%    to the output value from the previous call.
%
%    Input, integer ISGN, results of comparison of elements I and J.
%    (Used only when the previous call returned INDX less than 0).
%    ISGN <= 0 means I is less than or equal to J;
%    0 <= ISGN means I is greater than or equal to J.
%
%    Output, integer INDX, the main communication signal.
%    If INDX is
%
%      greater than 0, the user should:
%      * interchange items I and J;
%      * call again.
%
%      less than 0, the user should:
%      * compare items I and J;
%      * set ISGN = -1 if I < J, ISGN = +1 if J < I;
%      * call again.
%
%      equal to 0, the sorting is done.
%
%    Output, integer I, J, the indices of two items.
%    On return with INDX positive, elements I and J should be interchanged.
%    On return with INDX negative, elements I and J should be compared, and
%    the result reported in ISGN on the next call.
%
  persistent i_save;
  persistent j_save;
  persistent k;
  persistent k1;
  persistent n1;
%
%  INDX = 0: This is the first call.
%
  if ( indx == 0 )

    i_save = -1;
    j_save = -1;
    k = floor ( n / 2 );
    k1 = k;
    n1 = n;
%
%  INDX < 0: The user is returning the results of a comparison.
%
  elseif ( indx < 0 )

    if ( indx == -2 )

      if ( isgn < 0 )
        i_save = i_save + 1;
      end

      j_save = k1;
      k1 = i_save;
      indx = -1;
      i = i_save;
      j = j_save;
      return;
    end

    if ( 0 < isgn )
      indx = 2;
      i = i_save;
      j = j_save;
      return;
    end

    if ( k <= 1 )

      if ( n1 == 1 )
        i_save = 0;
        j_save = 0;
        indx = 0;
      else
        i_save = n1;
        n1 = n1 - 1;
        j_save = 1;
        indx = 1;
      end

      i = i_save;
      j = j_save;
      return;

    end

    k = k - 1;
    k1 = k;
%
%  0 < INDX, the user was asked to make an interchange.
%
  elseif ( indx == 1 )

    k1 = k;

  end

  while ( 1 )

    i_save = 2 * k1;

    if ( i_save == n1 )
      j_save = k1;
      k1 = i_save;
      indx = -1;
      i = i_save;
      j = j_save;
      return;
    elseif ( i_save <= n1 )
      j_save = i_save + 1;
      indx = -2;
      i = i_save;
      j = j_save;
      return;
    end

    if ( k <= 1 )
      break;
    end

    k = k - 1;
    k1 = k;

  end

  if ( n1 == 1 )
    i_save = 0;
    j_save = 0;
    indx = 0;
    i = i_save;
    j = j_save;
  else
    i_save = n1;
    n1 = n1 - 1;
    j_save = 1;
    indx = 1;
    i = i_save;
    j = j_save;
  end

  return
end
function tetra_neighbor = tet_mesh_neighbor_tets ( tetra_order, tetra_num, ...
  tetra_node )

%*****************************************************************************80
%
% TET_MESH_NEIGHBOR_TETS determines tetrahedron neighbors.
%
%  Discussion:
%
%    A tet mesh of a set of nodes can be completely described by
%    the coordinates of the nodes, and the list of nodes that make up
%    each tetrahedron.  In the most common case, four nodes are used.
%    There is also a 10 node case, where nodes are also placed on
%    the midsides of the tetrahedral edges.
%
%    This routine can handle 4 or 10-node tetrahedral meshes.  The
%    10-node case is handled simply by ignoring the six midside nodes,
%    which are presumed to be listed after the vertices.
%
%    The tetrahedron adjacency information records which tetrahedron
%    is adjacent to a given tetrahedron on a particular face.
%
%    This routine creates a data structure recording this information.
%
%    The primary amount of work occurs in sorting a list of 4 * TETRA_NUM
%    data items.
%
%    The neighbor tetrahedrons are indexed by the face they share with
%    the tetrahedron.
%
%    Each face of the tetrahedron is indexed by the node which is NOT
%    part of the face.  That is:
%
%    * Neighbor 1 shares face 1 defined by nodes 2, 3, 4.
%    * Neighbor 2 shares face 2 defined by nodes 1, 3, 4;
%    * Neighbor 3 shares face 3 defined by nodes 1, 2, 4;
%    * Neighbor 4 shares face 4 defined by nodes 1, 2, 3.
%
%    For instance, if the (transposed) TETRA_NODE array was:
%
%    Row       1      2      3      4
%    Col
%
%      1       4      3      5      1
%      2       4      2      5      1
%      3       4      7      3      5
%      4       4      7      8      5
%      5       4      6      2      5
%      6       4      6      8      5
%
%    then the (transposed) TETRA_NEIGHBOR array should be:
%
%    Row       1      2      3      4
%    Col
%
%      1      -1      2     -1      3
%      2      -1      1     -1      5
%      3      -1      1      4     -1
%      4      -1      6      3     -1
%      5      -1      2      6     -1
%      6      -1      4      5     -1
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 January 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer TETRA_ORDER, the order of the tetrahedrons.
%
%    Input, integer TETRA_NUM, the number of tetrahedrons.
%
%    Input, integer TETRA_NODE(TETRA_ORDER,TETRA_NUM), the nodes that make up
%    each tetrahedron.
%
%    Output, integer TETRA_NEIGHBOR(4,TETRA_NUM), the four tetrahedrons that
%    are direct neighbors of a given tetrahedron.  If there is no neighbor
%    sharing a given face, the index is set to -1.
%

%
%  Step 1.
%  From the list of nodes for tetrahedron T, of the form: (I,J,K,L)
%  construct the four face relations:
%
%    (J,K,L,1,T)
%    (I,K,L,2,T)
%    (I,J,L,3,T)
%    (I,J,K,4,T)
%
%  In order to make matching easier, we reorder each triple of nodes
%  into ascending order.
%
  faces = zeros ( 5, 4 * tetra_num );
  for tetra = 1 : tetra_num

    i = tetra_node(1,tetra);
    j = tetra_node(2,tetra);
    k = tetra_node(3,tetra);
    l = tetra_node(4,tetra);

    [ a, b, c ] = i4i4i4_sort_a ( j, k, l );

    faces(1:5,4*(tetra-1)+1) = [ a, b, c, 1, tetra ]';

    [ a, b, c ] = i4i4i4_sort_a ( i, k, l );

    faces(1:5,4*(tetra-1)+2) = [ a, b, c, 2, tetra ]';

    [ a, b, c ] = i4i4i4_sort_a ( i, j, l );

    faces(1:5,4*(tetra-1)+3) = [ a, b, c, 3, tetra ]';

    [ a, b, c ] = i4i4i4_sort_a ( i, j, k );

    faces(1:5,4*(tetra-1)+4) = [ a, b, c, 4, tetra ]';

  end
%
%  Step 2. Perform an ascending dictionary sort on the neighbor relations.
%  We only intend to sort on rows 1:3; the routine we call here
%  sorts on rows 1 through 5 but that won't hurt us.
%
%  What we need is to find cases where two tetrahedrons share a face.
%  By sorting the columns of the FACES array, we will put shared faces
%  next to each other.
%
  faces = i4col_sort_a ( 5, 4*tetra_num, faces );
%
%  Step 3. Neighboring tetrahedrons show up as consecutive columns with
%  identical first three entries.  Whenever you spot this happening,
%  make the appropriate entries in TETRA_NEIGHBOR.
%
  tetra_neighbor(1:4,1:tetra_num) = -1;

  face = 1;

  while ( 1 )

    if ( 4 * tetra_num <= face )
      break
    end

    if ( faces(1:3,face) == faces(1:3,face+1) )
      face1 = faces(4,face);
      tetra1 = faces(5,face);
      face2 = faces(4,face+1);
      tetra2 = faces(5,face+1);
      tetra_neighbor(face1,tetra1) = tetra2;
      tetra_neighbor(face2,tetra2) = tetra1;
      face = face + 2;
    else
      face = face + 1;
    end

  end

  return
end
function timestamp ( )

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

  return
end


function options = get_nmf_default_options()
% Function to set default options
%
% This file is part of NMFLibrary.
%
% Created by H.Kasai
%

    options.not_store_infos     = false;
    options.metric_type         = 'euc';
    options.metric_param        = [];
    options.max_epoch           = 100;
    options.f_opt               = -Inf;
    options.tol_optgap          = 1.0e-12;
    options.verbose             = 0;
    options.store_sol           = false;
    options.batch_size          = 1;
    options.permute_on          = false;
    options.gnd                 = [];
    options.x_init_robust       = false;
    options.calc_symmetry       = false;
    options.calc_clustering_acc = false;
    options.clustering_gnd      = [];
    options.clustering_classnum = 0;
    options.clustering_eval_num = 5;
    options.disp_freq           = 0;

end


function h = hashmd5(inp)
% Computes the MD5 hash of input data.
%
% function h = hashmd5(inp)
%
% Returns a string containing the MD5 hash of the input variable. The input
% variable may be of any class that can be typecast to uint8 format, which
% is fairly non-restrictive.

% This file is part of Manopt: www.manopt.org.
% This code is a stripped version of more general hashing code by
% Michael Kleder, Nov 2005.
% Change log:
%
%   Aug. 8, 2013 (NB):
%       Made x a static (persistent) variable, in the hope it will speed
%       it up. Furthermore, the function is now Octave compatible.

    is_octave = exist('OCTAVE_VERSION', 'builtin');

    persistent x;
    if isempty(x) && ~is_octave
        x = java.security.MessageDigest.getInstance('MD5');
    end

    inp=inp(:);
    % Convert strings and logicals into uint8 format
    if ischar(inp) || islogical(inp)
        inp=uint8(inp);
    else % Convert everything else into uint8 format without loss of data
        inp=typecast(inp,'uint8');
    end

    % Create hash
    if ~is_octave
        x.update(inp);
        h = typecast(x.digest, 'uint8');
        h = dec2hex(h)';
        % Remote possibility: all hash bytes < 128, so pad:
        if(size(h,1))==1
            h = [repmat('0',[1 size(h,2)]);h];
        end
        h = lower(h(:)');
    else
        h = md5sum(char(inp'), true);
    end

end


function eeg_write_ascii(file,data,format)

% eeg_write_ascii - Write matrix of EEG data into ascii data format
%
% Useage: eeg_write_ascii(file,data,format)
%
% where:    file is the path + filename, eg "c:\data.dat"
%           data is a data matrix (floating point)
%           format is an fprintf format string ('%12.6f' default)
%
% comment:  Uses the fprintf method, which is quicker than the
%           dlmwrite() function. It remains to be seen whether it
%           is quicker or provides more format options than the
%           built-in SAVE function.
%

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

% Licence:  GNU GPL, no express or implied warranties
% History:  07/2001, Darren.Weber_at_radiology.ucsf.edu
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    if ~exist('format','var') format = '%12.6f'; end

    % transpose data for output, see note below
    data = data';

    [r,c] = size(data);         % size of matrix: r rows and c columns

    % create a format string long enough to provide a format for every
    % row of the data - put a line return at the end of this string
    formats = '';
    for i = 1:r
        formats = strcat(formats, ' ', format);
    end
    formats = strcat(formats,'\n');

    % Output data
    fid = fopen(file,'w');  fprintf(fid,formats,data);  fclose(fid);

    fprintf('Completed ascii write to:\t%s\n', file);
    return

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   NOTE on TRANSPOSE
%   this routine transposes in the input data matrix to
%   accommodate the matlab fprintf routine, which outputs in
%   column major format to effectively transpose the input.  For
%   example, 'help fprintf' provides this example:
%
%   x = 0:.1:1; y = [x; exp(x)];
%   fprintf('%6.2f  %12.8f\n',y);
%
%   where y is a 2row, 11 column matrix and the output is:
%
%   0.00    1.00000000
%   0.10    1.10517092
%        ...
%   1.00    2.71828183


%................................................................

function outputDisplacements...
    (displacements,numberNodes,GDof)

% output of displacements in tabular form

disp('Displacements')
jj=1:numberNodes; format
f=[jj; displacements(1:2:GDof)'; displacements(2:2:GDof)'];
fprintf('Node           UX           UY\n')
fprintf('%4d   %10.4e    %10.4e\n',f)


function title = p39_title ( )

%*****************************************************************************80
%
%% P39_TITLE returns a title for problem 39.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 January 2001
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string TITLE, a title for the problem.
%
  title = 'The Bohachevsky Function #2';

  return
end


function [ x, y ] = hand_acquire ( )

%*****************************************************************************80
%
%% HAND_ACQUIRE prompts the user to enter data about the hand shape.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 April 2011
%
%  Author:
%
%    Cleve Moler
%    Modifications by John Burkardt
%
%  Reference:
%
%    Cleve Moler,
%    Numerical Computing with MATLAB,
%    SIAM, 2004,
%    ISBN13: 978-0-898716-60-3,
%    LC: QA297.M625.
%
%  Parameters:
%
%    Output, real X(*), Y(*), the screen coordinates of points selected by the
%    user using mouse clicks.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'HAND_ACQUIRE:\n' );
  fprintf ( 1, '  This function will help you record the shape of your hand\n' );
  fprintf ( 1, '  as a pair of X, Y data vectors.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  In a moment, a blank screen will appear.\n' );
  fprintf ( 1, '  Place your hand on the screen.\n' );
  fprintf ( 1, '  Using the mouse, trace the outline of your hand, clicking\n' );
  fprintf ( 1, '  with the mouse at each point you want to record.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Once you have outlined your hand, press RETURN to save the data.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Press RETURN to begin recording your hand!\n' );

  screen = get ( 0, 'ScreenSize' );
%
%  Specify the location and size of a figure window
%  that takes up the whole screen.
%
  figure ( 'Position', screen );
%
%  Create a graphical coordinate system on the figure.
%
  axes ( 'Position', [ 0, 0, 1, 1 ] );
%
%  Get input from the user.
%
  [ x, y ] = ginput ( );

  n = length ( x );

  printf ( 1, '\n' );
  printf ( 1, '  %d points were recorded.\n' );

  return
end


function data = fetchDaily(symbol,apikey)
% Copyright 2020 The MathWorks, Inc.

url = ['https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=',symbol,'&outputsize=full&apikey=',apikey,'&datatype=json'];

s = webread(url);
fnames = fieldnames(s.TimeSeries_Daily_);
C = struct2cell(s.TimeSeries_Daily_);

for i = 1:length(C)
    Close_Date(i,:) = datetime(fnames{i}(2:end),'InputFormat','yyyy_MM_dd');
    Close_Price(i,:) = str2num(C{i}.x4_Close);
end

data = table(Close_Date,Close_Price);
data = table2timetable(data);


% RGBTOGRAY.m
% -------------------------------------------------------------------
%
% Date:    27/04/2013
% Last modified: 27/04/2013
% -------------------------------------------------------------------

function gray = RGBTOGRAY(img)

    if size(img, 3) ~= 3,
        error('The input should be RGB');
    end

    if ~isinteger(img) && max(img(:)) > 1,
        gray = rgb2gray(uint8(img));
        gray = double(gray);
    else
        gray = rgb2gray(img);
    end

end


function s = ymdf_to_s_republican ( y, m, d, f )

%*****************************************************************************80
%
%% YMDF_TO_S_REPUBLICAN writes a Republican YMDF date into a string.
%
%  Format:
%
%    ER YYYY/MM/DD.FF
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 March 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, M, D, real F, the YMDF date.
%
%    Output, string S, a representation of the date.
%
  s = sprintf ( 'ER %d/%02d/%05.2f', y, m, d + f );

  return
end


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


function pyramid_grid_test ( )

%*****************************************************************************80
%
%% PYRAMID_GRID_TEST tests the PYRAMID_GRID library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 August 2014
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'PYRAMID_GRID_TEST:\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the PYRAMID_GRID library.\n' );

  pyramid_grid_test01 ( );
  pyramid_grid_test02 ( );
  pyramid_grid_test03 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'PYRAMID_GRID_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


%kcknn_printsig 'Print a K-Nearest Neighbors Signature '
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros cknn_printsig.pane file
%
% Parameters:
% InputFile: isig 'Input Signature', required: 'input signature file'
% MultiChoice: omode 'Output Mode', default: 1: 'output mode toggle'
%    Choices are:
%   1: 'Text'
%   2: 'LaTeX'
%   3: 'HTML'
%   4: 'CSV'
% OutputFile: o 'Output', optional: 'Resulting output data object'
%
% Example: o = kcknn_printsig(isig, {'isig','';'omode',1;'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% cknn_printsig - Print a K-Nearest Neighbors Signature
%
%  DESCRIPTION
% This operator prints out the contents of a K-Nearest Neighbors Signature file created with "cknn_signature". It expects a valid K-Nearest Neighbors signature in the parameter [-isig] so its input must be either the output of a \fIcknn_signature\fP or the output of \fIcsigappend\fP which can be used to append signatures of variable size. Its output can be formatted so it can be used in reports, etc. and will be redirected to kstdout unless a file name is passed with the parameter [-o].
% The output of this program can be in four formats, depending on the value of the parameter [-omode] :
% The Text (ASCII) format option ([-omode 1]) formats the output so it can be viewed with simple text editors or in kstdout.
% The LaTeX format option ([-omode 2]) formats the output so it can be included in a LaTeX file with the \\input command.
% The HTML format option ([-omode 3]) formats the output in a HTML table so it can be read into a HTML file.
% The CSV format option ([-omode 4]) formats the output in a Comma-delimited format so it can be read by spreadsheets, etc.
% One of the problems with the generation of LaTeX tables is that a single table is generated, and if there are too many signatures in the input the table will be too big to be displayed in a single page. In this case the user must edit the .tex file and break the table manually.
%
%
%
%  EXAMPLES
% All examples for the Classify toolbox are listed on the Classify Toolbox Manual. For an example of this routine, please see the example workspace Classify:workspaces:KNN-Signatures.
%
%  "SEE ALSO"
% cknn_signature, csigappend
%
%  RESTRICTIONS
% Expect the input file to be a valid signature file for the K-Nearest Neighbors classifier.
%
%  REFERENCES
% All references for the Classify toolbox are listed on the Classify Toolbox Manual.
%
%  COPYRIGHT
% Copyright (C) 1997 Rafael Santos. Khoros (C) Khoral Research, Inc.
%

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

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


function pairsChart(LCO, WTI)
% PAIRSCHART: Shows the full time history for LCO and WTI

% Copyright 2011, The MathWorks, Inc.
% All rights reserved.

plot(LCO(:,1), LCO(:,4), WTI(:,1), WTI(:,4))

datetick('x')
grid on

xlabel('Date')
ylabel('Price (USD)')

title('Intraday prices for LCO and WTI')
legend('LCO', 'WTI', 'Location', 'best')


function [summaryTable, booleanTable, problemTypes, solvers] = getAvailableGAMSSolvers
% This function return the GAMS solvers which are available in your system
% according to the license.
%
% USAGE:
%
%         [summaryTable, booleanTable, problemTypes, solvers] = getAvailableGAMSSolvers
%
% OUTPUTS:
%    summaryTable    Type: cell array
%                    Description: matrix summarizing which problem can be
%                    solved by which solver. A "yes" in position (i,j)
%                    means that the GAMS solver "j" is available in your
%                    system to solve a problem of type "i". Please note
%                    that headers are included in this summaryTable, so the
%                    first column and the first row have labels for solvers
%                    and problem types, respectively.
%    booleanTable    Type: double matrix
%                    Description: matrix summarizing which problem can be
%                    solved by which solver. A "1" in position (i,j) means
%                    that the GAMS solver "j" is available in your system
%                    to solve a problem of type "i"
%    problemTypes    Type: cell array of strings
%                    Description: list of problem types that can be solved
%                    in GAMS. E.g: LP, MIP, etc
%    solvers         Type: cell array of strings
%                    Description: list of solvers available in GAMS
%
% .. Author: - Sebastiian Mendoza, May 30th 2017, Center for Mathematical Modeling, University of Chile, snmendoz@uc.cl

gamsPath = which('gams');  % verify that gams is installed
if isempty(gamsPath)
    error('GAMS is not installed or GAMS path has not been added to MATLAB path.');
end

%verify that licememo.gms in the path of the system
licememoFullPath = which('licememo.gms');
if isempty(licememoFullPath)
    error('licememo.gms in not in MATLAB path.');
end

%copy licememo.gms to the current folder
current = pwd;
if ~strcmp(regexprep(licememoFullPath, {'\\licememo.gms', '/licememo.gms'}, {'', ''}), current)
    copyfile(licememoFullPath);
end

%run licememo.gms
run = system('gams licememo');

%if licememo.gms ran correctly.
if run == 0
    % read the content of the file generated by licememo.gms to find the
    % GAMS solvers available
    fileID = fopen('licememo.txt', 'r');
    summaryTable = cell(2, 2);
    booleanTable = zeros(120, 30);
    tline = fgetl(fileID);
    solvers = {};
    while ischar(tline)
        if strfind(tline,'Solver/Modeltype Matrix:')
            tline = fgetl(fileID); if isempty(tline); tline = fgetl(fileID); end;
            problemTypes = {};
            aux = regexp(tline, ' ', 'split');
            for i = 1:length(aux)
                if ~isempty(aux{i})
                    problemTypes(end + 1) = aux(i);
                end
            end
            nProblemType = length(problemTypes);

            nSolvers = 0;
            tline = fgetl(fileID);
            while ischar(tline)
                solver = regexprep(tline(1:12), ' ', '');
                nSolvers = nSolvers + 1;
                solvers{nSolvers} = solver;
                for i = 1:length(problemTypes)
                    if length(tline) < 12 + 7 * (i - 1)
                        continue;
                    elseif length(tline)>12 + 7 * (i - 1) && length(tline)< 12 + 7 * (i) && ~isempty(regexprep(tline(12 + 7 * (i - 1):end), ' ', ''))
                        summaryTable{nSolvers,i} = 'yes';
                        booleanTable(nSolvers,i) = 1;
                        continue;
                    elseif ~isempty(regexprep(tline(12 + 7 * (i - 1):12 + 7 * i), ' ', ''))
                        summaryTable{nSolvers,i} = 'yes';
                        booleanTable(nSolvers,i) = 1;
                    end
                end
                tline = fgetl(fileID);
            end
            break;
        end
        tline = fgetl(fileID);
    end

    booleanTable = booleanTable(1:nSolvers, 1:nProblemType);
    summaryTable = [{''}, problemTypes; [solvers', summaryTable]];
    fclose(fileID);
    %delete autogenerated file
    delete('licememo.txt')
else

    summaryTable ={};
    booleanTable = 0;
    problemTypes = {};
    solvers = {};
end
%delete autogenerated file and licememo.gms
delete('licememo.gms')
delete('licememo.lst')

end


function dim_num = p00_dim_num ( prob )

%*****************************************************************************80
%
%% P00_DIM_NUM returns the spatial dimension for any problem.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 July 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer PROB, the problem index.
%
%    Output, integer DIM_NUM, the spatial dimension of the
%    dependent variables.
%
  if ( prob == 1 )
    dim_num = p01_dim_num ( );
  elseif ( prob == 2 )
    dim_num = p02_dim_num ( );
  elseif ( prob == 3 )
    dim_num = p03_dim_num ( );
  elseif ( prob == 4 )
    dim_num = p04_dim_num ( );
  elseif ( prob == 5 )
    dim_num = p05_dim_num ( );
  elseif ( prob == 6 )
    dim_num = p06_dim_num ( );
  elseif ( prob == 7 )
    dim_num = p07_dim_num ( );
  elseif ( prob == 8 )
    dim_num = p08_dim_num ( );
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'P00_DIM_NUM - Fatal error!\n' );
    fprintf ( 1, '  Unexpected input value of PROB.\n' );
    error ( 'P00_DIM_NUM - Fatal error!' );
  end

  return
end


function xxdecode = i4_to_xxdecode ( i )

%*****************************************************************************80
%
%% I4_TO_XXDECODE returns the I-th character in the XXDECODE encoding.
%
%  Example:
%
%    I  I4_TO_UUDECODE
%
%    1  '+'
%    2  '-'
%    3  '0'
%   ..
%   64  'z'
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer I, the index of the character.
%    1 <= I <= 64.
%
%    Output, character XXDECODE, the requested character.
%
  string = '+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

  if ( 1 <= i && i <= 64 )
    xxdecode = string(i);
  else
    xxdecode = ' ';
  end

  return
end


function sS = som_vs2to1(sS)

%SOM_VS2TO1 Convert version 2 struct to version 1.
%
% sSold = som_vs2to1(sSnew)
%
%  sMold = som_vs2to1(sMnew);
%  sDold = som_vs2to1(sDnew);
%
%  Input and output arguments:
%   sSnew   (struct) a SOM Toolbox version 2 struct
%   sSold   (struct) a SOM Toolbox version 1 struct
%
% For more help, try 'type som_vs2to1' or check out online documentation.
% See also  SOM_SET, SOM_VS1TO2.

%%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% som_vs2to1
%
% PURPOSE
%
% Converts SOM Toolbox version 2 structs to version 1 structs.
%
% SYNTAX
%
%  sS1 = som_vs2to1(sS2)
%
% DESCRIPTION
%
% This function is offered to allow the change of new map and data structs
% to old ones. There are quite a lot of changes between the versions,
% especially in the map struct, and this function makes it possible to
% use the old functions with new structs.
%
% Note that part of the information is lost in the conversion. Especially,
% training history is lost, and the normalization is, except in the simplest
% cases (like all have 'range' or 'var' normalization) screwed up.
%
% REQUIRED INPUT ARGUMENTS
%
%  sS2       (struct) som SOM Toolbox version 2.0 struct (map, data,
%                     training or normalization struct)
%
% OUTPUT ARGUMENTS
%
%  sS1       (struct) the corresponding SOM Toolbox version 2.0 struct
%
% EXAMPLES
%
%  sM = som_vs2to1(sMnew);
%  sD = som_vs2to1(sDnew);
%  sT = som_vs2to1(sMnew.trainhist(1));
%
% SEE ALSO
%
%  som_set          Set values and create SOM Toolbox structs.
%  som_vs1to2       Transform structs from 1.0 version to 2.0.

% Copyright (c) 1999-2000 by the SOM toolbox programming team.
% http://www.cis.hut.fi/projects/somtoolbox/

% Version 2.0beta juuso 101199

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% check arguments

error(nargchk(1, 1, nargin));   % check no. of input arguments is correct

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% set field values

switch sS.type,
 case 'som_map',
  msize = sS.topol.msize;
  [munits dim] = size(sS.codebook);

  % topology
  if strcmp(sS.topol.shape,'sheet'), shape = 'rect';
  else shape = sS.shape;
  end

  % labels
  labels = cell(munits,1);
  nl = size(sS.labels,2);
  for i=1:munits,
    labels{i} = cell(nl,1);
    for j=1:nl, labels{i}{j} = sS.labels{i,j}; end
  end

  % trainhist
  tl = length(sS.trainhist);
  if tl==0 || strcmp(sS.trainhist(1).algorithm,'lininit'),
    init_type = 'linear';
  else
    init_type = 'random';
  end
  if tl>1,
    for i=2:tl,
      train_seq{i-1} = som_vs2to1(sS.trainhist(i));
    end
    train_type = sS.trainhist(tl).algorithm;
  else
    train_seq = [];
    train_type = 'batch';
  end
  if tl>0, data_name = sS.trainhist(tl).data_name; else data_name = ''; end

  % component normalizations
  sN = convert_normalizations(sS.comp_norm);
  if strcmp(sN.name,'som_hist_norm'),
    sS.codebook = redo_hist_norm(sS.codebook,sS.comp_norm,sN);
  end

  % map
  sSnew = struct('init_type', 'linear', 'train_type', 'batch', 'lattice' ,...
		 'hexa', 'shape', 'rect', 'neigh', 'gaussian', 'msize', msize, ...
		 'train_sequence', [], 'codebook', [], 'labels', [], ...
		 'mask', [], 'data_name', 'unnamed', 'normalization', [], ...
		 'comp_names', [], 'name', 'unnamed');
  sSnew.init_type = init_type;
  sSnew.train_type = train_type;
  sSnew.lattice = sS.topol.lattice;
  sSnew.shape = shape;
  sSnew.neigh = sS.neigh;
  sSnew.msize = sS.topol.msize;
  sSnew.train_sequence = train_seq;
  sSnew.codebook = reshape(sS.codebook,[sS.topol.msize dim]);
  sSnew.labels = labels;
  sSnew.mask = sS.mask;
  sSnew.data_name = data_name;
  sSnew.normalization = sN;
  sSnew.comp_names = sS.comp_names;
  sSnew.name = sS.name;

 case 'som_data',
  [dlen dim] = size(sS.data);

  % component normalizations
  sN = convert_normalizations(sS.comp_norm);
  if strcmp(sN.name,'som_hist_norm'),
    sS.codebook = redo_hist_norm(sS.codebook,sS.comp_norm,sN);
  end

  % data
  sSnew = struct('data', [], 'name', '', 'labels' , [], 'comp_names', ...
		 [], 'normalization', []);
  sSnew.data = sS.data;
  sSnew.name = sS.name;
  sSnew.labels = sS.labels;
  sSnew.comp_names = sS.comp_names;
  sSnew.normalization = sN;

 case 'som_norm',
  sSnew = struct('name','som_var_norm','inv_params',[]);

  switch sS.method,
   case 'var',   sSnew.name = 'som_var_norm';
   case 'range', sSnew.name = 'som_lin_norm';
   case 'histD', sSnew.name = 'som_hist_norm';
   otherwise,
    warning(['Method ' method ' does not exist in version 1.'])
  end

  if strcmp(sS.status,'done'),
    switch sS.method,
     case 'var',
      sSnew.inv_params = zeros(2,1);
      sSnew.inv_params(1) = sS.params(1);
      sSnew.inv_params(2) = sS.params(2);
     case 'range',
      sSnew.inv_params = zeros(2,1);
      sSnew.inv_params(1) = sS.params(1);
      sSnew.inv_params(2) = sS.params(2) + sS.params(1);
     case 'histD',
      bins = length(sS.params);
      sSnew.inv_params = zeros(bins+1,1) + Inf;
      sSnew.inv_params(1:bins,i) = sS.params;
      sSnew.inv_params(end,i) = bins;
    end
  end

 case 'som_train',
  sSnew = struct('algorithm', sS.algorithm, 'radius_ini', ...
		 sS.radius_ini, 'radius_fin', sS.radius_fin, 'alpha_ini', ...
		 sS.alpha_ini, 'alpha_type', sS.alpha_type, 'trainlen', sS.trainlen, ...
		 'qerror', NaN, 'time', sS.time);

 case 'som_topol',
  disp('Version 1 of SOM Toolbox did not have topology structure.\n');

 otherwise,

  error('Unrecognized struct.');
end

sS = sSnew;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% subfunctions

function sN = convert_normalizations(cnorm)

  dim = length(cnorm);
  sN = struct('name','som_var_norm','inv_params',[]);

  % check that there is exactly one normalization per component
  % and that their status and method is the same
  ok = 1;
  nof = zeros(dim,1);
  for i=1:dim, nof(i) = length(cnorm{i}); end
  if any(nof>1), ok=0;
  elseif any(nof==1) && any(nof==0), ok=0;
  elseif any(nof>0),
    status = cnorm{1}.status;
    method = cnorm{1}.method;
    for i=2:dim,
      if ~strcmp(cnorm{i}.status,status) || ~strcmp(cnorm{i}.method,method),
	ok = 0;
      end
    end
  elseif all(nof==0),
    return;
  end
  if ~ok,
    warning(['Normalization could not be converted. All variables can' ...
	     ' only be normalized with a single, and same, method.']);
    return;
  end

  % method name
  switch method,
   case 'var', sN.name = 'som_var_norm';
   case 'range', sN.name = 'som_lin_norm';
   case 'histD', sN.name = 'som_hist_norm';
   otherwise,
    warning(['Normalization could not be converted. Method ' method ...
	     'does not exist in version 1.']);
    return;
  end

  % if not done, inv_params is empty
  if ~strcmp(status,'done'), return; end

  % ok, make the conversion
  switch method,
   case 'var',
    sN.inv_params = zeros(2,dim);
    for i=1:dim,
      sN.inv_params(1,i) = cnorm{i}.params(1);
      sN.inv_params(2,i) = cnorm{i}.params(2);
    end
   case 'range',
    sN.inv_params = zeros(2,dim);
    for i=1:dim,
      sN.inv_params(1,i) = cnorm{i}.params(1);
      sN.inv_params(2,i) = cnorm{i}.params(2) + cnorm{i}.params(1);
    end
   case 'histD',
    bins = zeros(dim,1);
    for i=1:dim, bins(i) = length(cnorm{i}.params); end
    m = max(bins);
    sN.inv_params = zeros(m+1,dim) + Inf;
    for i=1:dim,
      sN.inv_params(1:bins(i),i) = cnorm{i}.params;
      if bins(i)<m, sN.inv_params(bins(i)+1,i) = NaN; end
      sN.inv_params(end,i) = bins(i);
    end
  end

function D = redo_hist_norm(D,cnorm,sN)

  dim = size(D,2);

  % first - undo the new way
  for i=1:dim,
    bins = length(cnorm{i}.params);
    D(:,i) = round(D(:,i)*(bins-1)+1);
    inds = find(~isnan(D(:,i)) & ~isinf(D(:,i)));
    D(inds,i) = cnorm{i}.params(D(inds,i));
  end
  % then - redo the old way
  n_bins = sN.inv_params(size(sN.inv_params,1),:);
  for j = 1:dim,
    for i = 1:size(D, 1)
      if ~isnan(D(i, j)),
	[d ind] = min(abs(D(i, j) - sN.inv_params(1:n_bins(j), j)));
	if (D(i, j) - sN.inv_params(ind, j)) > 0 && ind < n_bins(j),
	  D(i, j) = ind + 1;
	else
	  D(i, j) = ind;
	end
      end
    end
  end
  D = D * sparse(diag(1 ./ n_bins));


sim('pend2');

a = logsout.angles;
f = logsout.force;

figure(5)
plot(a.time, a.data*180/pi)
xlabel('time')
ylabel('angle [degree]')
grid on;

figure(6)
plot(f.time, f.data)
xlabel('time')
ylabel('force [N]')
grid on;


function output = CheckIn(input,array)
[a_rows,a_cols] = size(array);
output = 0;
for i = 1:a_cols
    if input == array(i)
        output = 1;
    end
end


function nedge=savegts(v,f,fname,edges)
%
% nedge=savegts(v,f,fname,edges)
%
% save a surface mesh to GNU Triangulated Surface Format (GTS)
%
% author: Qianqian Fang, <q.fang at neu.edu>
% date: 2011/02/23
%
% input:
%      v: input, surface node list, dimension (nn,3)
%      f: input, surface face element list, dimension (be,3)
%      fname: output file name
%      edges: edge list, if ignored, savegts will compute
%
% output:
%      nedge: the number of unique edges in the mesh
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

fid=fopen(fname,'wt');
if(fid==-1)
    error('You do not have permission to save mesh files.');
end
v=v(:,1:3);
f=f(:,1:3);
[edges,idx,edgemap]=uniqedges(f);
nedge=size(edges,1);

fprintf(fid,'%d %d %d\n',size(v,1),nedge,size(f,1));
fprintf(fid,'%.16f %.16f %.16f\n',v');
fprintf(fid,'%d %d\n',edges');
fprintf(fid,'%d %d %d\n',edgemap');
fclose(fid);


function calpak_test394 ( )

%*****************************************************************************80
%
%% CALPAK_TEST394 tests MONTH_TO_MONTH_NAME_EG_CIVIL.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 April 2013
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CALPAK_TEST394\n' );
  fprintf ( 1, '  For the Egyptian Civil calendar,\n' );
  fprintf ( 1, '  MONTH_TO_MONTH_NAME_EG_CIVIL names the months.\n' );
  fprintf ( 1, '\n' );

  y = 1;
  months = year_length_months_eg_civil ( y );

  for m = 1 : months
    month_name = month_to_month_name_eg_civil ( m );
    fprintf ( 1, '  %2d  %s\n', m, month_name );
  end

  return
end


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

%*****************************************************************************80
%
%% R4MAT_PRINT_SOME prints out a portion of an R4MAT.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns of the matrix.
%
%    Input, 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 j2lo = max ( jlo, 1 ): incx : min ( jhi, n )

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

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

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

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

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

    for i = i2lo : i2hi

      fprintf ( 1, '%7d :', i );

      for j = j2lo : j2hi
        fprintf ( 1, '%12g  ', a(i,j) );
      end

      fprintf ( 1, '\n' );

    end

  end

  return
end


function d = double(npd)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% double(kde) -- evaluates true (1) if the kde is non-empty
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Copyright (C) 2003 Alexander Ihler; distributable under GPL -- see README.txt

  if (npd.N > 0) d = 1;            % return 1 if the density exists
  else d = 0; end;


function nvar = p15_nvar ( option )

%*****************************************************************************80
%
%% P15_NVAR sets the number of variables for problem 15.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 September 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer OPTION, the option index.
%
%    Output, integer NVAR, the number of variables.
%
  nvar = 7;

  return
end


function sub = block(blocks, block_sizes)
% BLOCK Return a vector of subscripts corresponding to the specified blocks.
% sub = block(blocks, block_sizes)
%
% e.g., block([2 5], [2 1 2 1 2]) = [3 7 8].

blocks = blocks(:)';
block_sizes = block_sizes(:)';
skip = [0 cumsum(block_sizes)];
start = skip(blocks)+1;
fin = start + block_sizes(blocks) - 1;
sub = [];
for j=1:length(blocks)
  sub = [sub start(j):fin(j)];
end


function [ t_stop, y_stop ] = p26_stop ( neqn )

%*****************************************************************************80
%
%% P26_STOP returns the stopping point for problem p26.
%
%  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 = [ ...
   -1.294460621213470e+01; ...
   -2.208575158908672e-15 ];

  return
end


function s = SetDefaultParams(s);
% s = SetDefaultParams(s);
% Sets default parameters
% s: user-specified parameters that are used instead of defaults

if (isfield(s, 'gamma') == 0),
    s.gamma = 1;
end

if (isfield(s, 'beta') == 0),
    s.beta = 1;
end

if (isfield(s, 'const_factor') == 0),
    s.const_factor = 40;
end

if (isfield(s, 'type4_rank') == 0),
    s.type4_rank = 5;
end

if (isfield(s, 'thresh') == 0),
   s.thresh = 10e-3;
end

if (isfield(s, 'k') == 0),
    s.k = 4;
end

if (isfield(s, 'max_iters') == 0),
    s.max_iters = 100000;
end


%POSTANIMATE Plot and animate solution.
%
%   [ M ] = POSTANIMATE( PROB, VARARGIN ) Postprocessing function to
%   plot and animate FEATool solutions. PROB is a valid finite element
%   problem struct. If an IMGNAME is given video or frames will be
%   saved in the corresponding IMGFMT (images will be appended with
%   the frame number before the image file extension). Optionally also
%   returns image frames in the struct M that can be played with the
%   movie command. Accepts the following property/value pairs as for
%   postplot and the following additional properties
%
%       Property    Value/{Default}           Description
%       -----------------------------------------------------------------------------------
%       start       integer/{1}               Solution to start animation
%       step        integer/{1}               Step size (positive/negative integer)
%       end         integer/{end}             Solution to end animation
%       pause       scalar/{0}                Pause between frame generation (seconds)
%       imgname     string/{}                 Image/video base filename
%       imgfmt      png,mp4,avi/{jpeg}        Output image/video format
%
% See also POSTPLOT, MOVIE, VIDEOWRITER, PRINT

% Copyright 2013-2022 Precise Simulation, Ltd.


function calpak_test615 ( )

%*****************************************************************************80
%
%% CALPAK_TEST615 tests YEAR_LENGTH_REPUBLICAN.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 April 2013
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CALPAK_TEST615\n' );
  fprintf ( 1, '  For the Republican calendar:\n' );
  fprintf ( 1, '  YEAR_LENGTH_REPUBLICAN determines the length of a year.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Year  Length\n' );
  fprintf ( 1, '\n' );

  for y = 1 : 6
    sy = y_to_s_republican ( y );
    fprintf ( 1, '  %10s  %3d\n', sy, year_length_republican ( y ) );
  end

  return
end


function l=rows(x);
% ROWS
% ROWS(X) returns the number of lines in matrix
i=size(x);
l=i(1,1);


function jed = transition_to_jed_mayan_long ( )

%*****************************************************************************80
%
%% TRANSITION_TO_JED_MAYAN_LONG: Mayan long count calendar transition as a JED.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 December 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real JED, the Julian Ephemeris Date of the date.
%
  jed = 2456282.5;

  return
end


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

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

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

  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' );
    fprintf ( 1, '\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, '%7d  ', a(i,j) );
      end
      fprintf ( 1, '\n' );

    end

  end

  return
end


function u = ic_test01 ( x_num, x, t )

%*****************************************************************************80
%
%% IC_TEST01 sets the initial condition for problem 1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 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 time.
%
%    Output, real U(X_NUM,1), the initial value of U.
%
  u = zeros ( x_num, 1 );

  u(1:x_num,1) = 50.0;

  return
end


function mm_io_test08 ( )

%*****************************************************************************80
%
%% MM_IO_TEST08 tests MM_VALUES_READ.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 November 2008
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'MM_IO_TEST08:\n' );
  fprintf ( 1, '  MM_VALUE_READ reads the value records \n' );
  fprintf ( 1, '  of a Matrix Market file.\n' );

  input_filename = 'mm_io_test07.mm';

  input_unit = fopen ( input_filename );

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

  [ id, type, rep, field, symm ] = mm_header_read ( input_unit );

  while ( 1 )

    comment = mm_comment_read ( input_unit );

    if ( comment == -1 )
      break;
    end

    if ( comment(1) ~= '%' )
      break;
    end

  end
%
%  The COMMENT line is actually the line containing the size information.
%
  [ nrow, ncol, nnz ] = mm_size_read_string ( comment, rep, symm );

  [ indx, jndx, value ] = mm_values_read ( input_unit, rep, field, nnz );

  fclose ( input_unit );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Here is the value information read from the file:\n' );
  fprintf ( 1, '\n' );

  mm_values_print ( rep, field, nnz, indx, jndx, value );

  fprintf ( 1, '\n' );
  fprintf ( 1, 'MM_IO_TEST08:\n' );
  fprintf ( 1, '  The MM file "%s" containing \n', input_filename );
  fprintf ( 1, '  the header, comments, size and values, has been read.\n' );
  fprintf ( 1, '\n' );

  return
end


function bellman_ford_test ( )

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

  bellman_ford_test01 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BELLMAN_FORD_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function LabelAxis(ha, xlbls, ylbls)
%Puts text labels on axis of graph
%example:
%figure(1); plot ([1 2], [4 5]);
%LabelAxis(gca,{'Low' 'Hi'}, {'four' 'five'})

if (~isempty(xlbls) & ~iscellstr(xlbls)),
   fprintf(2,'Need array of cellstrings for x input');
end
if (~isempty(ylbls) & ~iscellstr(ylbls)),
   fprintf(2,'Need array of cellstrings for y input');
end

lx = length(xlbls);
ly = length(ylbls);

if (lx > 0),
   set(ha,'XTick',[1:1:lx]);
   set(ha,'XTickLabel',char(xlbls));
end
if (ly > 0),
   set(ha,'YTick',[1:1:ly]);
   set(ha,'YTickLabel',char(ylbls));
end

return;


% getSizeFromDimensions.m
% Brenden Kadota, Sunnybrook 2022
%
% Description: Helper function for MRSI processing. Takes an MRSI structure and
% cell array of dimension labels and returns their respective sizes.
% If the dimension does not exist, or is empty, set the dimension size to 1.
%
% Input:
%   MRSIStruct = MRSI structure used in FID-A
%   dimensionLabels = cell array of strings of dimension labels (ie. {'t', 'y', 'x'})
%
% Output:
%   dimensionSizes = dimension sizes from labels. Non-existent dimensions set to 1.

function dimensionSizes = getSizeFromDimensions(MRSIStruct, dimensionLabels)
    arguments
        MRSIStruct (1, 1) struct
        dimensionLabels (1, :) cell
    end
    % get dimension numbers from labels
    dimNumbers = getMultipleDimensions(MRSIStruct, dimensionLabels);
    dataSize = getSize(MRSIStruct);

    % get zero dimensions
    zeroIdx = dimNumbers == 0;
    biggerIndex = dimNumbers > length(dataSize);
    nonExistentIndexes = zeroIdx | biggerIndex;

    % get existing dimensions
    nonZeroIndexes = dimNumbers(~nonExistentIndexes);
    sizeOfNonZeroDimensions = dataSize(nonZeroIndexes);

    % initalize
    dimensionSizes = zeros(1, length(dimensionLabels));
    % set non existent dims to 1
    dimensionSizes(nonExistentIndexes) = 1;
    % set existing dimensions
    dimensionSizes(~nonExistentIndexes) = sizeOfNonZeroDimensions;
end


function nvar = p18_nvar ( option )

%*****************************************************************************80
%
%% P18_NVAR sets the number of variables for problem 18.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 September 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer OPTION, the option index.
%
%    Output, integer NVAR, the number of variables.
%
  nvar = 12;

  return
end


function [cMap]=turbo(varargin)

% function [cMap]=turbo(n)
% ------------------------------------------------------------------------
% Creates the colormap data for the turbo colormap.
%
% This colormap is a MATLAB implementation of the matplotlib turbo colormap
%
% Kevin Mattheus Moerman
% gibbon.toolbox@gmail.com
%
% 2020/08/25
%------------------------------------------------------------------------

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

%%

[cMap]=matplotlibColormap('turbo',n);

%%
% _*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 plots(d,xp,yp,hyper,methods)

% PLOTS  plotting for spider
%
% plots(d,xp,yp,[hyper],[methods])
%
% Inputs:
%
%  d          -- results in group of data objects
%  xp,yp      -- x-axis and y-axis variables, can be hyperparameters
%                of algorithms, or the type of loss, e.g xp='C', y='class_loss'
%  hyper      -- string of hyperparameters
%  methods    -- cell array of strings of names methods of interest
%
% Hyperparameters:
%  scatter=0      -- set to 1 for a scatter plot, otherwise tries to draw lines
%  log_scale=0    -- if set to 1 tries to guess when to use a log scale
%  logs=[0 0]     -- set to 1 for x-axis (1st component) or y-axis (2nd)
%                    to be on a log scale
%  no_error_bar=0 -- set to 1 to not draw error bars when given std. dev.
%  ax=[]          -- if nonempty calls axis(ax) to set axis dimensions
%
%  colors=['bkrgymcrgbdkym']          -- default colors to cycle through
%  dots= {'-*','--o','-.',':'};       -- default line styles
%  scats={'*','o','.','+','x','d','s'};- default scatter plot styles
%
% Examples:
%  r=train(cv(param(svm(kernel('rbf')),'rbf',2.^[-5:5])),gen(toy('l=60')));
%  plots(get_mean(r),'rbf','class_loss','log_scale')
%  plots(r,'fold','class_loss')
%
%  [tr a]=train( chain({ param(toy,'l',[10:10:100])  group({svm knn}) }) )
%  r=test(a); plots(r,'l','class_loss')

if nargin<3 yp='class_loss'; end;
if nargin<4 hyper=[]; end;
if nargin<5 methods=[]; end;

d=group(group2cell(d));
if (~isempty(findstr(xp,'loss')) | ~isempty(findstr(yp,'loss')) )
  if isempty(findstr(d.child{1}.name,'loss'))
    disp('[assuming class_loss]');
    d=loss(d,'class_loss');
  end
end

%% ------------------ basic defaults -------------------------
clf
colors=['bkrgymcrgbdkym'];
dots={'-*','--o','-.',':'};
scats={'*','o','.','+','x','d','s'};
assume=1;                      % make assumptions on methods and losses
scatter=0;                     % scatter plot
no_error_bars=0;
log_scale=0; logs=[];
xname=xp; yname=yp;
leg_pos=0; leg_txt=[];
ax=[];
%% ------------------- intelligent defaults -------------------
if strcmp(xp,'fold') | strcmp(yp,'fold') assume=0; scatter=1; end;

% labeling and titles
if strcmp(xname,'feat') xname='features'; end;
if strcmp(yname,'feat') yname='features'; end;
xname(xname=='_')=' '; yname(yname=='_')=' ';
%% ------------------------------------------------------------
evalobject=0;
eval_hyper;             %% evalute hyper params
%% ------------------------------------------------------------

%if nargin<2 calc_loss=1; loss_type='default'; else calc_loss=1; end;
%if isempty(loss_type) calc_loss=0; end;

d=d.child; dx=d; dy=d;

[m o t u a ind]=get_methods(d);
if isempty(methods) methods=m; end;
m=[]; for i=1:length(methods)
  methods{i}(methods{i}=='_')='-';
  m=[m ' ' methods{i}]; end;
disp(['[assuming methods:' m ']']);
if isempty(leg_txt)
  leg_txt=methods;
  leg_err_txt=[];
  for i=1:length(methods)
    leg_err_txt{(i-1)*2+1}=[methods{i} ' error bars'];
    leg_err_txt{(i-1)*2+2}=[methods{i} ];
  end
end;

%if assume & ~isempty(strmatch('cv',u)) & strmatch('fold',t{1})
% dx=get_mean(dx); dy=get_mean(dy);
%end

%if length(dx)~=length(dy)  %% problem: grouping occured in one, not the other
%  if length(dx)<length(dy) dy=dx; else dx=dy; end;
%end

m=length(methods); % number of methods
r=[]; index=[];
for i=[1:m]
  x=[];y=[]; xe=[]; ye=[];
  for k=[1:length(dy)]
   if a(k,ind(i))      %% if method i is used in data k this is TRUE

     x1=get_data_value(dx{k},xp);
     y1=get_data_value(dy{k},yp);

     if ~isempty(x1) & ~isempty(y1)
       %% error bars
       xe1=0;ye1=0;
       if size(x1,2)>1 xe1=x1(1,2); x1=x1(1,1); end;
       if size(y1,2)>1 ye1=y1(1,2); y1=y1(1,1); end;
       xe=[xe xe1]; ye=[ye ye1];
       x=[x x1]; y=[y y1];
     end
   end
  end
  if i==1
    hold off;
    if log_scale & isempty(logs)   %% log scale stuff
       if max(x)>10 logs(1)=1; end;
       if max(y)>10 logs(2)=1; end;
    end
    if length(logs)<2 logs(2)=0; end;
  end;
  if logs(1) x=log(x); end; if logs(2) y=log(y); end;

  c=colors(mod(i-1,length(colors))+1);
  if ~scatter
   d=dots{mod(i-1,length(dots))+1};
  else
   d=scats{mod(i-1,length(scats))+1};
  end
  if sum(ye)==0 | no_error_bars
    plot(x,y,[c d ]); hold on;
  else
    errorbar2(x,y,ye,-ye,[c d ]); hold on;
    leg_txt=leg_err_txt;
  end
end

if logs(1) xname=['log ' xname]; end;
if logs(2) yname=['log ' yname]; end;
xlabel(xname); ylabel(yname);

legend(char(leg_txt),leg_pos);
if ~isempty(ax) axis(ax); end;

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

function val=get_data_value(d,v)

vv=length(v);
if  vv>4 & ~isempty(strcmp('_loss',v(vv-5:vv)))
  val=d.Y;
else
  v=[v '=']; n=d.name;
  f=max(findstr(n,v))+length(v);
  if isempty(f) val=[]; return; end;
  p=[];
  while 1
    if f>length(n) break; end;
    if n(f)~='=' & n(f)~=' '
      p=[p n(f)];
    else
      break;
    end
    f=f+1;
  end
  val=str2num(p);
end