text:
function pyramid_exactness ( quad_filename, degree_max )

%*****************************************************************************80
%
%% MAIN is the main program for PYRAMID_EXACTNESS.
%
%  Discussion:
%
%    This program investigates the polynomial exactness of a quadrature
%    rule for the pyramid.
%
%    The integration region is:
%
%      - ( 1 - Z ) <= X <= 1 - Z
%      - ( 1 - Z ) <= Y <= 1 - Z
%                0 <= Z <= 1.
%
%    When Z is zero, the integration region is a square lying in the (X,Y)
%    plane, centered at (0,0,0) with "radius" 1.  As Z increases to 1, the
%    radius of the square diminishes, and when Z reaches 1, the square has
%    contracted to the single point (0,0,1).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 July 2009
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'PYRAMID_EXACTNESS\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Investigate the polynomial exactness of\n' );
  fprintf ( 1, '  a quadrature rule for the pyramid.\n' );
%
%  Get the quadrature file root name:
%
  if ( 1 <= nargin )

  else

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

    quad_filename = input ( '  Enter the "root" name of the quadrature files.' );

  end
%
%  Create the names of:
%    the quadrature X file;
%    the quadrature W file;
%
  quad_x_filename = strcat ( quad_filename, '_x.txt' );
  quad_w_filename = strcat ( quad_filename, '_w.txt' );
%
%  The second command line argument is the maximum degree.
%
  if ( 2 <= nargin )

  else

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

    degree_max = input ( '  Please enter the maximum total degree to check.' );

  end
%
%  Summarize the input.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'PYRAMID_EXACTNESS: User input:\n' );
  fprintf ( 1, '  Quadrature rule X file = "%s".\n', quad_x_filename );
  fprintf ( 1, '  Quadrature rule W file = "%s".\n', quad_w_filename );
  fprintf ( 1, '  Maximum total degree to check = %d', degree_max );
%
%  Read the X file.
%
  [ dim_num, order ] = r8mat_header_read ( quad_x_filename );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Spatial dimension = %d\n', dim_num );
  fprintf ( 1, '  Number of points  = %d\n', order );

  if ( dim_num ~= 3 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'PYRAMID_EXACTNESS - Fatal error!\n' );
    fprintf ( 1, '  The quadrature abscissas must be 3 dimensional.\n' );
    error ( 'PYRAMID_EXACTNESS - Fatal error!' );
  end

  x = r8mat_data_read ( quad_x_filename, dim_num, order );
%
%  Read the W file.
%
  [ dim_num2, order2 ] = r8mat_header_read ( quad_w_filename );

  if ( dim_num2 ~= 1 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'PYRAMID_EXACTNESS - Fatal error!\n' );
    fprintf ( 1, '  The quadrature weight file should have exactly\n');
    fprintf ( 1, '  one value on each line.\n' );
    error ( 'PYRAMID_EXACTNESS - Fatal error!' );
  end

  if ( order2 ~= order )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'PYRAMID_EXACTNESS - Fatal error!\n' );
    fprintf ( 1, '  The quadrature weight file should have exactly\n' );
    fprintf ( 1, '  the same number of lines as the abscissa file.\n' );
    error ( 'PYRAMID_EXACTNESS - Fatal error!' );
  end

  w = r8mat_data_read ( quad_w_filename, 1, order );
%
%  Explore the monomials.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '      Error    Degree  Exponents\n' );
  fprintf ( 1, '\n' );

  for degree = 0 : degree_max

    expon = [];
    more = 0;
    h = 0;
    t = 0;

    while ( 1 )

      [ expon, more, h, t ] = comp_next ( degree, dim_num, expon, more, h, t );

      v = monomial_value ( dim_num, order, expon, x );

      quad = pyra_unit_volume ( ) * w(1:order) * v(1:order)';

      exact = pyra_unit_monomial ( expon );

      quad_error = abs ( quad - exact );

      fprintf ( 1, '  %24.16f   %2d  ', quad_error, degree );
      for dim = 1 : dim_num
        fprintf ( 1, '%3d', expon(dim) );
      end
      fprintf ( 1, '\n' );

      if ( ~more )
        break
      end

    end

    fprintf ( 1, '\n' );

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

  return
end
function [ a, more, h, t ] = comp_next ( n, k, a, more, h, t )

%*****************************************************************************80
%
%% COMP_NEXT computes the compositions of the integer N into K parts.
%
%  Discussion:
%
%    A composition of the integer N into K parts is an ordered sequence
%    of K nonnegative integers which sum to N.  The compositions (1,2,1)
%    and (1,1,2) are considered to be distinct.
%
%    The routine computes one composition on each call until there are no more.
%    For instance, one composition of 6 into 3 parts is
%    3+2+1, another would be 6+0+0.
%
%    On the first call to this routine, set MORE = FALSE.  The routine
%    will compute the first element in the sequence of compositions, and
%    return it, as well as setting MORE = TRUE.  If more compositions
%    are desired, call again, and again.  Each time, the routine will
%    return with a new composition.
%
%    However, when the LAST composition in the sequence is computed
%    and returned, the routine will reset MORE to FALSE, signaling that
%    the end of the sequence has been reached.
%
%    This routine originally used a SAVE statement to maintain the
%    variables H and T.  I have decided that it is safer
%    to pass these variables as arguments, even though the user should
%    never alter them.  This allows this routine to safely shuffle
%    between several ongoing calculations.
%
%    There are 28 compositions of 6 into three parts.  This routine will
%    produce those compositions in the following order:
%
%     I         A
%     -     ---------
%     1     6   0   0
%     2     5   1   0
%     3     4   2   0
%     4     3   3   0
%     5     2   4   0
%     6     1   5   0
%     7     0   6   0
%     8     5   0   1
%     9     4   1   1
%    10     3   2   1
%    11     2   3   1
%    12     1   4   1
%    13     0   5   1
%    14     4   0   2
%    15     3   1   2
%    16     2   2   2
%    17     1   3   2
%    18     0   4   2
%    19     3   0   3
%    20     2   1   3
%    21     1   2   3
%    22     0   3   3
%    23     2   0   4
%    24     1   1   4
%    25     0   2   4
%    26     1   0   5
%    27     0   1   5
%    28     0   0   6
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 July 2008
%
%  Author:
%
%    FORTRAN77 original version by Albert Nijenhuis and Herbert Wilf
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Albert Nijenhuis, Herbert Wilf,
%    Combinatorial Algorithms for Computers and Calculators,
%    Second Edition,
%    Academic Press, 1978,
%    ISBN: 0-12-519260-6,
%    LC: QA164.N54.
%
%  Parameters:
%
%    Input, integer N, the integer whose compositions are desired.
%
%    Input, integer K, the number of parts in the composition.
%
%    Input, integer A(K), the previous composition.  On the first call,
%    with MORE = FALSE, set A = [].  Thereafter, A should be the
%    value of A output from the previous call.
%
%    Input, logical MORE.  The input value of MORE on the first
%    call should be FALSE, which tells the program to initialize.
%    On subsequent calls, MORE should be TRUE, or simply the
%    output value of MORE from the previous call.
%
%    Input, integer H, T, two internal parameters needed for the
%    computation.  The user may need to initialize these before the
%    very first call, but these initial values are not important.
%    The user should not alter these parameters once the computation
%    begins.
%
%    Output, integer A(K), the next composition.
%
%    Output, logical MORE, will be TRUE unless the composition
%    that is being returned is the final one in the sequence.
%
%    Output, integer H, T, the updated values of the two internal
%    parameters.
%
  if ( ~more )

    t = n;
    h = 0;
    a(1) = n;
    a(2:k) = 0;

  else

    if ( 1 < t )
      h = 0;
    end

    h = h + 1;
    t = a(h);
    a(h) = 0;
    a(1) = t - 1;
    a(h+1) = a(h+1) + 1;

  end

  more = ( a(k) ~= n );

  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 value = monomial_value ( dim_num, point_num, expon, x )

%*****************************************************************************80
%
%% MONOMIAL_VALUE evaluates a monomial.
%
%  Discussion:
%
%    This routine evaluates a monomial of the form
%
%      product ( 1 <= dim <= dim_num ) x(dim)^expon(dim)
%
%    where the exponents are nonnegative integers.  Note that
%    if the combination 0^0 is encountered, it should be treated
%    as 1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    05 May 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer DIM_NUM, the spatial dimension.
%
%    Input, integer POINT_NUM, the number of points at which the
%    monomial is to be evaluated.
%
%    Input, integer EXPON(DIM_NUM), the exponents.
%
%    Input, real X(DIM_NUM,POINT_NUM), the point coordinates.
%
%    Output, real VALUE(POINT_NUM), the value of the monomial.
%
  value(1:point_num) = 1.0;

  for dim = 1 : dim_num
    if ( 0 ~= expon(dim) )
      value(1:point_num) = value(1:point_num) .* x(dim,1:point_num).^expon(dim);
    end
  end

  return
end
function value = pyra_unit_monomial ( expon )

%*****************************************************************************80
%
%% PYRA_UNIT_MONOMIAL: monomial integral in a unit pyramid.
%
%  Discussion:
%
%    This routine returns the integral of
%
%      product ( 1 <= I <= 3 ) X(I)^EXPON(I)
%
%    over the unit pyramid.
%
%    The unit pyramid is defined as:
%
%    - ( 1 - Z ) <= X <= 1 - Z
%    - ( 1 - Z ) <= Y <= 1 - Z
%              0 <= Z <= 1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2008
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Arthur Stroud,
%    Approximate Calculation of Multiple Integrals,
%    Prentice Hall, 1971,
%    ISBN: 0130438936,
%    LC: QA311.S85.
%
%  Parameters:
%
%    Input, integer EXPON(3), the exponents.
%
%    Output, real VALUE, the integral of the monomial.
%
  value = 0.0;

  if ( mod ( expon(1), 2 ) == 0 && mod ( expon(2), 2 ) == 0 )

    i_hi = 2 + expon(1) + expon(2);

    for i = 0 : i_hi
      value = value + r8_mop ( i ) * r8_choose ( i_hi, i ) / ( i + expon(3) + 1 );
    end

    value = value * 2.0 / ( expon(1) + 1 ) * 2.0 / ( expon(2) + 1 );

  end

  return
end
function value = pyra_unit_volume ( )

%*****************************************************************************80
%
%% PYRA_UNIT_VOLUME_3D returns the volume of a unit pyramid.
%
%  Discussion:
%
%    A pyramid with square base can be regarded as the upper half of a
%    3D octahedron.
%
%    The integration region:
%
%      - ( 1 - Z ) <= X <= 1 - Z
%      - ( 1 - Z ) <= Y <= 1 - Z
%                0 <= Z <= 1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    31 March 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real VALUE, the volume of the pyramid.
%
  value = 4.0 / 3.0;

  return
end
function value = r8_choose ( n, k )

%*****************************************************************************80
%
%% R8_CHOOSE computes the binomial coefficient C(N,K).
%
%  Discussion:
%
%    The value is calculated in such a way as to avoid overflow and
%    roundoff.  The calculation is done in integer arithmetic.
%
%    The formula used is:
%
%      C(N,K) = N! / ( K! * (N-K)! )
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    31 March
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    ML Wolfson, HV Wright,
%    Algorithm 160:
%    Combinatorial of M Things Taken N at a Time,
%    Communications of the ACM,
%    Volume 6, Number 4, April 1963, page 161.
%
%  Parameters:
%
%    Input, integer N, K, are the values of N and K.
%
%    Output, real VALUE, the number of combinations of N
%    things taken K at a time.
%
  mn = min ( k, n - k );

  if ( mn < 0 )
    value = 0;
  elseif ( mn == 0 )
    value = 1;
  else
    mx = max ( k, n - k );
    value = mx + 1;
    for i = 2 : mn
      value = ( value * ( mx + i ) ) / i;
    end
  end

  return
end
function value = r8_mop ( i )

%*****************************************************************************80
%
%% R8_MOP returns the I-th power of -1 as an R8 value.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 November 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer I, the power of -1.
%
%    Output, real R8_MOP, the I-th power of -1.
%
  if ( mod ( i, 2 ) == 0 )
    value = + 1.0;
  else
    value = - 1.0;
  end

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

%*****************************************************************************80
%
%% R8MAT_DATA_READ reads data from an R8MAT file.
%
%  Discussion:
%
%    An R8MAT is an array of R8's.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    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 of data.
%
%    Output, real 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, ' %f' );
  end

  input_unit = fopen ( input_filename );

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

  i = 0;

  while ( i < n )

    line = fgets ( input_unit );

    if ( line == -1 )
      break;
    end

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

    elseif ( s_len_trim ( line ) == 0 )

    else

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

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

    end

  end

  fclose ( input_unit );

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

%*****************************************************************************80
%
%% R8MAT_HEADER_READ reads the header from an R8MAT file.
%
%  Discussion:
%
%    An R8MAT is an array of R8's.
%
%  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, 'R8MAT_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, 'R8MAT_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 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 timestamp ( )

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

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function folds = create_folds(N, k_folds)

prev_rng = seed_rand();

perm = randperm(N);
fold_points = floor(linspace(1, N, k_folds+1));
fold_points(end) = N+1;
folds = cell(k_folds, 1);
for i = 1:k_folds
  folds{i} = perm(fold_points(i):fold_points(i+1)-1);
end
assert(isempty(setdiff(1:N, cat(2, folds{:}))));

rng(prev_rng);

author: rbgirshick

repo: rcnn

save_path: github-repos/MATLAB/rbgirshick-rcnn


text:
% POP_JOINTPROB - reject artifacts in an EEG dataset using joint
%                   probability of the recorded electrode or component
%                   activities observed at each time point.  e.g., Observing
%                   large absolute values at most electrodes or components
%                   is improbable and may well mark the presence of artifact.
% Usage:
%   >> pop_jointprob( INEEG, typerej) % pop-up interactive window mode
%   >> [OUTEEG, locthresh, globthresh, nrej] = ...
%		= pop_jointprob( INEEG, typerej, elec_comp, ...
%                   locthresh, globthresh, superpose, reject, vistype);
%
% Graphic interface:
%   "Electrode|Component" - [edit box] electrodes or components indices to take
%                 into consideration for rejection. Same as the 'elec_comp'
%                 parameter in the command line call (see below).
%   "Single-channel limit|Single-component limit" - [edit box] activity
%                 probability limit(s) (in  std. dev.) Sets the 'locthresh'
%                  command line parameter. If more than one, defined individual
%                 electrode|channel limits. If fewer values than the number
%                 of electrodes|components specified above, the last input
%                 value is used for all remaining electrodes|components.
%   "All-channel limit|All-component limit" - [edit box] activity probability
%                 limit(s) (in std. dev.) for all channels (grouped).
%                 Sets the 'globthresh' command line parameter.
%   "visualization type" - [popup menu] can be either 'REJECTRIALS'|'EEGPLOT'.
%                 This correspond to the command line input option 'vistype'
%   "Display with previous rejection(s)" - [checkbox] This checkbox set the
%                 command line input option 'superpose'.
%   "Reject marked trial(s)" - [checkbox] This checkbox set the command
%                  line input option 'reject'.
% Inputs:
%   INEEG      - input dataset
%   typerej    - [1|0] data to reject on (0 = component activations;
%              1 = electrode data). {Default: 1 = electrode data}.
%   elec_comp  - [n1 n2 ...] electrode|component number(s) to take into
%              consideration for rejection
%   locthresh  - activity probability limit(s) (in std. dev.) See "Single-
%              channel limit(s)" above.
%   globthresh - global limit(s) (all activities grouped) (in std. dev.)
%   superpose  - [0|1] 0 = Do not superpose rejection marks on previously
%              marks stored in the dataset: 1 = Show both current and
%              previous marks using different colors. {Default: 0}.
%   reject     - 0 = do not reject marked trials (but store the marks:
%              1 = reject marked trials {Default: 1}.
%   vistype    - Visualization type. [0] calls REJSTATEPOCH and [1] calls
%              EEGPLOT default is [0].When added to the command line
%              call it will not display the plots if the option 'plotflag'
%              is not set.
% topcommand   - [] Deprecated argument , keep to ensure backward compatibility
% plotflag     - [1,0] [1]Turns plots 'on' from command line, [0] off.
%              (Note for developers: When called from command line
%              it will make 'calldisp = plotflag') {Default: 0}
%
% Outputs:
%   OUTEEG     - output dataset with updated joint probability array
%   locthresh  - electrodes probability of activity thresholds in terms
%              of standard-dev.
%   globthresh - global threshold (where all electrode activity are
%              regrouped).
%   nrej       - number of rejected sweeps
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: JOINTPROB, REJSTATEPOCH, EEGPLOT, EEGLAB, POP_REJEPOCH

% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

% 01-25-02 reformated help & license -ad
% 03-07-02 added srate argument to eegplot call -ad
% 03-08-02 add eeglab options -ad

function [EEG, locthresh, globthresh, nrej, com] = pop_jointprob( EEG, icacomp, elecrange, ...
                       		locthresh, globthresh, superpose, reject, vistype, topcommand,plotflag);
nrej = []; com = '';
if nargin < 1
   help pop_jointprob;
   return;
end;
if nargin < 2
   icacomp = 1;
end;

if icacomp == 0
	if isempty( EEG.icasphere )
	    ButtonName=questdlg( 'Do you want to run ICA now ?', ...
                         'Confirmation', 'NO', 'YES', 'YES');
    	switch ButtonName,
        	case 'NO', disp('Operation cancelled'); return;
        	case 'YES', [ EEG com ] = pop_runica(EEG);
    	end % switch
	end
end;
if exist('reject') ~= 1
    reject = 1;
end

if nargin < 3

    % which set to save
    % -----------------
    promptstr   = { [ fastif(icacomp, 'Electrode', 'Component') ' (indices; Ex: 2 6:8 10):' ], ...
                    [ fastif(icacomp, 'Single-channel', 'Single-component') ' limit(s) (std. dev(s).: Ex: 2 2 2.5):'], ...
                    [ fastif(icacomp, 'All-channel', 'All-component') ' limit(s) (std. dev(s).: Ex: 2 2.1 2):'], ...
                    'Visualization type',...
                    'Display previous rejection marks', ...
                    'Reject marked trial(s)'};

    inistr = { fastif(icacomp, ['1:' int2str(EEG.nbchan)], ['1:' int2str(size(EEG.icaweights,1))])...
               fastif(icacomp, '3', '5'),  ...
               fastif(icacomp, '3', '5'), ...
               '',...
               '1', ...
               '0'};

    vismodelist= {'REJECTTRIALS','EEGPLOT'};
    g1  = [1 0.1 0.75];
    g2 = [1 0.26 0.9];
    g3 = [1 0.22 0.85];
    geometry = {g1 g1 g1 g2 [1] g3 g3};

    uilist = {...
              { 'Style', 'text', 'string', promptstr{1}} {} { 'Style','edit'      , 'string' ,inistr{1} 'tag' 'cpnum'}...
              { 'Style', 'text', 'string', promptstr{2}} {} { 'Style','edit'      , 'string' ,inistr{2} 'tag' 'singlelimit'}...
              { 'Style', 'text', 'string', promptstr{3}} {} { 'Style','edit'      , 'string' ,inistr{3} 'tag' 'alllimit'}...
              { 'Style', 'text', 'string', promptstr{4}} {} { 'Style','popupmenu' , 'string' , vismodelist 'tag' 'specmethod' 'value' 2 }...
              {}...
              { 'Style', 'text', 'string', promptstr{5}} {} { 'Style','checkbox'  ,'string'  , ' ' 'value' str2double(inistr{5}) 'tag','rejmarks' }...
              { 'Style', 'text', 'string', promptstr{6}} {} { 'Style','checkbox'  ,'string'  ,' ' 'value'  str2double(inistr{6})  'tag' 'rejtrials'} ...
              };
    figname = fastif( ~icacomp, 'Reject. improbable comp. -- pop_jointprob()', 'Reject improbable data -- pop_jointprob()');
    result = inputgui( geometry,uilist,'pophelp(''pop_jointprob'');', figname);

    size_result  = size( result );
    if size_result(1) == 0, locthresh = []; globthresh = []; return; end
    elecrange    = result{1};
    locthresh    = result{2};
    globthresh   = result{3};
    switch result{4}, case 1, vistype=0; otherwise, vistype=1; end
    superpose    = result{5};
    reject       = result{6};

end

if ~exist('vistype'  ,'var'), vistype   = 0; end
if ~exist('reject'   ,'var'), reject    = 0; end
if ~exist('superpose','var'), superpose = 1; end

if ischar(elecrange) % convert arguments if they are in text format
    calldisp = 1;
	elecrange  = eval( [ '[' elecrange ']'  ]  );
	locthresh  = eval( [ '[' locthresh ']'  ]  );
	globthresh = eval( [ '[' globthresh ']' ]  );
else
    calldisp = 0;
end

if exist('plotflag','var') && ismember(plotflag,[1,0])
    calldisp = plotflag;
else
    plotflag = 0;
end

if isempty(elecrange)
	error('No electrode selectionned');
end;

% compute the joint probability
% -----------------------------
if icacomp == 1
	fprintf('Computing joint probability for channels...\n');
    tmpdata = eeg_getdatact(EEG);
    if isempty(EEG.stats.jpE)
		[ EEG.stats.jpE rejE ] = jointprob( tmpdata, locthresh, EEG.stats.jpE, 1);
	end
	[ tmp rejEtmp ] = jointprob( tmpdata(elecrange,:,:), locthresh, EEG.stats.jpE(elecrange,:), 1);
    rejE    = zeros(EEG.nbchan, size(rejEtmp,2));
	rejE(elecrange,:) = rejEtmp;

	fprintf('Computing all-channel probability...\n');
	tmpdata2 = permute(tmpdata, [3 1 2]);
	tmpdata2 = reshape(tmpdata2, size(tmpdata2,1), size(tmpdata2,2)*size(tmpdata2,3));
	[ EEG.stats.jp rej ] = jointprob( tmpdata2, globthresh, EEG.stats.jp, 1);
    clear tmpdata2;
else
    tmpdata = eeg_getica(EEG);
	fprintf('Computing joint probability for components...\n');
    if isempty(EEG.stats.icajpE)
		[ EEG.stats.icajpE rejE ] = jointprob( tmpdata, locthresh, EEG.stats.icajpE, 1);
	end
	[ tmp rejEtmp ] = jointprob( tmpdata(elecrange,:), locthresh, EEG.stats.icajpE(elecrange,:), 1);
    rejE    = zeros(size(tmpdata,1), size(rejEtmp,2));
	rejE(elecrange,:) = rejEtmp;

	fprintf('Computing global joint probability...\n');
	tmpdata2 = permute(tmpdata, [3 1 2]);
	tmpdata2 = reshape(tmpdata2, size(tmpdata2,1), size(tmpdata2,2)*size(tmpdata2,3));
	[ EEG.stats.icajp  rej] = jointprob( tmpdata2, globthresh, EEG.stats.icajp, 1);
	clear tmpdata2;
end
rej = rej' | max(rejE, [], 1);
fprintf('%d/%d trials marked for rejection\n', sum(rej), EEG.trials);

if calldisp
	if vistype == 1 % EEGPLOT -------------------------
	    if icacomp == 1 macrorej  = 'EEG.reject.rejjp';
	        			macrorejE = 'EEG.reject.rejjpE';
	    else			macrorej  = 'EEG.reject.icarejjp';
	        			macrorejE = 'EEG.reject.icarejjpE';
	    end
		colrej = EEG.reject.rejjpcol;
		eeg_rejmacro; % script macro for generating command and old rejection arrays

	    if icacomp == 1
	        eegplot( tmpdata(elecrange,:,:), 'srate', ...
		      EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:});
	    else
	        eegplot( tmpdata(elecrange,:,:), 'srate', ...
		      EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:});
	    end;
    else % REJECTRIALS -------------------------
	  	if icacomp	== 1
			[ rej, rejE, n, locthresh, globthresh] = ...
				rejstatepoch( tmpdata(elecrange,:,:), EEG.stats.jpE(elecrange,:), 'global', 'on', 'rejglob', EEG.stats.jp, ...
						'threshold', locthresh, 'thresholdg', globthresh, 'normalize', 'off'  );
		else
			[ rej, rejE, n, locthresh, globthresh] = ...
				rejstatepoch( tmpdata(elecrange,:,:), EEG.stats.icajpE(elecrange,:), 'global', 'on', 'rejglob', EEG.stats.icajp, ...
						'threshold', locthresh, 'thresholdg', globthresh, 'normalize', 'off' );
		end;
		nrej = n;
	end;
else
	% compute rejection locally
	rejtmp = max(rejE(elecrange,:),[],1);
	rej = rejtmp | rej;
	nrej =  sum(rej);
	fprintf('%d trials marked for rejection\n', nrej);
    if reject
        EEG = pop_rejepoch(EEG, rej, 0);
    end
end
if ~isempty(rej)
	if icacomp	== 1
		EEG.reject.rejjp = rej;
		EEG.reject.rejjpE = rejE;
	else
		EEG.reject.icarejjp = rej;
		EEG.reject.icarejjpE = rejE;
	end
end
nrej = sum(rej);

com = [ com sprintf('EEG = pop_jointprob(EEG,%s);', ...
		vararg2str({icacomp,elecrange,locthresh,globthresh,superpose,reject & ~calldisp, vistype, [],plotflag})) ];
if nargin < 3 && nargout == 2
	locthresh = com;
end

return;

author: sccn

repo: eeglab

save_path: github-repos/MATLAB/sccn-eeglab


text:
function [r] = volume2radius(V)
% volume2radius returns the radius of a sphere of volume V.
% Chad Greene 2012
r = (3*V/(4*pi)).^(1/3);

author: Sable

repo: mcbench-benchmarks


text:
function varargout = size( F, varargin )
%SIZE   Size of a BALLFUN.
%   S = SIZE(F) returns the size of the tensor of expansion coefficients
%   for F, where S = [m,n,p] for an mxnxp tensor of coefficients.
%
%   [M, N, P] = SIZE(F) is the same as S = SIZE(F) with S = [M, N, P].

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

if isempty( F )
    S = [];
else
    % Grab dimensions of underlying coefficient tensor:
    S = size( F.coeffs );

    % If F.coeffs is a matrix, then it has one fiber:
    if ( numel( S ) == 2 )
        S(3) = 1;
    end
end

% Prepare output:
if ( nargout <= 1 )
    if nargin > 1
        S = S(varargin{1});
    end
    varargout = { S };
else
    varargout = { S(1), S(2), S(3) };
end
end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


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

%%begin

% In the field of robotics there are many possible ways of representing
% positions and orientations, but the homogeneous transformation is well
% matched to MATLABs powerful tools for matrix manipulation.
%
% Homogeneous transformations describe the relationships between Cartesian
% coordinate frames in terms of translation and orientation.

%  A pure translation of 0.5m in the X direction is represented by

transl(0.5, 0.0, 0.0)

% a rotation of 90degrees about the Y axis by

troty(pi/2)

% and a rotation of -90degrees about the Z axis by

trotz(-pi/2)

%  these may be concatenated by multiplication

t = transl(0.5, 0.0, 0.0) * troty(pi/2) * trotz(-pi/2)

%
% If this transformation represented the origin of a new coordinate frame with respect
% to the world frame origin (0, 0, 0), that new origin would be given by

t * [0 0 0 1]'

% the orientation of the new coordinate frame may be expressed in terms of
% Euler angles

tr2eul(t)

% or roll/pitch/yaw angles

tr2rpy(t)

% It is important to note that tranform multiplication is in general not
% commutative as shown by the following example

trotx(pi/2) * trotz(-pi/8)
trotz(-pi/8) * trotx(pi/2)

author: petercorke

repo: robotics-toolbox-matlab


text:
function v = cvxtuple( varargin )

if nargin == 1,
    v = varargin{1};
    switch class( v ),
        case 'struct',
            if numel( v ) ~= 1,
                error( 'struct arrays not permitted in cvx tuple objects.' );
            end
        case 'cell',
            v = reshape( v, 1, numel( v ) );
        otherwise,
            return
    end
else
    v = varargin;
end

v = class( struct( 'value_', { v } ), 'cvxtuple', cvxobj );

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.

repo: REST


text:
function [sUnitVector, OUnitVector, vInfMag] = computeHyperSVectOVect(hSMA, hEcc, hInc, hRAAN, hArg, hTA, gmu)
%computeHyperSVectOVect Summary of this function goes here
%   Detailed explanation goes here
    [hRVect,hVVect]=getStatefromKepler(hSMA, hEcc, hInc, hRAAN, hArg, hTA, gmu);
    hHat = normVector(cross(hRVect, hVVect));

    flyByAngle=2*asin(1/hEcc);
    SigmaAngle=pi/2 - flyByAngle/2;
    hUnitVector=hHat;
    eVector=(norm(hVVect)^2/gmu - 1/norm(hRVect))*hRVect - (dot(hRVect,hVVect)/gmu)*hVVect;
    eUnitVect=eVector/norm(eVector);
    sUnitVector=cos(SigmaAngle)*eUnitVect + sin(SigmaAngle)*cross(hUnitVector,eUnitVect);
    BUnitVector=cross(sUnitVector,hUnitVector)/norm(cross(sUnitVector,hUnitVector));
    OUnitVector=cos(flyByAngle)*sUnitVector - sin(flyByAngle)*BUnitVector;

    sUnitVector = real(sUnitVector);
    OUnitVector = real(OUnitVector);

    vInfMag = sqrt(-gmu/hSMA);
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
classdef KalmanFilter < handle
    %KALMANFILTER  Kalman filter class
    %
    % The class implements a standard
    % [Kalman filter](https://en.wikipedia.org/wiki/Kalman_filter), [Welch95].
    % However, you can modify `transitionMatrix`, `controlMatrix`, and
    % `measurementMatrix` to get an extended Kalman filter functionality.
    %
    % ## Example
    %
    %     % initialization
    %     kf = cv.KalmanFilter(4,2);
    %     kf.statePre = [10;20;0;0]; % initial state prediction
    %     kf.transitionMatrix = [1,0,1,0; 0,1,0,1; 0,0,1,0; 0,0,0,1];
    %     kf.measurementMatrix([1,4]) = 1;
    %     kf.processNoiseCov = eye(4) * 1e-4;
    %     kf.measurementNoiseCov = eye(2) * 1e-1;
    %     kf.errorCovPost = eye(4) * 0.1;
    %
    %     % dynamics
    %     p_pred = kf.predict();       % update internal state
    %     measure = [11;21];           % measurement
    %     p_est = kf.correct(measure); % correct
    %
    % ## References
    % [Welch95]:
    % > Greg Welch and Gary Bishop. An introduction to the kalman filter, 1995.
    % > [PDF](http://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf)
    %
    % See also: cv.KalmanFilter.init, cv.KalmanFilter.predict,
    %  cv.KalmanFilter.correct, vision.KalmanFilter
    %

    properties (SetAccess = private)
        % Object ID
        id
    end

    properties (Dependent)
        % predicted state `(x'(k)): x(k)=A*x(k-1)+B*u(k)`
        statePre
        % corrected state `(x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k))`
        statePost
        % state transition matrix `(A)`
        transitionMatrix
        % control matrix `(B)` (not used if there is no control)
        controlMatrix
        % measurement matrix `(H)`
        measurementMatrix
        % process noise covariance matrix `(Q)`
        processNoiseCov
        % measurement noise covariance matrix `(R)`
        measurementNoiseCov
        % priori error estimate covariance matrix
        % `(P'(k)): P'(k)=A*P(k-1)*At + Q`
        errorCovPre
        % Kalman gain matrix `(K(k)): K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R`)
        gain
        % posteriori error estimate covariance matrix
        % `(P(k)): P(k)=(I-K(k)*H)*P'(k)`
        errorCovPost
    end

    methods
        function this = KalmanFilter(varargin)
            %KALMANFILTER  KalmanFilter constructor
            %
            %     kf = cv.KalmanFilter()
            %     kf = cv.KalmanFilter(dynamParams, measureParams)
            %     kf = cv.KalmanFilter(..., 'OptionName', optionValue, ...)
            %
            % ## Input
            % * __dynamParams__ Dimensionality of the state.
            % * __measureParams__ Dimensionality of the measurement.
            %
            % ## Options
            % * __ControlParams__ Dimensionality of the control vector.
            %   default 0
            % * __Type__ Type of the created matrices that should be `single`
            %   or `double`. default `single`
            %
            % The constructor invokes the cv.KalmanFilter.init method to
            % initialize the object with the passed parameters.
            %
            % See also: cv.KalmanFilter, cv.KalmanFilter.init
            %
            this.id = KalmanFilter_(0, 'new');
            if nargin>0, this.init(varargin{:}); end
        end

        function delete(this)
            %DELETE  Destructor
            %
            %     kf.delete()
            %
            % See also: cv.KalmanFilter
            %
            if isempty(this.id), return; end
            KalmanFilter_(this.id, 'delete');
        end

        function init(this, dynamParams, measureParams, varargin)
            %INIT  Re-initializes Kalman filter. The previous content is destroyed
            %
            %     kf.init(dynamParams, measureParams)
            %     kf.init(..., 'OptionName', optionValue, ...)
            %
            % ## Input
            % * __dynamParams__ Dimensionality of the state.
            % * __measureParams__ Dimensionality of the measurement.
            %
            % ## Options
            % * __ControlParams__ Dimensionality of the control vector.
            %   default 0
            % * __Type__ Type of the created matrices that should be `single`
            %   or `double` (default).
            %
            % See also: cv.KalmanFilter.KalmanFilter
            %
            KalmanFilter_(this.id, 'init', dynamParams, measureParams, varargin{:});
        end

        function s = predict(this, varargin)
            %PREDICT  Computes a predicted state
            %
            %     s = kf.predict('OptionName', optionValue, ...)
            %
            % ## Output
            % * __s__ Output predicted state.
            %
            % ## Options
            % * __Control__ The optional input control. Not set by default
            %
            % See also: cv.KalmanFilter.correct
            %
            s = KalmanFilter_(this.id, 'predict', varargin{:});
        end

        function s = correct(this, measurement)
            %CORRECT  Updates the predicted state from the measurement
            %
            %     s = kf.correct(measurement)
            %
            % ## Input
            % * __measurement__ The measured system parameters.
            %
            % ## Output
            % * __s__ Output corrected state.
            %
            % See also: cv.KalmanFilter.predict
            %
            s = KalmanFilter_(this.id, 'correct', measurement);
        end
    end

    %% Getters/Setters
    methods
        function value = get.statePre(this)
            value = KalmanFilter_(this.id, 'get', 'statePre');
        end
        function set.statePre(this, value)
            KalmanFilter_(this.id, 'set', 'statePre', value);
        end

        function value = get.statePost(this)
            value = KalmanFilter_(this.id, 'get', 'statePost');
        end
        function set.statePost(this, value)
            KalmanFilter_(this.id, 'set', 'statePost', value);
        end

        function value = get.transitionMatrix(this)
            value = KalmanFilter_(this.id, 'get', 'transitionMatrix');
        end
        function set.transitionMatrix(this, value)
            KalmanFilter_(this.id, 'set', 'transitionMatrix', value);
        end

        function value = get.controlMatrix(this)
            value = KalmanFilter_(this.id, 'get', 'controlMatrix');
        end
        function set.controlMatrix(this, value)
            KalmanFilter_(this.id, 'set', 'controlMatrix', value);
        end

        function value = get.measurementMatrix(this)
            value = KalmanFilter_(this.id, 'get', 'measurementMatrix');
        end
        function set.measurementMatrix(this, value)
            KalmanFilter_(this.id, 'set', 'measurementMatrix', value);
        end

        function value = get.processNoiseCov(this)
            value = KalmanFilter_(this.id, 'get', 'processNoiseCov');
        end
        function set.processNoiseCov(this, value)
            KalmanFilter_(this.id, 'set', 'processNoiseCov', value);
        end

        function value = get.measurementNoiseCov(this)
            value = KalmanFilter_(this.id, 'get', 'measurementNoiseCov');
        end
        function set.measurementNoiseCov(this, value)
            KalmanFilter_(this.id, 'set', 'measurementNoiseCov', value);
        end

        function value = get.errorCovPre(this)
            value = KalmanFilter_(this.id, 'get', 'errorCovPre');
        end
        function set.errorCovPre(this, value)
            KalmanFilter_(this.id, 'set', 'errorCovPre', value);
        end

        function value = get.gain(this)
            value = KalmanFilter_(this.id, 'get', 'gain');
        end
        function set.gain(this, value)
            KalmanFilter_(this.id, 'set', 'gain', value);
        end

        function value = get.errorCovPost(this)
            value = KalmanFilter_(this.id, 'get', 'errorCovPost');
        end
        function set.errorCovPost(this, value)
            KalmanFilter_(this.id, 'set', 'errorCovPost', value);
        end
    end

end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
function varargout=spm_help(varargin)
% SPM help and manual facilities
% FORMAT spm_help
%_______________________________________________________________________
%  ___  ____  __  __
% / __)(  _ \(  \/  )
% \__ \ )___/ )    (   Statistical Parametric Mapping
% (___/(__)  (_/\/\_)  SPM - http://www.fil.ion.ucl.ac.uk/spm/
%
%_______________________________________________________________________
%
% SEE ALSO:   spm.man      - "About SPM"
%
% The "Help" facilities are about software and implementation. The
% underlying mathematics, concepts and operational equations have been
% (or will be) published in the peer reviewed literature and the
% interested user is referred to these sources. An intermediate
% theoretical exposition is given in the SPM course notes. This and
% other resources are available via the SPM Web site. Visit
% http://www.fil.ion.ucl.ac.uk/spm/, or press the "SPMweb" button on the
% spm_help toolbar.
%
%-----------------------------------------------------------------------
%
% spm_help sets up a GUI help system for the SPM package.
% `spm_help('Topic')` or `spm_help Topic` displays the help for a
% particular topic in the SPM help window.
%
% Help topics are displayed in a special help window. Initially, a
% representation of the SPM Menu window is drawn. Clicking buttons in
% this representation leads to the help pages for the appropriate
% topic.
%
% The SPM Help ToolBar contains controls for the help system.
%
%  ---  Routines and manual pages (generically referred to as help
%       "topics") referenced by the currently displayed help file are
%       listed in the "Referenced Topics..." pull-down menu on the help
%       interface. Selecting a routine there displays it's help
%       information.
%
%  ---  Alternatively, a specific function name can be entered into
%       the lilac editable text widget in the help window toolbar.
%       Its help will be displayed.
%
%  ---  As the tree of routines is explored, the "Previous Topics"
%       pulldown menu keeps track of recently visited help topics,
%       allowing easy backtracking and exploration of the "tree" of SPM
%       functions and dependencies.
%
% Special topic buttons lead to "About SPM", "Menu", and "Help" topics.
% "About SPM" displays the introduction file for this version of SPM.
% "Menu" displays the help representation of the SPM Menu window.
% "Help" displays this file.
%
% Multi-page help files are displayed by the help facility with pagination
% controls at the bottom right of the Graphics window.
%
% The print button enables printing to the specified Print device. This
% is set in the Defaults area, initially to a PostScript file
% "spm*.ps" in the current directory. Multi page topics are paged on
% screen, and printed page by page.
%
%
%-----------------------------------------------------------------------
% The SPM package provides help at three levels, the first two being
% available via the SPM graphical help system:
%
% (i)   Manual pages on specific topics.
%       These give an overview of specific components or topics its
%       relation to other components, the inputs and outputs and
%       references to further information.
%
%       Many of the buttons in the help menu window lead to such "man"
%       pages.  These are contained in ASCII files named spm_*.man.
%       These can be viewed on the MATLAB command line with the `help`
%       command, e.g. `help spm_help` prints out this manual file in
%       the MATLAB command window.
%
% (ii)  Help information for each routine within SPM (E.g. This is the).
%       help information for spm_help.m - the help function.)
%       This help information is the help header of the actual MATLAB
%       function, and can be displayed on the command line with the
%       `help` command, e.g. `help spm_help`.
%
%       Commented header text from that spm_*.m file is displayed in the
%       following format:
%
%        A one line description
%        FORMAT [outputs] = spm_routine(inputs);
%        inputs  -  the input arguments
%        outputs -  the output arguments
%        A short paragraph detailing what the routine does and other
%        pertinent information
%        ref:  citations
%
% (iii) SPM is (mainly) implemented as MATLAB functions and scripts.
%       These are ASCII files named spm_*.m, which can be viewed in the
%       MATLAB command window with the `type` command, e.g. `type
%       spm_help`, or read in a text editor.
%
%  ---  MATLAB syntax is very similar to standard matrix notation that
%       would be found in much of the literature on matrices. In this
%       sense the SPM routines can be used (with MATLAB) for data
%       analysis, or they can be regarded as the ultimate pseudocode
%       specification of the underlying ideas.
%
%  ---  The coding is concise but clear, and annotated with comments
%       where necessary.
%
% In addition, the MATLAB help system provides keyword searching
% through the H1 lines (the first comment line) of the help entries of
% *all* M-files found on MATLABPATH. This can be used to identify
% routines from keywords. Type `help lookfor` in the MATLAB command
% window for further details.
%
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Andrew Holmes, Karl Friston
% $Id$

%=======================================================================
% - FORMAT specifications for embedded CallBack functions
%=======================================================================
%( This is a multi function function, the first argument is an action  )
%( string, specifying the particular action function to take. Recall   )
%( MATLAB's command-function duality: `spm_help MenuWin` is equivalent )
%( to `spm_help('MenuWin')`.                                           )
%
% FORMAT spm_help
% Makes Help window visible if there is one around. Otherwise
% defaults to spm_help('!Topic','MenuWin').
%
% FORMAT spm_help('Topic')
% Defaults to spm_help('!Topic','Topic').
%
% FORMAT spm_help('!Quit')
% Hides the Help window.
% (Re)Shows the welcome splash screen if it exists.
%
% FORMAT spm_help('!DrawMenuWin')
% Draws representation of Menu window in help window, with button
% CallBacks for the appropriate help topics.
%
% FORMAT [S,Err] = spm_help('!ShortTopics',Topic)
% Returns help text (as a string) for special topics. If the topic is
% not found then S contains an error topic, and Err is true.
% Topic     - Special internal help topic
% S         - String vector containing help topic
% Err       - True if the topic is not found
%
% FORMAT spm_help('!Topic',Topic)
% Topic     - Help topic: Either name of file from which to display help,
%             or name of an internal help topic
%             Defaults to the "MenuWin" topic. (See '!ShortTopics')
% Loads file Topic (which must be on the MATLABPATH), parses it for
% references to other spm_* routines, puts these in the Help ToolBars
% "Referenced routines" pulldown (with callbacks to display their
% help), and sets up the "Previous topics" pulldown. Puts Topic in the
% editable topic window on the ToolBar. Then calls spm_help('!Disp') to
% display the help portion of the file.
% Special internal topics are tried if Topic file doesn't exist.
% "MenuWin" Topic prints a short message and displays the help
% representation of the Menu window.
%
% FORMAT spm_help('!Disp',Fname,S,F)
% Fname     - Name of file from which to display help
% S         - [Optional] String vector containing a previously read in
%             contents of file Fname
% F         - Figure to use
% Displays the help for the given file in the Help window (creating
% one if required). Paginates and provides paging buttons if necessary.
%
% FORMAT F = spm_help('!Create')
% F        - Handle of figure created
% Creates central Help window 'Tag'ged 'Help', with Help ToolBar
%
% FORMAT F = spm_help('!CreateHelpWin')
% F        - Handle of figure created
% Creates central Help window 'Tag'ged 'Help'. If one already exists
% then it's handle is returned.
%
% FORMAT spm_help('!CreateBar',F)
% F        - Handle (or 'Tag') of window to use. Defaults to 'Help'.
% Creates Help ToolBar.
%
% spm_help('!Clear',F)
% F        - Handle (or 'Tag') of window to use. Defaults to 'Help'.
% Clears help window, leaving ToolBar intact. Any 'HelpMenu' objects
% (with 'UserData' 'HelpMenu') are merely hidden, to speed up
% subsequent use.
%
% FORMAT h = spm_help('!ContextHelp',Topic)
% Sets up a small green "?" help symbol in the bottom right corner of
% the SPM Interactive window with callback to spm_help('Topic'). If SPM
% is in CommandLine mode then an appropriate message is printed in the
% MATLAB command window.
% Topic     - Help topic [defaults to name of calling function]
% h         - handle of "?" text (or 0 if CmdLine)
%_______________________________________________________________________

%-Condition arguments
%-----------------------------------------------------------------------
%-All actions begin '!' - Other (string) actions are topics
if nargin==0 || isempty(varargin{1})
    Fhelp = spm_figure('FindWin','Help');
    if ~isempty(Fhelp), set(Fhelp,'Visible','on')
    else spm_help('!Topic','MenuWin'), end
    return
elseif varargin{1}(1)~='!'
    spm_help('!Topic',varargin{:}), return
end

switch lower(varargin{1}), case '!quit'
%=======================================================================
Fhelp   = spm_figure('FindWin','Help');
set(Fhelp,'Visible','off')

case '!drawmenuwin'
%=======================================================================
% Fhelp = spm_help('!DrawMenuWin');

%-Find help window
%-----------------------------------------------------------------------
Fhelp = spm_figure('FindWin','Help');
if isempty(Fhelp), error('No Help window'), end

%-If there's already a HelpMenu then show it and return
H = findobj(Fhelp,'Tag','HelpMenu');
if ~isempty(H), set(H,'Visible','on'), return, end

%-Create window frame
%-----------------------------------------------------------------------
S      = get(Fhelp,'Position');       %-Help window position
WS     = [S(3)/600 S(4)/865 S(3)/600 S(4)/865];  %-Window scaling factors
%FS    = spm('FontSizes');            %-Scaled font sizes
PF     = spm_platform('fonts');       %-Font names (for this platform)
SPMver = spm('Ver');                  %-SPM version
O      = [170 050 000 000].*WS;       %-Offset for MenuWin plot

%-Button to emulate window title bar, frames to emulate window
%-----------------------------------------------------------------------
uicontrol(Fhelp,'Style','PushButton','String',['About ',SPMver],...
    'ForegroundColor',[0 0 0.9],...
    'ToolTipString','about this release of SPM [spm.man]',...
    'CallBack','spm_help(''spm.man'')',...
    'Position',[-4,447,406,30].*WS+O,...
    'Tag','HelpMenu')

uicontrol(Fhelp,'Style','Frame',...
    'Position',[-2,-3,404,450].*WS+O,...
    'Tag','HelpMenu')
uicontrol(Fhelp,'Style','Frame',...
    'Position',[0,0,400,445].*WS+O,...
    'Tag','HelpMenu',...
    'BackgroundColor',[1,1,1]*.8)

%-Frames & text
%-----------------------------------------------------------------------
Fmenu  = spm_figure('Findwin','Menu');
C      = get(Fmenu,'Children');
modality = spm('CheckModality');
for i = length(C):-1:1
    units = get(C(i),'Units');
    funits = get(C(i),'FontUnits');
    set(C(i),'Units','pixels');
    set(C(i),'FontUnits','points');
    c = get(C(i));
    set(C(i),'Units',units);
    set(C(i),'FontUnits',funits);

    % modality-specific help
    if isempty(c.Tag) || strcmp(c.Tag, 'frame') || ~isempty(strfind(c.Tag, modality))
        if strcmp(c.Type,'uicontrol')

            if ischar(c.UserData)
                Callback = sprintf('spm_help(''%s'')',c.UserData);
            else
                Callback = '';
            end

            uicontrol(Fhelp,...
                'BackgroundColor',c.BackgroundColor,...
                'Callback',  Callback,...
                'Enable',c.Enable,...
                'FontAngle',c.FontAngle,...
                'FontName',c.FontName,...
                'FontSize',c.FontSize,...
                'ForegroundColor',c.ForegroundColor,...
                'HorizontalAlignment',c.HorizontalAlignment,...
                'Units',c.Units,...
                'Position',c.Position + O,...
                'String',c.String,...
                'Style',c.Style,...
                'Tag', 'HelpMenu',...
                'TooltipString',c.TooltipString,...
                'Visible','on',...
                'Interruptible','on');
        end
    end
end

%-Special topics
%-----------------------------------------------------------------------
uicontrol(Fhelp,'Style','Frame','Position',[-145-2,-3,132+4,474+5].*WS+O,...
    'Tag','HelpMenu')
uicontrol(Fhelp,'Style','Frame','Position',[-145,0,132,474].*WS+O,...
    'Tag','HelpMenu',...
    'BackgroundColor',[1,1,1]*.8)
uicontrol(Fhelp,'Style','Text','String','special topics...',...
    'ForegroundColor','w','BackGroundColor',[1,1,1]*.8,...
    'FontName',PF.times,'FontAngle','Italic','FontWeight','Bold',...
    'HorizontalAlignment','Center',...
    'Position',[-133-5 447-10 110+10 30].*WS+O,...
    'Tag','HelpMenu')
uicontrol(Fhelp,'String','Data format','ForegroundColor','b',...
    'ToolTipString',...
    'about the image format used by SPM [spm_format.man]',...
    'Position',[-133 410 110 30].*WS+O,...
    'CallBack','spm_help(''spm_format.man'')',...
    'Tag','HelpMenu','Interruptible','on')
uicontrol(Fhelp,'String','Templates','ForegroundColor','b',...
    'ToolTipString',...
    'templates and other data [spm_templates.man]',...
    'Position',[-133 370 110 30].*WS+O,...
    'CallBack','spm_help(''spm_templates.man'')',...
    'Tag','HelpMenu','Interruptible','on')
uicontrol(Fhelp,'String','','ForegroundColor','b',...
    'ToolTipString','',...
    'Position',[-133 330 110 30].*WS+O,...
    'CallBack','',...
    'Enable','off',...
    'Tag','HelpMenu','Interruptible','on')
uicontrol(Fhelp,'String','','ForegroundColor','b',...
    'ToolTipString','',...
    'Position',[-133 290 110 30].*WS+O,...
    'CallBack','',...
    'Enable','off',...
    'Tag','HelpMenu','Interruptible','on')
uicontrol(Fhelp,'String','','ForegroundColor','b',...
    'ToolTipString','',...
    'Position',[-133 250 110 30].*WS+O,...
    'CallBack','',...
    'Enable','off',...
    'Tag','HelpMenu','Interruptible','on')
uicontrol(Fhelp,'String','','ForegroundColor','b',...
    'ToolTipString','',...
    'Position',[-133 210 110 30].*WS+O,...
    'CallBack','',...
    'Enable','off',...
    'Tag','HelpMenu','Interruptible','on')
uicontrol(Fhelp,'String','','ForegroundColor','b',...
    'ToolTipString','',...
    'Position',[-133 170 110 30].*WS+O,...
    'CallBack','',...
    'Enable','off',...
    'Tag','HelpMenu','Interruptible','on')
uicontrol(Fhelp,'String','','ForegroundColor','b',...
    'ToolTipString','',...
    'Position',[-133 130 110 30].*WS+O,...
    'CallBack','',...
    'Enable','off',...
    'Tag','HelpMenu','Interruptible','on')
uicontrol(Fhelp,'String','Random FX','ForegroundColor','b',...
    'ToolTipString','about implementing random effects analyses in SPM [spm_RandFX.man]',...
    'Position',[-133 090 110 30].*WS+O,...
    'CallBack','spm_help(''spm_RandFX.man'')',...
    'Tag','HelpMenu','Interruptible','on')
uicontrol(Fhelp,'String','','ForegroundColor','b',...
    'ToolTipString','',...
    'Position',[-133 050 110 30].*WS+O,...
    'CallBack','',...
    'Enable','off',...
    'Tag','HelpMenu','Interruptible','on')
uicontrol(Fhelp,'String','SPM motd','ForegroundColor','b',...
    'ToolTipString','SPM startup "message of the day"',...
    'Position',[-133 010 110 30].*WS+O,...
    'CallBack','spm_help(''spm_motd.man'')',...
    'Tag','HelpMenu','Interruptible','on')

uicontrol(Fhelp,'String','Copyright (c) Wellcome Trust Centre for NeuroImaging',...
    'ForegroundColor',[1 1 1]*.6,'BackgroundColor','w',...
    'ToolTipString','Copyleft information',...
    'FontName',PF.times,'FontSize',8,...
    'Position',[-145 -030 549 015].*WS+O,...
    'CallBack','spm_help(''spm_LICENCE.man'')',...
    'Tag','HelpMenu','Interruptible','on')

case '!shorttopics'
%=======================================================================
% [S,Err] = spm_help('!ShortTopics',Topic)
if nargin<2, Topic='!Topics'; else Topic=varargin{2}; end

Usep = sprintf('%%%s',repmat('_',1,71));
Err = 0;

if strcmp(Topic,'!Topics')
    S = 'MenuWin';
elseif strcmp(Topic,'spm_motd.man')
    S = sprintf([...
        '\n%% %s : Message of the Day\n',...
        '%s\n%%\n',...
        '%% No message of the day has been set.\n',...
        '%%\n',...
        '%% File spm_motd.man can contain the message, which is',...
            ' displayed at startup\n',...
        '%% if it exists.\n',...
        '%s\n%%\n%% The FIL methods group\n'],...
        spm('Ver'),Usep,Usep);
elseif strcmp(Topic,'MenuWin')
    S = sprintf([...
        '\n%% %s : Statistical Parametric Mapping\n',...
        '%s\n%%\n',...
        '%% SPM functions are called from the main SPM Menu ',...
            'window.\n',...
        '%% Click the buttons in the representation below ',...
            'for help on that topic...\n',...
        '%%\n',...
        '%% Click on "Help" for information on SPM documentation, ',...
            'and instructions\n',...
        '%% on using the SPM help system.\n',...
        '%s\n%%\n%% The FIL methods group\n'],...
        spm('Ver'),Usep,Usep);
elseif strcmp(Topic,'SPM_Modality')
    S = sprintf([...
        '\n%% SPM Modality switch\n',...
        '%s\n%%\n',...
        '%% The modality switch on the SPM Menu interface ',...
            'allows switching\n',...
        '%% between PET/SPECT and fMRI modalities on the fly,',...
            'without re-starting SPM\n',...
        '%%\n',...
        '%% Operating the switch sets the MODALITY global ',...
            'variable,\n',...
        '%% sets the package defaults to those specified for ',...
            'the current modality\n',...
        '%% and changes the interface so that the appropriate ',...
            'routines\n',...
        '%% lie behind the buttons.\n',...
        '%%\n',...
        '%% See also: spm.m spm_defaults.m\n',...
        '%s\n%%\n%% Andrew Holmes\n'],Usep,Usep);
elseif strcmp(Topic,'MenuWin_Toolboxes_PullDown')
    S = sprintf([...
        '\n%% SPM Menu window: Toolboxes button\n',...
        '%s\n%%\n',...
        '%% The Toolboxes pulldown provides access to SPM ',...
            'toolboxes installed in\n',...
        '%% the toolbox subdirectory of the SPM installation ',...
            'directory.\n',...
        '%%\n',...
        '%% SPM toolboxes are defined as the contents of sub-',...
            'directories of\n',...
        '%% fullfile(spm(''Dir''),''toolbox'') - the ''toolbox'' ',...
            'subdirectory of the SPM\n',...
        '%% directory. For SPM to pick a toolbox up, there must be ',...
            'a single mfile\n',...
        '%% in the directory whose name ends with the toolbox ',...
            'directory name. (I.e.\n',...
        '%% A toolbox called "test" would be in the "test" ',...
            'subdirectory of\n',...
        '%% spm(''Dir''), with a single file named *test.m.) This ',...
            'M-file is\n',...
        '%% regarded as the launch file for the toolbox.\n',...
        '%%\n',...
        '%% On selecting the toolbox from the pulldown menu, the ',...
            'toolbox directory\n',...
        '%% is prepended to the MATLAB path (unless it is already ',...
            'on the path), and\n',...
        '%% the toolbox launch program executed (with no ',...
            'arguments).\n',...
        '%%\n',...
        '%% For help on specific toolboxes, refer to the toolbox ',...
            'itself.\n',...
        '%%\n',...
        '%% The toolbox directory for this installation of SPM is:\n',...
        '%%     %s\n',...
        '%%\n',...
        '%% SPM toolboxes are only identified at SPM startup.\n',...
        '%%\n',...
        '%% If there are no toolboxes installed, then the button ',...
            'is disabled.\n',...
        '%%\n',...
        '%% See spm.m for programmers help with toolbox handling.\n',...
        '%s\n%%\n%% Andrew Holmes\n'],...
        Usep,fullfile(spm('Dir'),'toolbox'),Usep);
elseif strcmp(Topic,'MenuWin_Utils_PullDown')
    S = sprintf([...
        '\n%% SPM Menu window: PullDown menu of utilities...\n',...
        '%s\n%%\n',...
        '%% 1) CD:        Calls spm_get prompting for a directory,\n',...
        '%%               and changes directory to it.\n',...
        '%% 2) PWD:       Reports the present working directory.\n',...
        '%%               \n',...
        '%% 3) delete:    GUI file deletion utility:\n',...
        '%%               Prompts for files to delete using',...
            ' spm_get.\n',...
        '%%               Seeks confirmation before deleting\n.',...
        '%%               List of deleted files reported in MATLAB',...
            ' command window.\n',...
        '%% 4) Show SPM:  Pops up all the figures for this SPM',...
            ' session.\n',...
        '%%               Typing "spm show" in the MATLAB command',...
            ' window has the\n',...
        '%%               same effect.\n',...
        '%% 5) Run mFile: Prompts for selection of a MATLAB M-file',...
            ' (script or function with\n',...
        '%%               no arguments), which is then run in the',...
            ' base workspace.\n',...
        '%% 6) SPMweb:    Opens http://www.fil.ion.ucl.ac.uk/spm/',...
            ' in your web browser.\n',...
        '%%               See MATLAB `web` command for details.\n',...
        '%s\n%%\n%% Andrew Holmes\n'],Usep,Usep);
elseif strcmp(Topic,'QuitSPM')
    S = sprintf([...
        '\n%% Quit SPM and cleanup the MATLAB workspace\n',...
        '%s\n%%\n',...
        '%% Closes all windows, clears workspace variables,',...
            ' global variables\n',...
        '%% compiled functions and MEX links. This leaves',...
            ' MATLAB in "startup" condition\n',...
        '%% except that it doesn''t release the memory claimed',...
            ' during the session.\n',...
        '%% You need to `quit` MATLAB to release it''s memory.',...
            ' It is advisable to do.\n',...
        '%% reasonably frequently, especially after large',...
            ' analyses.\n',...
        '%%\n',...
        '%% It is *not* necessary to quit SPM after an SPM error.',...
            ' Simply `clear` the \n',...
        '%% workspace (type `clear` in the MATLAB command window)',...
            ' and clear the\n',...
        '%% "Results" and "Interactive" with the `clear` button',...
            ' in the "Results" window.\n',...
        '%% (SPMs defaults are held as global variables.)\n',...
        '%%\n',...
        '%% The `Close` button in the "Help" window merely hides',...
            ' the SPMhelp window.\n',...
        '%%\n',...
        '%s\n%%\n%% The FIL methods group\n'],Usep,Usep);
else
    doc = spm_jobman('help',Topic);
    if ~isempty(doc),
        doc = char(doc{:});
        doc = [repmat('% ',size(doc,1),1) doc repmat(sprintf('\n'),size(doc,1),1)]';
        S   = doc(:)';
    else
        S = sprintf([...
            '\n%% ! - Topic not found\n',...
            '%s\n%%\n',...
            '%% This topic is not recognised by the help system.\n',...
            '%s\n%%\n'],Usep,Usep);
        Err = 1;
    end
end
varargout = {S,Err};

case '!topic'
%=======================================================================
% spm_help('!Topic',Topic)
if nargin<2, Topic='MenuWin'; else Topic=varargin{2}; end

%-Find (or create) help window.
%-----------------------------------------------------------------------
Fhelp = spm_figure('FindWin','Help');
if isempty(Fhelp)
    Fhelp = spm_help('!Create');
else
    set(Fhelp,'Visible','on')
end
set(Fhelp,'Pointer','Watch')
HD = get(Fhelp,'UserData');

%-Sort out integer Topic parameters from uicontrol CallBacks
%-----------------------------------------------------------------------
%-PrevTopics passes Topic as PullDown value, Back button passes -1
if ~ischar(Topic)
    PrevTopics = get(HD.hPrevTopics,'String');
    if Topic<0
        %-Go back to last topic - find PrevTopics pulldown
        if isempty(get(HD.hTopic,'String'))
            %-Topic string is empty - no topic displayed
            % go to last displayed topic (if there was one)
            Topic = min(size(PrevTopics,1),2);
        else
            %-Current topic is second, previous is third
            Topic = min(size(PrevTopics,1),3);
        end
    end
    if Topic==1, set(Fhelp,'Pointer','Arrow'), return, end
    if Topic>2, PrevTopics(2:Topic-1,:)=[]; end
    Topic = deblank(PrevTopics(2,:));
    bDonePrevTopics = 1;
else
    bDonePrevTopics = 0;
end
bMenuWin = strcmp(Topic,'MenuWin');

%-Load text file or get text from 'ShortTopics'
%-----------------------------------------------------------------------
Fname = which(Topic);           %-Try to find file on MATLABPATH
if isempty(Fname) || ...        %-No such file
    exist(Fname,'file')==3      %-Watch out for MEX files!
    Fname = which([Topic,'.m']);    %-if MEX, try *.m file
end
fid = fopen(Fname,'rt');            %-Try to open file

if fid<0                %-No file - try 'ShortTopics'
    [S,Err] = spm_help('!ShortTopics',Topic);
else                    %-Read help text from file
    S = fread(fid,'*char')';
    Err = 0;
    fclose(fid);
end

%-Display the current help comments
%-----------------------------------------------------------------------
spm_help('!Disp',Topic,S,Fhelp);

%-Display MenuWin graphic if required
%-----------------------------------------------------------------------
if bMenuWin
    spm_help('!DrawMenuWin')
end

%-Sort out control objects
%-----------------------------------------------------------------------
set(HD.hTopic,'String',Topic);

%-If unknown topic then return
%-----------------------------------------------------------------------
if Err, set(Fhelp,'Pointer','Arrow'), return, end

%-Sort out previous topics pulldown
%-For "PrevTopics" & "Back" buttons we did this above
%-----------------------------------------------------------------------
if ~bDonePrevTopics
    PrevTopics = get(HD.hPrevTopics,'String');
    Prompt     = PrevTopics(1,:); PrevTopics(1,:)=[];
    %-Add current topic to previous topics if not same as one before
    if ~strcmp(Topic,deblank(PrevTopics(1,:)))
        PrevTopics = char(Topic,PrevTopics);
    end
    % %-Delete any replications of Topic within PrevTopics
    % if size(PrevTopics,1)>1
    %   IDRows = 1+find(all( PrevTopics(2:size(PrevTopics,1),:) ==...
    %       repmat(PrevTopics(1,:),size(PrevTopics,1)-1,1),2));
    %   PrevTopics(IDRows,:)=[];
    % end
    %-Truncate to 20 items max
    if size(PrevTopics,1)>20, PrevTopics(21:size(PrevTopics,1),:)=[]; end
    PrevTopics=char(Prompt,PrevTopics);
end
%-Update popup
set(HD.hPrevTopics,'String',PrevTopics,'Value',1)

%-Find referenced topics
%-----------------------------------------------------------------------
RefdTopics = cellstr(get(HD.hRefdTopics,'String'));
RefdTopics = {RefdTopics{1};Topic}; %-Add current topic at top of references
q     = findstr(S,'spm_');      %-Find 'spm_' strings
for i = 1:length(q)
    d = (0:31) + q(i);          %-32 is max "spm_*" length considered
    Q = S(d(d <= length(S)));       %-string (len<=32) starting "spm_"
    d = find(Q==';'|Q=='('|Q==')'|Q==10|Q=='.'|Q==','|Q==' ');
    if length(d)            %-Look for filename extensions
    if any(strncmp(Q(min(d):end),{'.man','.txt'},4))
        Q = Q(1:min(d)+3);
    elseif any(strncmp(Q(min(d):end),{'.c','.h'},2))
        Q = Q(1:min(d)+1);
    else
        Q = Q(1:min(d)-1);
    end
    if exist(Q,'file') == 2 && ~any(strcmp(RefdTopics,Q))
        RefdTopics = [RefdTopics;{Q}]; end
    else
    warning('spm_* string end not found - neglecting reference')
    end
end
RefdTopics(2)=[];           %-Delete current Topic from references
%-Update popup
set(HD.hRefdTopics,'String',RefdTopics,'Value',1)

set(Fhelp,'Pointer','Arrow')

case '!disp'
%=======================================================================
% spm_help('!Disp',Fname,S,F,TTitle)
if nargin<5, TTitle=''; else TTitle=varargin{5}; end
if nargin<4, F='Help'; else F=varargin{4}; end
if nargin<3, S=''; else S=varargin{3}; end
if nargin<2, Fname='spm.man'; else Fname=varargin{2}; end
if isempty(TTitle), TTitle=Fname; end

%-Find (or create) window to print in
Fhelp = spm_figure('FindWin',F);
if isempty(Fhelp)
    Fhelp = spm_help('!CreateHelpWin');
else
    set(Fhelp,'Visible','on');
end
FS = spm('FontSizes');
PF = spm_platform('fonts');
set(Fhelp,'Pointer','Watch')
spm_help('!Clear',Fhelp)

%-Parse text file/string
%-----------------------------------------------------------------------
if isempty(S)
    %-Load text file or get text from 'ShortTopics'
    fid = fopen(Fname,'rt');
    if fid<0
        [S,Err] = spm_help('!ShortTopics',Fname);
    else
        S = fread(fid,'*char')';
        % Err = 0;
        fclose(fid);
    end
end
q     = min([length(S),findstr(S,char([10 10]))]);  % find empty lines
q     = find(S(1:q(1)) == 10);              % find line breaks

figure(Fhelp)
hAxes = axes('Position',[0.028,0.05,0.85,0.85],...
        'DefaultTextInterpreter','none',...
        'Units','Points','Visible','off');
AxPos = get(hAxes,'Position'); set(hAxes,'YLim',[0,AxPos(4)])

dy = FS(10)*1.2; y0 = floor(AxPos(4)) -dy;

text(-0.03,y0,TTitle,'FontSize',FS(14),'FontWeight','bold');
y     = y0 - FS(14);

%-Loop over pages & lines of text
%-----------------------------------------------------------------------
FmtLine = 1;
for i = 1:(length(q) - 1)
    d = S((q(i) + 1):(q(i + 1) - 1));

    %-Display help text lines
    if d(1) == abs('%');
        %-For some reason, '|' characters cause a CR.
        d = strrep(d,'|','I');
        h = text(0,y,d(2:length(d)),...
            'FontName',PF.courier,'FontSize',FS(9));
        if FmtLine
            set(h,'FontWeight','bold',...
                'FontName',PF.times,'FontSize',FS(10));
            y = y - FS(8);
            FmtLine=0;
        end
        y = y - dy;
    end

    %-Paginate if necessary
    if y<0
        text(0.5,-10,['Page ',num2str(length(hAxes))],...
            'FontSize',FS(8),'FontAngle','Italic')
        spm_figure('NewPage',[hAxes(end);get(hAxes(end),'Children')])
        hAxes = [hAxes,axes('Units','Points','Position',AxPos,...
                'DefaultTextInterpreter','none',...
                'YLim',[0,AxPos(4)],'Visible','off')];
        y     = y0;
    end
end

%-Register last page if paginated
if length(hAxes)>1
    text(0.5,-10,sprintf('Page %d/%d',length(hAxes)*[1,1]),...
        'FontSize',FS(8),'FontAngle','italic')
    spm_figure('NewPage',[hAxes(end);get(hAxes(end),'Children')])
end

set(Fhelp,'Pointer','Arrow')

case '!create'
%=======================================================================
% F = spm_help('!Create')
%-Condition arguments

F = spm_help('!CreateHelpWin');
spm_help('!CreateBar',F)
spm_figure('WaterMark',F,spm('Ver'),'WaterMark',-45,1)
varargout = {F};

case '!createhelpwin'
%=======================================================================
% F = spm_help('!CreateHelpWin')

F = spm_figure('FindWin','Help');
if any(F), return, end

%-Draw window
%-----------------------------------------------------------------------
WS     = spm('WinScale');           %-Window scaling factors
FS     = spm('FontSizes');          %-Scaled font sizes
PF     = spm_platform('fonts');     %-Font names (for this platform)
S0     = spm('WinSize','0',1);      %-Screen size (of the current monitor)

F      = figure('IntegerHandle','off',...
    'Position',[S0(1)+S0(3)/2,S0(2),0,0] + [-300 008 600 865].*WS,...
    'Resize','off',...
    'Name',sprintf('%s%s: SPMhelp',spm('ver'),spm('GetUser',' (%s)')),...
    'NumberTitle','off',...
    'Tag','Help',...
    'MenuBar','none',...
    'Units','Pixels',...
    'DefaultTextInterpreter','none',...
    'DefaultTextFontName',PF.helvetica,...
    'DefaultTextFontSize',FS(12),...
    'DefaultUicontrolFontName',PF.helvetica,...
    'DefaultUicontrolFontSize',FS(12),...
    'DefaultUicontrolInterruptible','on',...
    'Color','w',...
    'ColorMap',gray(64),...
    'DefaultTextColor','k',...
    'DefaultAxesColor','w',...
    'DefaultAxesXColor','k',...
    'DefaultAxesYColor','k',...
    'DefaultAxesZColor','k',...
    'DefaultAxesFontName',PF.helvetica,...
    'DefaultPatchFaceColor','k',...
    'DefaultPatchEdgeColor','k',...
    'DefaultSurfaceEdgeColor','k',...
    'DefaultLineColor','k',...
    'PaperType','A4',...
    'PaperUnits','normalized',...
    'PaperPosition',[.0726 .0644 .854 .870],...
    'InvertHardcopy','off',...
    'Visible','on');
varargout = {F};

case '!createbar'
%=======================================================================
% spm_help('!CreateBar',F)
%-----------------------------------------------------------------------
% Print | Clear | Current Topic     | Back | Menu | Help | SPMweb
% About SPMver  | Referenced Topics |   Previous Topics  | Close
%-----------------------------------------------------------------------

% if nargin<2, F='Help'; else F=varargin{2}; end
F = spm_figure('FindWin','Help');
if isempty(F)
    error('Help figure not found')
elseif ~strcmp(get(F,'Tag'),'Help')
    error('Specified figure is not an SPM Help window')
end

%-Get position and size parameters
%-----------------------------------------------------------------------
cF    = get(0,'CurrentFigure');
set(0,'CurrentFigure',F)
set(F,'Units','Pixels');
P     = get(F,'Position'); P = P(3:4);      % Figure dimensions {pixels}
S_Gra = P./[600,865];               % x & y scaling coefs

nBut  = 11;
nGap  = 4;
sx    = floor(P(1)./(nBut+(nGap+2)/6));     % uicontrol object width
dx    = floor(2*sx/6);              % inter-uicontrol gap
sy    = floor(20*S_Gra(1));         % uicontrol object height
x0    = dx/2;                   % initial x position
x     = dx/2;                   % uicontrol x position
y     = P(2) - sy;              % uicontrol y position
y2    = P(2) - 2.25*sy;             % uicontrol y position
FS    = round(10*min(S_Gra));            % uicontrol font size

%-Delete any existing HelpBar objects
%-----------------------------------------------------------------------
spm_figure('Clear',F,'HelpBar')

%-Create Frame for controls
%-----------------------------------------------------------------------
uicontrol(F,'Style', 'Frame',...
    'Position',[-4 (P(2) - 2.50*sy) P(1)+8 2.50*sy+4],...
    'Tag','HelpBar','HandleVisibility','callback');

%-Create uicontrol objects
%-----------------------------------------------------------------------
uicontrol(F,'String','Print' ,'Position',[x y sx sy],...
    'ToolTipString','print topic',...
    'FontSize',FS,...
    'CallBack','spm_figure(''Print'',[])',...
    'Interruptible','off','BusyAction','cancel',...
    'Tag','HelpBar','HandleVisibility','callback',...
    'ForegroundColor','b'); x = x+sx;

uicontrol(F,'String','Clear' ,'Position',[x y sx sy],...
    'ToolTipString','clear topic',...
    'FontSize',FS,...
    'CallBack','spm_help(''!Clear'',gcf)',...
    'Interruptible','off','BusyAction','cancel',...
        'Tag','HelpBar','HandleVisibility','callback',...
        'ForegroundColor','b'); x = x+sx+dx;

uicontrol(F,'String',sprintf('About %s',spm('Ver')),...
    'ToolTipString','about this release of SPM',...
    'FontSize',FS,...
    'Position',[x0 y2 2*sx sy],...
    'HorizontalAlignment','Center',...
    'CallBack','spm_help(''spm.man'')',...
    'Tag','HelpBar','HandleVisibility','callback',...
    'ForegroundColor',[0 0.5 0])

uicontrol(F,'Style','Text','String','Topic ',...
    'FontSize',FS,...
    'Position',[x y sx sy],...
    'HorizontalAlignment','Right',...
    'Tag','HelpBar','HandleVisibility','callback',...
    'ForegroundColor','k')

hRefdTopics = uicontrol(F,'Style','PopUp',...
    'ToolTipString','topics referenced by the current topic',...
    'FontSize',FS,...
    'Position',[x-1,y2-1,4*sx+1,sy],...
    'String',{'Referenced Topics...'},...
    'CallBack',...
        'spm_help(''!PullDownTopic'')',...
    'Tag','HelpBar','HandleVisibility','callback',...
    'HorizontalAlignment','Left',...
    'ForegroundColor','k'); x = x+sx;

hTopic = uicontrol(F,'Style','Edit','String','',...
    'ToolTipString','type/edit topic name here & press RETURN',...
    'FontSize',FS,...
    'Position',[x y 3*sx sy],...
    'CallBack','spm_help(get(gco,''String''))',...
    'Tag','HelpBar','HandleVisibility','callback',...
    'ForegroundColor','k','BackgroundColor',[.8,.8,1],...
    'HorizontalAlignment','Center'); x = x+3*sx+dx;

uicontrol(F,'String','Back',   'Position',[x y sx sy],...
    'ToolTipString','return to last topic',...
    'FontSize',FS,...
    'CallBack','spm_help(''!Topic'',-1)',...
    'Interruptible','off','BusyAction','cancel',...
    'Tag','HelpBar','HandleVisibility','callback')

hPrevTopics = uicontrol(F,'Style','PopUp',...
    'ToolTipString','return to a previous topic',...
    'FontSize',FS,...
    'Position',[x-1,y2-1,3*sx+2*dx+1,sy],...
    'String',char('Previous Topics...','MenuWin'),...
    'CallBack',...
    'if get(gcbo,''Value'')~=1,spm_help(get(gcbo,''Value'')),end',...
    'Tag','HelpBar','HandleVisibility','callback',...
    'HorizontalAlignment','Left',...
    'ForegroundColor','k'); x = x+sx+dx;

uicontrol(F,'String','Menu',   'Position',[x y sx sy],...
    'ToolTipString','draw SPMmenu for exploring help',...
    'FontSize',FS,...
    'CallBack','spm_help(''MenuWin'')',...
    'Interruptible','off','BusyAction','cancel',...
    'Tag','HelpBar','HandleVisibility','callback',...
    'ForegroundColor',[0 0.5 0]), x = x+sx+dx;

uicontrol(F,'String','Help',   'Position',[x y sx sy],...
    'ToolTipString','help on using the SPMhelp browser',...
    'FontSize',FS,...
    'CallBack','spm_help(''spm_help.m'')',...
    'Interruptible','off','BusyAction','cancel',...
    'Tag','HelpBar','HandleVisibility','callback',...
    'ForegroundColor',[0 0.5 0]), x = x+sx+dx;

uicontrol(F,'String','SPMweb', 'Position',[x y sx+dx/2 sy],...
    'ToolTipString',...
    'launch web browser - http://www.fil.ion.ucl.ac.uk/spm/',...
    'FontSize',FS,...
    'FontWeight','Bold','FontName',spm_platform('font','courier'),...
    'CallBack',['set(gcbf,''Pointer'',''Watch''),',...
            'web(''http://www.fil.ion.ucl.ac.uk/spm'');',...
            'set(gcbf,''Pointer'',''Arrow'')'],...
    'Interruptible','off','BusyAction','cancel',...
    'Tag','HelpBar','HandleVisibility','callback',...
    'ForegroundColor','k')

uicontrol(F,'String','Close',   'Position',[x y2 sx+dx/2 sy],...
    'ToolTipString','close the SPMhelp browser',...
    'FontSize',FS,...
    'CallBack','spm_help(''!Quit'')',...
    'Interruptible','off','BusyAction','cancel',...
    'Tag','HelpBar','HandleVisibility','callback',...
    'ForegroundColor','r')

%-Store useful handles in UserData of Help figure
%-----------------------------------------------------------------------
set(F,'UserData',struct(...
    'hTopic',hTopic,...
    'hPrevTopics',hPrevTopics,...
    'hRefdTopics',hRefdTopics) )

%-Create FigureKeyPressFcn to edit Topic widget
%-----------------------------------------------------------------------
set(F,'KeyPressFcn',[...
    'spm_help(''!FigKeyPressFcn'',',...
        'getfield(get(gcbf,''UserData''),''hTopic''),',...
        'get(gcbf,''CurrentCharacter''))'] )

%-Reset CurrentFigure
set(0,'CurrentFigure',cF);

case '!pulldowntopic'
%=======================================================================
% spm_help('!PullDownTopic')
Topic = get(gcbo,'Value');
if Topic==1, return, end
Topics = get(gcbo,'String');
spm_help('!Topic',Topics{Topic})

case '!figkeypressfcn'
%=======================================================================
% spm_help('!FigKeyPressFcn',h,ch)
if nargin<2, error('Insufficient arguments'); else h=varargin{2};  end
if nargin<3, ch=get(gcf,'CurrentCharacter');  else ch=varargin{3}; end

tmp = get(h,'String');

if isempty(ch)
    %- shift / control / &c. pressed
    return
elseif abs(ch)==13
    %-Goto topic
    spm_help(tmp)
    return
elseif any(abs(ch)==32:126)
    tmp = [tmp, ch];
elseif abs(ch)==21
    %- ^U - kill
    tmp = '';
elseif any(abs(ch)==[8,127])
    %-BackSpace or Delete
    if ~isempty(tmp), tmp(length(tmp))=''; end
else
    %-Illegal character
    return
end
set(h,'String',tmp)

case '!clear'
%=======================================================================
% spm_help('!Clear',F)
%-Clear window, leaving 'ToolBar' 'Tag'ed objects, hiding 'HelpMenu'
% 'Tag'ged objects. Clear "Topic" widget.
%-Note: spm_help('!Disp') calls spm_help('!Clear'), so we might be
% working in the 'Graphics' window.

%-Sort out arguments
%-----------------------------------------------------------------------
if nargin<2, F='Help'; else F = varargin{2}; end
F=spm_figure('FindWin',F);
if isempty(F), return, end

%-If not 'Help' window, then just do a normal clear.
if ~strcmp(get(F,'Tag'),'Help'), spm_figure('Clear',F), return, end
HD = get(F,'UserData');

%-Clear figure & make any 'HelpMenu' objects invisible
%-----------------------------------------------------------------------
for h = findobj(get(F,'Children'),'Flat','HandleVisibility','on')'
    if ~strcmp(get(h,'Tag'),'HelpMenu'), delete(h), end
end
set(findobj(F,'Tag','HelpMenu'),'Visible','off')
try
    set(HD.hTopic,'String','');
    RefdTopics = cellstr(get(HD.hRefdTopics,'String'));
    set(HD.hRefdTopics,'Value',1,'String',RefdTopics{1})
end

case '!contexthelp'
%=======================================================================
% h = spm_help('!ContextHelp',Topic)

%-If no topic specified, use caller function
%-----------------------------------------------------------------------
if nargin<2
    st = dbstack;
    if length(st)>1, Topic=st(2).name; else Topic='MenuWin'; end
else
    Topic=varargin{2};
end

%-----------------------------------------------------------------------
Finter = spm_figure('FindWin','Interactive');
if spm('CmdLine')
    fprintf('\nSPM: Type `help %s` for help on this routine.\n',Topic)
    if nargout>0, varargout = {0}; end
elseif ~isempty(Finter)
    delete(findobj(Finter,'Tag','ContextHelp'))
    S2 = get(Finter,'Position');
    hAx = axes('Parent',Finter,...
        'Units','Pixels',...
        'Position',[S2(3)-23 05 20 25],...
        'Tag','ContextHelp',...
        'Visible','off');
    h = text(0.5,0.5,'?',...
        'Parent',hAx,...
        'Color','g',...
        'FontName',spm_platform('font','helvetica'),...
        'FontSize',spm('FontSize',14),...
        'FontWeight','bold','FontAngle','italic',...
        'HorizontalAlignment','Center',...
        'VerticalAlignment','middle',...
        'ButtonDownFcn',['spm_help(''',Topic,''')']);
    if nargout>0, varargout = {h}; end
end

otherwise
%=======================================================================
error('Unknown action string')

%=======================================================================
end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function toolboxUpdateHeader
% Update the headers of all the files.
%
% USAGE
%  toolboxUpdateHeader
%
% INPUTS
%
% OUTPUTS
%
% EXAMPLE
%
% See also
%
% Piotr's Image&Video Toolbox      Version 3.22
% Copyright 2013 Piotr Dollar.  [pdollar-at-caltech.edu]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Simplified BSD License [see external/bsd.txt]

header={
  '% Piotr''s Image&Video Toolbox      Version 3.22'; ...
  '% Copyright 2013 Piotr Dollar.  [pdollar-at-caltech.edu]'; ...
  '% Please email me if you find bugs, or have suggestions or questions!'; ...
  '% Licensed under the Simplified BSD License [see external/bsd.txt]'};

% must start in /toolbox base directory
cd(fileparts(mfilename('fullpath'))); cd('../');
dirs={ 'channels', 'classify', 'classify/private', 'detector', ...
  'filters', 'images', 'images/private', 'matlab', 'external' };

% update the headers
for i=1:length(dirs)
  mFiles = dir([ dirs{i}, '/*.m' ]);
  disp( ['--------------------------------->' dirs{i}] );
  for j=1:length(mFiles);
    fName = [dirs{i} '/' mFiles(j).name]; disp( fName );
    toolboxUpdateHeader1( fName, header );
  end
end

end

function toolboxUpdateHeader1( fName, header )
lines=readFile(fName); n=length(lines);

% find first part of first lines of header in file
loc = strfind(lines,header{1}(1:30));
for i=1:n, if(~isempty(loc{i})), break; end; end; loc=i;

% if not found nothing to do, ow assert nHeader lines exist
nHeader = length(header);
if(loc>n-nHeader+1), warning([fName ' no header']); return; end %#ok<WNTAG>
for i=1:nHeader; assert( strfind(lines{loc+i-1},header{i}(1:10))>0 ); end

% check if first lines changed, if so update; optionally update rest
if(~any(strfind(lines{loc},'NEW'))); return; end
lines{loc+1}(13:16)=header{2}(13:16);
for i=[1 3:nHeader]; lines{loc+i-1}=header{i}; end
assert(isempty(lines{loc-1}) || strcmp(lines{loc-1},'%'));
lines{loc-1} = '%'; writeFile( fName, lines );

end

function lines = readFile( fName )
fid = fopen( fName, 'rt' ); assert(fid~=-1);
lines=cell(10000,1); n=0;
while( 1 )
  n=n+1; lines{n}=fgetl(fid);
  if( ~ischar(lines{n}) ), break; end
end
fclose(fid); n=n-1; lines=lines(1:n);
end

function writeFile( fName, lines )
fid = fopen( fName, 'wt' );
for i=1:length(lines); fprintf( fid, '%s\n', lines{i} ); end
fclose(fid);
end

author: zouchuhang

repo: LayoutNet


text:
function Population = EvolveByMOEAD(Problem,Population,W,deltaG)
% Uniformity optimization by MOEA/D

%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    %% Detect the neighbours of each solution
    W = W.*repmat(max(Population.objs,[],1)-min(Population.objs,[],1),size(W,1),1);
    B = pdist2(W,W);
    [~,B] = sort(B,2);
    B = B(:,1:ceil(Problem.N/10));

    %% Associate each subproblem with one solution
    % The ideal point
    Z = min(Population.objs,[],1);
    % The value of each solution on each subproblem (modified Tchebycheff approach)
    g = zeros(Problem.N);
    for i = 1 : Problem.N
        g(i,:) = max(repmat(abs(Population(i).obj-Z),Problem.N,1)./W,[],2)';
    end
    [~,rank] = sort(g,2);
    % The index of solution which each subproblem associated with
    associate = zeros(1,Problem.N);
    for i = 1 : Problem.N
        x = find(~associate(rank(i,:)),1);
        associate(rank(i,x)) = i;
    end
    Population = Population(associate);

    %% Optimization
    for k = 1 : deltaG
        % For each solution
        for i = 1 : Problem.N
            % Choose the parents
            if rand < 0.9
                P = B(i,randperm(size(B,2)));
            else
                P = randperm(Problem.N);
            end

            % Generate an offspring
            Offspring = OperatorDE(Problem,Population(i),Population(P(1)),Population(P(2)));
            % Update the ideal point
            Z = min(Z,Offspring.obj);
            % Update the solutions in P by modified Tchebycheff approach
            g_old = max(abs(Population(P).objs-repmat(Z,length(P),1))./W(P,:),[],2);
            g_new = max(repmat(abs(Offspring.obj-Z),length(P),1)./W(P,:),[],2);
            Population(P(g_old>=g_new)) = Offspring;
        end
    end
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
function [NTWDseries TWDseries] = SquaredDiffComputation_beatbybeat(Complexes)
% [NTWDseries TWDseries] = SquaredDiffComputation_beatbybeat(Complexes)
%   OVERVIEW:   Computed squared difference between consecutive QRS
%               complexes with and without dynamic time warping.
%
%   INPUT:      MANDATORY:
%               Complexes       : 2D array of dimension number of complexes by median length of complexes
%
%
%
%
%   OUTPUT:
%               NTWDseries      : Squared difference between consecutive QRS complexes without time warping
%
%               TWDseries       : Squared difference between consecutive QRS complexes with time warping
%
%	REPO:
%       https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox
%   ORIGINAL SOURCE AND AUTHORS:
%       Written by Ismail Sadiq
%	COPYRIGHT (C) 2019
%   LICENSE:
%       This software is offered freely and without warranty under
%       the GNU (v3 or later) public license. See license file for
%       more information. The license may be found in
%       the Documents folder of the Physionet-Cardiovascular-Signal-Toolbox.
%

noofconsecutivecomplexes = size(Complexes,1);

% time warped squared diff
TWDseries(1:noofconsecutivecomplexes) = 0;
% non time warped squared diff
NTWDseries(1:noofconsecutivecomplexes) = 0;

for index = 1:noofconsecutivecomplexes-1

    complex1 = Complexes(index,:);
    complex2 = Complexes(index+1,:);

    % compute squared difference between each complex and median complex w/o
    % dtw
    SD = sum((complex1 - complex2).^2);
    SD = SD ./ length(complex1);
    NTWDseries(index) = SD;

    % compute squared difference between each complex and median complex with dtw
    [dist,ix,iy] = dtw(complex1, complex2);
    templt1 = complex1(ix);
    templt2 = complex2(iy);

    MD = sum((templt1 - templt2).^2);
    MD = MD ./ length(templt1);

    TWDseries(index) = MD;

end

end

author: cliffordlab

repo: PhysioNet-Cardiovascular-Signal-Toolbox


text:
function bn = bacon_numbers(A,u)
% BACON_NUMBERS Compute the Bacon numbers for a graph.
%
% bn = bacon_numbers(A,u) computes the Bacon numbers for all nodes in the
% graph assuming that Kevin Bacon is node u.

% allocate storage for the bacon numbers
% the ipdouble call allocates storage that can be modified in place.
bn_inplace = ipdouble(zeros(num_vertices(A),1));

% implement a nested function that can refer to variables we declare.  In
% this case, we refer to the bn_inplace variable.
function tree_edge(ei,u,v)
    bn_inplace(v) = bn_inplace(u)+1;
end

% setup the bacon_recorder visitor
bacon_recorder = struct();
bacon_recorder.tree_edge = @tree_edge;

% call breadth_first_search
breadth_first_search(A,u,bacon_recorder);

% convert the inplace storage back to standard Matlab storage to return.
bn = double(bn_inplace);

% the end line is required with nested functions to terminate the file
end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore