function result = polygon_xy_2d ( n, x, y )

%*****************************************************************************80
%
%% POLYGON_XY_2D integrates the function X*Y over a polygon in 2D.
%
%  Integration region:
%
%    The polygon bounded by the points (X(1:N), Y(1:N)).
%
%  Formula:
%
%    INTEGRAL = (1/24) * SUM ( 1 <= I <= N )
%      ( Y(I)   * ( 3 * X(I)**2 + 2 * X(I) * X(I-1) +     X(I-1)**2 )
%      + Y(I-1) * (     X(I)**2 + 2 * X(I) * X(I-1) + 3 * X(I-1)**2 ) )
%      * ( Y(I) - Y(I-1) )
%
%    where X(0) and Y(0) should be replaced by X(N) and Y(N).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 May 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    S F Bockman,
%    Generalizing the Formula for Areas of Polygons to Moments,
%    American Mathematical Society Monthly,
%    1989, pages 131-132.
%
%  Parameters:
%
%    Input, integer N, the number of vertices of the polygon.
%    N should be at least 3 for a nonzero result.
%
%    Input, real X(N), Y(N), the coordinates of the vertices
%    of the polygon.  These vertices should be given in
%    counter-clockwise order.
%
%    Output, real RESULT, the value of the integral.
%
  result = 0.0E+00;

  if ( n < 3 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'POLYGON_XY_2D - Warning!\n' );
    fprintf ( 1, '  The number of vertices must be at least 3.\n' );
    fprintf ( 1, '  The input value of N = %d\n', n );
    error ( 'POLYGON_XY_2D - Fatal error!' );
  end

  for i = 1 : n

    if ( i == 1 )
      im1 = n;
    else
      im1 = i - 1;
    end

    result = result + ( ...
      y(i) * ( 3.0E+00 * x(i)^2 + 2.0E+00 * x(i) * x(im1) + x(im1)^2 ) ...
      + y(im1) * ( x(i)^2 + 2.0E+00 * x(i) * x(im1) + 3.0E+00 * x(im1)^2 ) ...
      ) * ( y(i) - y(im1) );

  end

  result = result / 24.0E+00;

  return
end


function variance = log_series_variance ( a )

%*****************************************************************************80
%
%% LOG_SERIES_VARIANCE returns the variance of the Logarithmic Series PDF.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 February 1999
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real A, the parameter of the PDF.
%    0.0 < A < 1.0.
%
%    Output, real VARIANCE, the variance of the PDF.
%
  alpha = - 1.0 / log ( 1.0 - a );

  variance = a * alpha * ( 1.0 - alpha * a ) / ( 1.0 - a )^2;

  return
end


function [f] = psi(z)
%Psi     Psi (or Digamma) function valid in the entire complex plane.
%
%                 d
%        Psi(z) = --log(Gamma(z))
%                 dz
%
%usage: [f] = psi(z)
%
%tested under versions 6.0 and 5.3.1
%
%        Z may be complex and of any size.
%
%        This program uses the analytical derivative of the
%        Log of an excellent Lanczos series approximation
%        for the Gamma function.
%
%References: C. Lanczos, SIAM JNA  1, 1964. pp. 86-96
%            Y. Luke, "The Special ... approximations", 1969 pp. 29-31
%            Y. Luke, "Algorithms ... functions", 1977
%            J. Spouge,  SIAM JNA 31, 1994. pp. 931
%            W. Press,  "Numerical Recipes"
%            S. Chang, "Computation of special functions", 1996
%
%
%see also:   GAMMA GAMMALN GAMMAINC PSIN
%see also:   mhelp psi
%see also:   mhelp GAMMA

%Paul Godfrey
%pgodfrey@conexant.com
%July 13, 2001
%see gamma for calculation details...

siz = size(z);
z=z(:);
zz=z;

f = 0.*z; % reserve space in advance

%reflection point
p=find(real(z)<0.5);
if ~isempty(p)
   z(p)=1-z(p);
end

%Lanczos approximation for the complex plane

g=607/128; % best results when 4<=g<=5

c = [  0.99999999999999709182;
      57.156235665862923517;
     -59.597960355475491248;
      14.136097974741747174;
      -0.49191381609762019978;
        .33994649984811888699e-4;
        .46523628927048575665e-4;
       -.98374475304879564677e-4;
        .15808870322491248884e-3;
       -.21026444172410488319e-3;
        .21743961811521264320e-3;
       -.16431810653676389022e-3;
        .84418223983852743293e-4;
       -.26190838401581408670e-4;
        .36899182659531622704e-5];

n=0;
d=0;
for k=size(c,1):-1:2
    dz=1./(z+k-2);
    dd=c(k).*dz;
    d=d+dd;
    n=n-dd.*dz;
end
d=d+c(1);
gg=z+g-0.5;
%log is accurate to about 13 digits...

f = log(gg) + (n./d - g./gg) ;

if ~isempty(p)
   f(p) = f(p)-pi*cot(pi*zz(p));
end

p=find(round(zz)==zz & real(zz)<=0 & imag(zz)==0);
if ~isempty(p)
   f(p) = Inf;
end

f=reshape(f,siz);

return

%A demo of this routine is:
clc
clear all
close all
x=-4:1/16:4.5;
y=-4:1/16:4;
[X,Y]=meshgrid(x,y);
z=X+i*Y;
f=psi(z);
p=find(abs(f)>10);
f(p)=10;

mesh(x,y,abs(f),phase(f));
view([45 10]);
rotate3d;

figure(2);
ezplot psi;
grid on;

One=psi(2)-psi(1)
EulerGamma=-psi(1)

return


function J = computeCostMulti(X, y, theta)
%COMPUTECOSTMULTI Compute cost for linear regression with multiple variables
%   J = COMPUTECOSTMULTI(X, y, theta) computes the cost of using theta as the
%   parameter for linear regression to fit the data points in X and y

% Initialize some useful values
m = length(y); % number of training examples

% You need to return the following variables correctly
J = 0;

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta
%               You should set J to the cost.

predictions =  X*theta;
sqerrors = (predictions - y).^2;
J = 1/(2*m)* sum(sqerrors);

% =========================================================================

end


% book : Signals and Systems Laboratory with MATLAB
% authors : Alex Palamides & Anastasia Veloni

% DTFT of a discrete time signal x[n]

%x[n]=0.8^n , 0<=n<=20
syms w
n= 0:20;
x=0.8.^n;
X=sum(x.*exp(-j*w*n));
ezplot(abs(X),[-pi pi])
title(' Magnitude of DTFT')
ylim([0 5.4])

figure
w1=-pi:.01:pi;
XX=subs(X,w,w1)
plot(w1,angle(XX));
xlim([-pi pi])
title('Phase of DTFT')

figure
ezplot(abs(X),[-5*pi 5*pi]);
title('Magnitude of DTFT in 5 periods')
ylim([0 5.8])

figure
w1=-5*pi:.01:5*pi;
XX=subs(X,w,w1);
plot(w1,angle(XX));
xlim([-5*pi 5*pi])
title(' Phase of DTFT in 5 periods')

%x[n]=0.8^n u[n]
figure
syms n w
x=0.6^n
X=symsum(x*exp(-j*w*n),n,0,inf)
w1=-pi:.01:pi;
X_=subs(X,w,w1);
plot(w1,abs(X_));
legend('|X(\omega)|')
xlim([-pi pi])

figure
plot(w1,angle(X_));
xlim([-pi pi])
legend('\angle X(\omega)')


function cartPoints=ellips2Cart(points,a,f)
%%ELLIPS2CART Convert ellipsoidal coordinates to ECEF Cartesian
%             coordinates.
%
%INPUTS: points One or more points given in geodetic latitude and
%               longitude, in radians, and height, in meters that are to be
%               converted to Cartesian coordinates. To convert N points,
%               points is a 3XN matrix with each column having the format
%               [latitude;longitude; height].
%             a The semi-major axis of the reference ellipsoid. If this
%               argument is omitted or an empty matrix is passed, the value
%               in Constants.WGS84SemiMajorAxis is used.
%             f The flattening factor of the reference ellipsoid. If this
%               argument is omitted or an empty matrix is passed, the value
%               in Constants.WGS84Flattening is used.
%
%OUTPUTS: cartPoints For N points, cartPoints is a 3XN matrix of the
%               converted points with each column having the format
%               [x;y;z].
%
%The conversions are mentioned in [1].
%
%REFERENCES:
%[1] D. F. Crouse, "Simulating aerial targets in 3D accounting for the
%    Earth's curvature," Journal of Advances in Information Fusion, vol.
%    10, no. 1, Jun. 2015.
%
%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

if(nargin<3||isempty(f))
    f=Constants.WGS84Flattening;
end

if(nargin<2||isempty(a))
    a=Constants.WGS84SemiMajorAxis;
end

%The geodetic latitudes
phi=points(1,:);
%The longitudes
lambda=points(2,:);

if(size(points,1)==3)
    %The altitudes
    h=points(3,:);
else
    h=0;
end

sinP=sin(phi);
cosP=cos(phi);
sinL=sin(lambda);
cosL=cos(lambda);

%The square of the first numerical eccentricity
e2=2*f-f^2;
%The normal radii of curvature.
Ne=a./sqrt(1-e2*sinP.^2);

x=(Ne+h).*cosP.*cosL;
y=(Ne+h).*cosP.*sinL;
z=(Ne*(1-e2)+h).*sinP;

cartPoints=[x;y;z];
end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.


function fibonacci_spiral ( n )

%*****************************************************************************80
%
%% FIBONACCI_SPIRAL draws points on a Fibonacci spiral.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 April 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of points to plot.
%    Default is 101.
%
  if ( nargin < 1 )
    n = 101;
  end
%
%  PHI is the golden ratio, the limit of the ratio of
%  successive Fibonacci numbers:
%
%    PHI = limit ( N->oo ) F(N+1)/F(N)
%
  phi = ( 1.0 + sqrt ( 5.0 ) ) / 2.0;
%
%  Allocate storage for the data.
%
  x = zeros ( n, 1 );
  y = zeros ( n, 1 );
%
%  Set the angle and radius of the first point.
%
  a = 0.0;
  r = 0.0;
%
%  Set the increments.
%
  da = 2.0 * pi * ( phi - 1.0 ) / phi;
  dr = 1.0;
%
%  Create a spiral in which the radius R and angle A both
%  increase by a constant increment,
%
  for i = 1 : n
    x(i) = r * cos ( a );
    y(i) = r * sin ( a );
    a = mod ( a + da, 2 * pi );
    r = r + dr;
  end
%
%  Display the data in a scatter plot.
%
  scatter ( x, y, 'b.' )
  axis equal
  title ( sprintf ( 'Fibonacci spiral, N = %d', n ) )

  return
end


function l = l1dn ( n, h )

%*****************************************************************************80
%
%% L1DN stores the 1D DN Laplacian as a full matrix.
%
%  Discussion:
%
%    The N grid points are assumed to be evenly spaced by H.
%
%    For N = 5, the discrete Laplacian with left Dirichlet and right
%    Neumann condition on [0,6] has the matrix form L:
%
%       2 -1  0  0  0
%      -1  2 -1  0  0
%       0 -1  2 -1  0
%       0  0 -1  2 -1
%       0  0  0 -1  1
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 October 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of points.
%    N must be at least 3.
%
%    Input, real H, the spacing between points.
%
%    Output, real L(N,N), the Laplacian matrix.
%
  if ( n < 3 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'L1DN - Fatal error!\n' );
    fprintf ( 1, '  N < 3.\n' );
    error ( 'L1DN - Fatal error!' );
  end

  l = zeros ( n, n );

  i = 1;
  l(1,1) =  2.0 / h / h;
  l(1,2) = -1.0 / h / h;

  for i = 2 : n - 1
    l(i,i-1) = -1.0 / h / h;
    l(i,i) =    2.0 / h / h;
    l(i,i+1) = -1.0 / h / h;
  end

  i = n;
  l(n,n-1) = -1.0 / h / h;
  l(n,n) =    1.0 / h / h;

  return
end


function [ xval, yval ] = bc_val ( n, t, xcon, ycon )

%*****************************************************************************80
%
%% BC_VAL evaluates a parameterized Bezier curve.
%
%  Discussion:
%
%    BC_VAL(T) is the value of a vector function of the form
%
%      BC_VAL(T) = ( X(T), Y(T) )
%
%    where
%
%      X(T) = Sum ( 0 <= I <= N ) XCON(I) * BERN(I,N)(T)
%      Y(T) = Sum ( 0 <= I <= N ) YCON(I) * BERN(I,N)(T)
%
%    BERN(I,N)(T) is the I-th Bernstein polynomial of order N
%    defined on the interval [0,1],
%
%    XCON(0:N) and YCON(0:N) are the coordinates of N+1 "control points".
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 February 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Kahaner, Moler, and Nash,
%    Numerical Methods and Software,
%    Prentice Hall, 1989.
%
%  Parameters:
%
%    Input, integer N, the order of the Bezier curve, which
%    must be at least 0.
%
%    Input, real T, the point at which the Bezier curve should
%    be evaluated.  The best results are obtained within the interval
%    [0,1] but T may be anywhere.
%
%    Input, real XCON(0:N), YCON(0:N), the X and Y coordinates
%    of the control points.  The Bezier curve will pass through
%    the points ( XCON(0), YCON(0) ) and ( XCON(N), YCON(N) ), but
%    generally NOT through the other control points.
%
%    Output, real XVAL, YVAL, the X and Y coordinates of the point
%    on the Bezier curve corresponding to the given T value.
%
  bval = bp01 ( n, t );

  xval = xcon(1:n+1) * bval(1:n+1)';
  yval = ycon(1:n+1) * bval(1:n+1)';

  return
end


function [w,rho] = mh(A)
% Computes the Metropolis-Hastings heuristic edge weights
%
% [W,RHO] = MH(A) gives a vector of the Metropolis-Hastings edge weights
% for a graphb described by the incidence matrix A (NxM). N is the number
% of nodes, and M is the number of edges. Each column of A has exactly one
% +1 and one -1. RHO is computed from the weights W as follows:
%    RHO = max(abs(eig( eye(n,n) - (1/n)*ones(n,n) - A*W*A' ))).
%
% The M.-H. weight on an edge is one over the maximum of the degrees of the
% adjacent nodes.
%
% For more details, see the references:
% "Fast linear iterations for distributed averaging" by L. Xiao and S. Boyd
% "Fastest mixing Markov chain on a graph" by S. Boyd, P. Diaconis, and L. Xiao
% "Convex Optimization of Graph Laplacian Eigenvalues" by S. Boyd
%
% Almir Mutapcic 08/29/06

% degrees of the nodes
n = size(A,1);
Lunw = A*A';          % unweighted Laplacian matrix
degs = diag(Lunw);

% Metropolis-Hastings weights
mh_degs = abs(A)'*diag(degs);
w = 1./max(mh_degs,[],2);

% compute the norm
if nargout > 1,
    rho = norm( eye(n) - A*diag(w)*A' - (1/n)*ones(n) );
end


function u=randDirVec(numDim,N)
%%RANDDIRVEC Generate a uniformly distributed random direction vector
%            (unit vector) in an arbitrary number of dimensions.
%
%INPUTS: numDim The number of dimensions of the random unit vector. This
%               is >=1.
%             N The number of random direction vectors to generate. If
%               this parameter is omitted, then N=1 is used.
%
%OUTPUTS: u A numDimXN matrix of N numDim-dimensional unit vectors that
%           are uniformly distributed on the unit-sphere (or hypersphere).
%
%One cannot simply generate a uniformly-distributed direction vector by
%setting each dimensions to a Uniform(-1,1) random variable and then
%normalizing the result. Rather, following the algorithm in Chapter 3.4.1,
%E6 of [1], the elements of the vector must be generated as normal 0-1
%random variables and then the vector normalized.
%
%REFERENCES:
%[1] D. Knuth, The Art of Computer Programming: Seminumerical Algorithms,
%    3rd ed. Reading, MA: Addison-Wesley, 1998, vol. 2.
%
%September 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

if(nargin<2)
    N=1;
end

u=zeros(numDim,N);

for curN=1:N
    %Knuth, Chapter 3.4.1, E6 (Random point on an n-dimensional sphere with
    %radius one.
    u(:,curN)=randn(numDim,1);
    u(:,curN)=u(:,curN)/norm(u(:,curN));

    %Deal with the instance that norm(u)=0, which will occur with an extremely
    %small probability due to the limited precision of the random number
    %generation.
    if(~isfinite(u(:,curN)))
       u(:,curN)=zeros(numDim,1);
       u(1,curN)=1;
    end
end
end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.


function Z = projectData(X, U, K)
%PROJECTDATA Computes the reduced data representation when projecting only
%on to the top k eigenvectors
%   Z = projectData(X, U, K) computes the projection of
%   the normalized inputs X into the reduced dimensional space spanned by
%   the first K columns of U. It returns the projected examples in Z.
%

% You need to return the following variables correctly.
Z = zeros(size(X, 1), K);

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the projection of the data using only the top K
%               eigenvectors in U (first K columns).
%               For the i-th example X(i,:), the projection on to the k-th
%               eigenvector is given as follows:
%                    x = X(i, :)';
%                    projection_k = x' * U(:, k);
%

subsetU = U(:, 1:K);
Z = X * subsetU;

% =============================================================

end


%  Script file: lsqfit.m
%
%  Purpose:
%    To perform a least-squares fit of an input data set
%    to a straight line, and print out the resulting slope
%    and intercept values.  The input data for this fit
%    comes from a user-specified input data file.
%
%  Record of revisions:
%      Date       Programmer          Description of change
%      ====       ==========          =====================
%    03/24/07    S. J. Chapman        Original code
%
% Define variables:
%   count     -- number of values read
%   filename  -- Input file name
%   fid       -- File id
%   msg       -- Open error message
%   n         -- Number of input data pairs (x,y)
%   slope     -- Slope of the line
%   sum_x     -- Sum of all input X values
%   sum_x2    -- Sum of all input X values squared
%   sum_xy    -- Sum of all input X*Y values
%   sum_y     -- Sum of all input Y values
%   x         -- An input X value
%   x_bar     -- Average X value
%   y         -- An input Y value
%   y_bar     -- Average Y value
%   y_int     -- Y-axis intercept of the line

% Initialize sums
n = 0; sum_x = 0; sum_y = 0; sum_x2 = 0; sum_xy = 0;
x1 = []; y1 = [];

% Prompt user and get the name of the input file.
disp('This program performs a least-squares fit of an');
disp('input data set to a straight line. Enter the name');
disp('of the file containing the input (x,y) pairs:  ' );
filename = input(' ','s');

% Open the input file
[fid,msg] = fopen(filename,'rt');

% Check to see if the open failed.
if fid < 0

   % There was an error--tell user.
   disp(msg);

else

   % File opened successfully. Read the (x,y) pairs from
   % the input file.  Get first (x,y) pair before the
   % loop starts.
   [in,count] = fscanf(fid,'%g %g',2);

   while ~feof(fid)
      x = in(1);
      y = in(2);
      n      = n + 1;                  %
      sum_x  = sum_x + x;              % Calculate
      sum_y  = sum_y + y;              %   statistics
      sum_x2 = sum_x2 + x.^2;          %
      sum_xy = sum_xy + x * y;         %
      x1(n) = x;
      y1(n) = y;

      % Get next (x,y) pair
      [in,count] = fscanf(fid,'%f',[1 2]);

   end

   % Close the file
   fclose(fid);

   % Now calculate the slope and intercept.
   x_bar = sum_x / n;
   y_bar = sum_y / n;
   slope = (sum_xy - sum_x*y_bar) / (sum_x2 - sum_x*x_bar);
   y_int = y_bar - slope * x_bar;

   % Tell user.
   fprintf('Regression coefficients for the least-squares line:\n');
   fprintf('   Slope (m)     = %12.3f\n',slope);
   fprintf('   Intercept (b) = %12.3f\n',y_int);
   fprintf('   No of points  = %12d\n',n);

   % Now plot this data set
   figure(1);
   plot(x1,y1,'bo','LineWidth',2);
   hold on;

   % Now plot the fitted line
   x2 = x1;
   y2 = slope .* x2 + y_int;
   plot(x2,y2,'r-','LineWidth',2);
   hold off;

   % Title and labels
   title ('\bfLeast-Squares Fit');
   xlabel ('\bf\itx');
   ylabel ('\bf\ity');
   grid on;

end


function g = sigmoid(z)
%SIGMOID Compute sigmoid functoon
%   J = SIGMOID(z) computes the sigmoid of z.

% You need to return the following variables correctly
g = zeros(size(z));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the sigmoid of each value of z (z can be a matrix,
%               vector or scalar).

g = 1 ./ (1 + (1 ./ exp(z)));

% =============================================================

end


function a = fourier_cosine ( n )

%*****************************************************************************80
%
%% FOURIER_COSINE returns the FOURIER_COSINE matrix.
%
%  Discussion:
%
%    FOURIER_COSINE is the discrete Fourier Cosine Transform matrix.
%
%  Example:
%
%    N = 5
%
%    0.447214      0.447214      0.447214      0.447214      0.447214
%    0.601501      0.371748      0.000000     -0.371748     -0.601501
%    0.511667     -0.195440     -0.632456     -0.195439      0.511667
%    0.371748     -0.601501      0.000000      0.601501     -0.371748
%    0.195439     -0.511667      0.632456     -0.511668      0.195439
%
%  Properties:
%
%    A * A' = I.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of A.
%
%    Output, real A(N,N), the matrix.
%
  a = zeros ( n, n );

  a(1,1:n) = 1.0 / sqrt ( n );

  for i = 2 : n

    for j = 1 : n

      angle = ( i - 1 ) * ( 2 * j - 1 ) * pi / ( 2 * n );
      a(i,j) = sqrt ( 2.0 ) * cos ( angle ) / sqrt ( n );

    end
  end

  return
end


function val=polygamma(k,z)
%%POLYGAMMA Evaluate the polygamma function. This function is the same as
%           the psi function except it will work with negative values of z.
%           The polygamma function is the value of the kth derivative of
%           the derivative of gamma(z) divided by gamma(z). That is, it is
%           the kth derivative of the digamma function.
%
%INPUTS: This function can be used with 1 or two inputs. If two inputs are
%        given, then it is polygamma(k,z). If only one is given, then it is
%        polygamma(z) where k is taken to be zero. The inputs are:
%        k The number of derivatives to take, k>=0. The digamma function is
%          k=0.
%        z A matrix of points at which the polygamma function is to be
%          evaluated.
%
%OUTPUTS: val The values of the polygamma function. This is the same size
%             as z.
%
%For values of z>0, this function just calls psi(k,z). For values of z<0,
%this function uses the identity of [1] to deal with negative values. For
%example, for k=0, one uses the identity:
%psi(1-x)=psi(x)+pi/tan(pi*x)
%
%REFERENCES:
%[1] Weisstein, Eric W. "Polygamma Function." From MathWorld--A Wolfram Web
%    Resource. http://mathworld.wolfram.com/PolygammaFunction.html
%
%October 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

if(nargin==1)
    z=k;
    k=0;
end

numVals=numel(z);
val=zeros(size(z));

for curVal=1:numVals
    x=z(curVal);
    if(x>0)
        val(curVal)=psi(k,x);
    else
        x=1-x;
        val(curVal)=(-1)^k*(psi(k,x)+pi^(k+1)*cotDerivVal(pi*x,k));
    end
end
end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.


function enum = deranged_enum ( n )

%*****************************************************************************80
%
%% DERANGED_ENUM returns the number of derangements of N objects.
%
%  Discussion:
%
%    A derangement of N objects is a permutation with no fixed
%    points.  If we symbolize the permutation operation by "P",
%    then for a derangment, P(I) is never equal to I.
%
%  Recursion:
%
%      D(0) = 1
%      D(1) = 0
%      D(2) = 1
%      D(N) = (N-1) * ( D(N-1) + D(N-2) )
%
%    or
%
%      D(0) = 1
%      D(1) = 0
%      D(N) = N * D(N-1) + (-1)**N
%
%  Formula:
%
%    D(N) = N! * ( 1 - 1/1! + 1/2! - 1/3! ... 1/N! )
%
%    Based on the inclusion/exclusion law.
%
%    D(N) is the number of ways of placing N non-attacking rooks on
%    an N by N chessboard with one diagonal deleted.
%
%    Limit ( N -> Infinity ) D(N)/N! = 1 / e.
%
%    The number of permutations with exactly K items in the right
%    place is COMB(N,K) * D(N-K).
%
%  First values:
%
%     N         D(N)
%     0           1
%     1           0
%     2           1
%     3           2
%     4           9
%     5          44
%     6         265
%     7        1854
%     8       14833
%     9      133496
%    10     1334961
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of objects to be permuted.
%
%    Output, integer ENUM, the number of derangements of N objects.
%
  if ( n < 0 )

    dn = 0;

  elseif ( n == 0 )

    dn = 1;

  elseif ( n == 1 )

    dn = 0;

  elseif ( n == 2 )

    dn = 1;

  else

    dnm1 = 0;
    dn = 1;

    for i = 3 : n
      dnm2 = dnm1;
      dnm1 = dn;
      dn = ( i - 1 ) * ( dnm1 + dnm2 );
    end

  end

  enum = dn;

  return
end


function p = predict(Theta1, Theta2, X)
%PREDICT Predict the label of an input given a trained neural network
%   p = PREDICT(Theta1, Theta2, X) outputs the predicted label of X given the
%   trained weights of a neural network (Theta1, Theta2)

% Useful values
m = size(X, 1);
num_labels = size(Theta2, 1);

% You need to return the following variables correctly
p = zeros(size(X, 1), 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned neural network. You should set p to a
%               vector containing labels between 1 to num_labels.
%
% Hint: The max function might come in useful. In particular, the max
%       function can also return the index of the max element, for more
%       information see 'help max'. If your examples are in rows, then, you
%       can use max(A, [], 2) to obtain the max for each row.
%

A1_intercept = [ones(1,size(X',2)); X'];

Z2 = Theta1*A1_intercept;
A2 = sigmoid(Z2);
A2_intercept = [ones(1,size(A2,2)); A2];

Z3 = Theta2*A2_intercept;
A3 = sigmoid(Z3);

[M, I] = max(A3);
p = I(:);

% =========================================================================

end


function [ v, seed ] = vibonacci ( n, seed )

%*****************************************************************************80
%
%% VIBONACCI computes the first N Vibonacci numbers.
%
%  Discussion:
%
%    The "Vibonacci numbers" are a generalization of the Fibonacci numbers:
%      V(N+1) = +/- V(N) +/- V(N-1)
%    where the signs are chosen randomly.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 March 2005
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Brian Hayes,
%    The Vibonacci Numbers,
%    American Scientist,
%    July-August 1999, Volume 87, Number 4.
%
%    Divakar Viswanath,
%    Random Fibonacci sequences and the number 1.13198824,
%    Mathematics of Computation, 1998.
%
%  Parameters:
%
%    Input, integer N, the highest number to compute.
%
%    Input, integer SEED, a seed for the random number generator.
%
%    Output, integer V(N), the first N Vibonacci numbers.  By convention,
%    V(1) and V(2) are taken to be 1.
%
%    Output, integer SEED, an updated seed for the random number generator.
%
  if ( n <= 0 )
    v = [];
    return
  end

  v(1) = 1;

  if ( n <= 1 )
    return
  end

  v(2) = 1;

  for i = 3 : n

    [ j, seed ] = i4_uniform_ab ( 0, 1, seed );

    if ( j == 0 )
      s1 = -1;
    else
      s1 = +1;
    end

    [ j, seed ] = i4_uniform_ab ( 0, 1, seed );

    if ( j == 0 )
      s2 = -1;
    else
      s2 = +1;
    end

    v(i) = s1 * v(i-1) + s2 * v(i-2);

  end

  return
end


function [xopt,fopt,niter,gnorm,dx] = grad_descent(varargin)
% grad_descent.m demonstrates how the gradient descent method can be used
% to solve a simple unconstrained optimization problem. Taking large step
% sizes can lead to algorithm instability. The variable alpha below
% specifies the fixed step size. Increasing alpha above 0.32 results in
% instability of the algorithm. An alternative approach would involve a
% variable step size determined through line search.
%
% This example was used originally for an optimization demonstration in ME
% 149, Engineering System Design Optimization, a graduate course taught at
% Tufts University in the Mechanical Engineering Department. A
% corresponding video is available at:
%
% http://www.youtube.com/watch?v=cY1YGQQbrpQ
%
% Author: James T. Allison, Assistant Professor, University of Illinois at
% Urbana-Champaign
% Date: 3/4/12

if nargin==0
    % define starting point
    x0 = [3 3]';
elseif nargin==1
    % if a single input argument is provided, it is a user-defined starting
    % point.
    x0 = varargin{1};
else
    error('Incorrect number of input arguments.')
end

% termination tolerance
tol = 1e-6;

% maximum number of allowed iterations
maxiter = 1000;

% minimum allowed perturbation
dxmin = 1e-6;

% step size ( 0.33 causes instability, 0.2 quite accurate)
alpha = 0.1;

% initialize gradient norm, optimization vector, iteration counter, perturbation
gnorm = inf; x = x0; niter = 0; dx = inf;

% define the objective function:
f = @(x1,x2) x1.^2 + x1.*x2 + 3*x2.^2;

% plot objective function contours for visualization:
figure(1); clf; ezcontour(f,[-5 5 -5 5]); axis equal; hold on

% redefine objective function syntax for use with optimization:
f2 = @(x) f(x(1),x(2));

% gradient descent algorithm:
while and(gnorm>=tol, and(niter <= maxiter, dx >= dxmin))
    % calculate gradient:
    g = grad(x);
    gnorm = norm(g);
    % take step:
    xnew = x - alpha*g;
    % check step
    if ~isfinite(xnew)
        display(['Number of iterations: ' num2str(niter)])
        error('x is inf or NaN')
    end
    % plot current point
    plot([x(1) xnew(1)],[x(2) xnew(2)],'ko-')
    refresh
    % update termination metrics
    niter = niter + 1;
    dx = norm(xnew-x);
    x = xnew;

end
xopt = x;
fopt = f2(xopt);
niter = niter - 1;

% define the gradient of the objective
function g = grad(x)
g = [2*x(1) + x(2)
    x(1) + 6*x(2)];


function [ THD, ph, amp ] = compute_THD( t,x, freq )
% function [ THD, ph, amp ] = compute_THD( t,x, freq )
%
% Written by Dr. Yoash Levron
% February 2013.
%
% computes the Total-Harmonic-Distortion (THD)
% of a signal x(t). The amplitude and phase of the
% basic harmonic are also computed. These values
% are typically useful in power systems, audio signal
% processing, and other related fields.
%
% DC offset does not affect THD.
%
% The function computes the basic harmonic
% of the signal, in the form:
% x(t) = amp*cos(w*t - ph) + (higher Harmonics)
% where :  w = 2*pi*freq
% so 'amp' and 'ph' are the phase and amplitude
% of the basic harmonic.
%
% inputs:
% t - [sec] time vector. (should be periodical with basic harmonic 'freq')
% x - signal vector.
% freq - [Hz] frequency of the basic harmonic.
%
% outputs:
% THD - total harmonic distortion (the scale is 1 = 100%).
% ph - [rad] phase of the basic harmonic.
% amp - Amplitude of the basic harmonic.

%%%%%%%%%%%% start function %%%%%%%%%%

%%% check that t,x are the same length
if (length(t) ~= length(x))
      'Error: t and x should be the same length'
      THD = NaN;   ph = NaN; amp = NaN;
      beep; return
end

if (size(t,2) == 1)
    t = t.';
end
if (size(x,2) == 1)
    x = x.';
end

%%% condition input time vector
input_error = 0;
%%% add two samples to complete the last cycle.
t = t - t(1);   % remove any time shift
dtt = t(end) - t(end-1);
t = [t (t(end)+dtt) (t(end)+2*dtt)];
x = [x x(end) x(end)];
T = t(end);
if (T < (1/freq) )
    input_error = 1;
end
if (input_error)
        'Error: Input time vector is illegal. Time samples should expand at least to 1/freq'
        THD = NaN;   ph = NaN; amp = NaN;
        beep; return
end

% truncate extra samples, to fit in an integer number of cycles of freq
T = floor(T * freq) /freq;

% resample on a linear grid:
% t1, x1 is the new input, not including the last sample
x = x - sum(x)/length(x);  % remove any DC offset
N = max(1e6, length(x));  % number of samples
dt = T/N;
t1 = 0:dt:(T-dt);
x1 = interp1(t,x,t1,'cubic');

%%% compute cos-sin fourier coefficients
w = 2*pi*freq;
acs = (2/T) * sum(x1.*cos(w*t1))*dt;  % basic frequency cos coefficient.
bsn = (2/T) * sum(x1.*sin(w*t1))*dt;  % basic frequency sin coefficient.
amp = (acs^2 + bsn^2)^0.5;
ph = pi/2 - sign(acs) * acos(bsn/amp);

rms22 = (2/T) * sum(x1.^2) * dt;
THD = (rms22/amp^2 - 1)^0.5;

% correct phase to be in the range [-pi : pi]
if (ph > pi)
    ph = ph - 2*pi;
end
if (ph < -pi)
    ph = ph + 2*pi;
end

end


function centroid = triangle_centroid_2d ( t )

%*****************************************************************************80
%
%% TRIANGLE_CENTROID_2D computes the centroid of a triangle in 2D.
%
%  Discussion:
%
%    The centroid of a triangle can also be considered the
%    center of gravity, or center of mass, assuming that the triangle
%    is made of a thin uniform sheet of massy material.
%
%    The centroid of a triangle is the intersection of the medians.
%
%    A median of a triangle is a line connecting a vertex to the
%    midpoint of the opposite side.
%
%    In barycentric coordinates, in which the vertices of the triangle
%    have the coordinates (1,0,0), (0,1,0) and (0,0,1), the centroid
%    has coordinates (1/3,1/3,1/3).
%
%    In geometry, the centroid of a triangle is often symbolized by "G".
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 January 2005
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Adrian Bowyer and John Woodwark,
%    A Programmer's Geometry,
%    Butterworths, 1983.
%
%  Parameters:
%
%    Input, real T(2,3), the triangle vertices.
%
%    Output, real CENTROID(2,1), the coordinates of the centroid.
%
  dim_num = 2;

  for i = 1 : dim_num
    centroid(i,1) = sum ( t(i,1:3) ) / 3.0;
  end

  return
end


% 近似计算 算法稳定性的演示
clear;

% 解法一   n从小到大
S0 = 0.182;
S(1) = 1 - 5*S0;
for n = 2 : 8
    S(n) = 1/n - 5*S(n-1);
    S(n) = vpa(S(n),3);
end
disp('解法一：')
disp(S)

% 解法二   n从大到小
S(8) = 0.0204;
for n = 8: -1 : 2
    S(n-1) = 1/(5*n) - S(n)/5;
    S(n-1) = vpa(S(n-1),3);
end
disp('解法二：')
disp(S)

% 精确值
syms x
for n = 1 : 5 % 8
    S(n) = int(x^n/(x+5),0,1);
    S(n) = vpa(S(n),3);
end
disp('精确值：')
disp(S)


function Q=cotes(f,a,b,N,nodes)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% cotes.m
%
% 2 to 11 point Summed Newton-Cotes numerical integration formulas.
%
% Inputs:
%
% f - function to be integrated
% a - lower limit of integration
% b - upper limit of integration
% N - Requested number of grid points
% nodes - number of nodes in Newton-Cotes formula
%
% Sample Usage:
%
% >>cotes(@sin,0,pi/2,20,5)
%
% ans =
%         0.999999999501637
%
% Written by: Greg von Winckel
% Contact: gregvw(at)math(dot)unm(dot)edu
% URL: http://math.unm.edu/~gregvw
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

N = (nodes-1)*ceil(N/(nodes-1));  N1=N+1;
x = linspace(a,b,N1)';
h = x(2)-x(1);    g=f(x);

endpts = g(1)+g(N1);

switch nodes

    case{2} % Trapezoidal Rule
    Q=(h/2)*(endpts+2*sum(g(2:N)));

    case{3} % Simpson's Rule
    Q=(h/3)*(endpts+4*sum(g(2:2:N))+2*sum(g(3:2:N)));

    case{4} % Simpson's 3/8 Rule
    Q=(3*h/8)*(endpts+3*sum(g(2:3:N)+g(3:3:N))+2*sum(g(4:3:N)));

    case{5} % Boole's 4/90 Rule
    Q=(4*h/90)*(7*endpts+32*sum(g(2:4:N))+...
        12*sum(g(3:4:N))+32*sum(g(4:4:N))+14*sum(g(5:4:N)));

    case{6}
    Q=(5*h/288)*(19*endpts+75*sum(g(2:5:N)+g(5:5:N))+...
        50*sum(g(3:5:N)+g(4:5:N))+38*sum(g(6:5:N)));

    case{7}
    Q=(6*h/840)*(41*endpts+216*sum(g(2:6:N)+g(6:6:N))+...
        27*sum(g(3:6:N)+g(5:6:N))+272*sum(g(4:6:N))+...
        +82*sum(g(7:6:N)));

    case{8}
    Q=(7*h/17280)*(751*endpts+3577*sum(g(2:7:N)+g(7:7:N))+...
        1323*sum(g(3:7:N)+g(6:7:N))+2989*sum(g(4:7:N)+g(5:7:N))+...
        +1502*sum(g(8:7:N)));

    case{9}
    Q=(4*h/14175)*(989*endpts+5888*sum(g(2:8:N)+g(8:8:N))-...
       928*sum(g(3:8:N)+g(7:8:N))+10496*sum(g(4:8:N)+g(6:8:N))-...
       4540*sum(g(5:8:N))+1978*sum(g(9:8:N)));

    case{10}
    Q=(9*h/89600)*(2857*endpts+15741*sum(g(2:9:N)+g(9:9:N))+...
       1080*sum(g(3:9:N)+g(8:9:N))+19344*sum(g(4:9:N)+g(7:9:N))+...
       5778*sum(g(5:9:N)+g(6:9:N))+5714*sum(g(10:9:N)));

    case{11}
    Q=(5*h/299376)*(16067*endpts+106300*sum(g(2:10:N)+g(10:10:N))-...
       48525*sum(g(3:10:N)+g(9:10:N))+272400*sum(g(4:10:N)+g(8:10:N))-...
       260550*sum(g(5:10:N)+g(7:10:N))+427368*sum(g(6:10:N))+...
       32134*sum(g(11:10:N)));
    otherwise
        error('Order must be between 2 and 11');
end


function angles = polyangles(x,y)
%POLYANGLES Computes internal polygon angles.
%	ANGLES = POLYANGLES(X,Y) computes the interior angles (in degrees) of
%	an arbitrary polygon whose vertices have x- and y-coordinates given
%	in column vectors X and Y. The vertices must be arranged in a
%	clockwise manner.  The program eliminates duplicate adjacent rows in
%	[X,Y], except that the first row may equal the last, so that the
%	polygon is closed.
%
%   Copyright 2002-2020 Gatesmark
%
%   This function, and other functions in the DIPUM Toolbox, are based
%   on the theoretical and practical foundations established in the
%   book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark
%   Press, 2020.
%
%   Book website: http://www.imageprocessingplace.com
%   License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt

% Preliminaries.
xy = [x(:),y(:)];
if isempty(xy)
    % No vertices!
    angles = zeros(0,1);
    return
end

% Close the polygon if necessary.
if (size(xy,1) == 1) || ~isequal(xy(1,:),xy(end,:))
    xy = [xy;xy(1,:)];
end

% Eliminate duplicate vertices.
if size(xy,1) > 2
    xy(all(diff(xy,1,1) == 0,2),:) = [];
end

% Form a set of vectors by taking the differences between adjacent
% vertices in the polygon.  These vectors form a chain directed in the
% clockwise direction because of the way the data is input.
v2 = diff(xy,1,1);

% Each angle of the polygon is formed by the head of a vector joining
% the tail of the vector following it in the sequence. Each vector in
% the following array precedes its corresponding vector in v2:
v1 = circshift(v2,[1 0]);

% Get the x- and y-components of each vector.
v1x = v1(:,1);
v1y = v1(:,2);
v2x = v2(:,1);
v2y = v2(:,2);

% The angles between the vectors in v2 relative to the vectors in v1 is
% given by the following expression. See, for example,
% http://www.euclideanspace.com/maths/algebra/vectors/ and (select
% "angle between" for an explanation of this expression).
angles = (180/pi)*(atan2(v2y,v2x) - atan2(v1y,v1x));

% Because the head of each vector in v1 points to the tail of the
% subsequent vector in v2 (see above), the preceding expression gives
% "outer" angles. We need the interior angles of the polygon. To do
% this, we have to reverse the direction of one of the vectors or,
% equivalently, add (or subtract) 180 degrees from the previous result.
% We also want to make sure that all angles are in the range 0 to 360
% degrees. The following expression implements both requirements:
angles = mod(angles + 180,360);


function [cRow, cCol, ra, rb, phi] = gauss2ellipse( mu, C, rad )
% Creates an ellipse representing the 2D Gaussian distribution.
%
% Creates an ellipse representing the 2D Gaussian distribution with mean mu
% and covariance matrix C.  Returns 5 parameters that specify the ellipse.
%
% USAGE
%  [cRow, cCol, ra, rb, phi] = gauss2ellipse( mu, C, [rad] )
%
% INPUTS
%  mu      - 1x2 vector representing the center of the ellipse
%  C       - 2x2 cov matrix
%  rad     - [2] Number of std to create the ellipse to
%
% OUTPUTS
%  cRow    - the row location of the center of the ellipse
%  cCol    - the column location of the center of the ellipse
%  ra      - semi-major axis length (in pixels) of the ellipse
%  rb      - semi-minor axis length (in pixels) of the ellipse
%  phi     - rotation angle (radians) of semimajor axis from x-axis
%
% EXAMPLE
%  [cRow, cCol, ra, rb, phi] = gauss2ellipse( [5 5], [1 0; .5 2] )
%  plotEllipse( cRow, cCol, ra, rb, phi );
%
% See also PLOTELLIPSE, PLOTGAUSSELLIPSES, MASKELLIPSE
%
% Piotr's Computer Vision Matlab Toolbox      Version 2.0
% Copyright 2014 Piotr Dollar.  [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]

if (nargin<3 || isempty(rad) ); rad=2; end;

% error check
if (~all(size(mu)==[1,2]) || ~all(size(C)==[2,2]))
  error('Works only for 2D Gaussians'); end

% decompose using SVD
[~,D,R] = svd(C);
normstd = sqrt( diag( D ) );

% get angle of rotation (in row/column format)
phi = acos(R(1,1));
if (R(2,1) < 0); phi = 2*pi - phi; end
phi = pi/2 - phi;

% get ellipse radii
ra = rad*normstd(1);
rb = rad*normstd(2);

% center of ellipse
cRow = mu(1);
cCol = mu(2);


% % See also plotbezierpatch3D.m

% % function to plot 3D cubic Bezier surface in many ways.

% % A Bezier surface is composed of one or more patches.
% % A patch is defined by 16 control points arranged in 4 x 4 x 3 matrix.
% % A control point has three coordinates (x,y,z)

% % Details
% % -> Input Matrix S stores all the control points of all the patches of
% %    a Bezier surface such that
% % -> S(:,:,:,k) holds control points of kth patch,
% %    where k=1..np and np is number of patches in the surface
% % -> Size of S(:,:,:,k) is 4 x 4 x 3, i.e., 16 control points and each
% %    control point has three coordinates (x,y,z)
% %    S(:,:,1,k): x-coordates of control points of kth patch as 4 x 4 matrix
% %    S(:,:,2,k): y-coordates of control points of kth patch as 4 x 4 matrix
% %    S(:,:,3,k): z-coordates of control points of kth patch as 4 x 4 matrix
% % -> Input Matrix Q stores interpolated values between control points
% %    Q is similar to S in format but has more values, i.e., it stores
% %    end control points and interpolated values.
% %    see the function bezierpatchinterp.m for more details

function plotbeziersurface3D(S,Q)

[r c dim np]=size(S);
% % np: number of patches

if dim > 3 or dim < 3
    error ('plotbeziersurface3D.m function handles only 3-D points')
end

az=21;  %azimuth
el=19;  %elevation.

lw=1; %plotting linewidth

str1='\bf Control Point';
str2='\bf Control Polygon';
str3='\bf Surface (bi-directional Bezier curve)';

% %-----------------------------------------------
% % For plotting it is convenient if we reshape the data
% % into vecotor format and separate (X,Y,Z) coordinates

xS=[]; yS=[]; zS=[];
for k=1:np
     xS =horzcat(xS, reshape(S(:,:,1,k),1,[]));
     yS =horzcat(yS, reshape(S(:,:,2,k),1,[]));
     zS =horzcat(zS, reshape(S(:,:,3,k),1,[]));
end

xQ=[]; yQ=[]; zQ=[];
for k=1:np
     xQ =horzcat(xQ, reshape(Q(:,:,1,k),1,[]));
     yQ =horzcat(yQ, reshape(Q(:,:,2,k),1,[]));
     zQ =horzcat(zQ, reshape(Q(:,:,3,k),1,[]));
end
% %------------------------------------------------
% % Wireframe Plot of Bezier Surface using interpolation of control points
% % Control Points and Control Polygon are marked
figure, hold on
plot3(xS,yS,zS,'ro','LineWidth',lw)
plot3(xS,yS,zS,'g','LineWidth',lw)
plot3(xQ,yQ,zQ,'b','LineWidth',lw)
legend(str1,str2,str3);
title('\bf Wireframe Plot of a Bezier Surface with Control Points and Control Polygon')
view(3); box;  view(az,el)
% %-----------------------------------------------
% % Wireframe Plot of Bezier Surface using interpolation of control points
figure, hold on
plot3(xQ,yQ,zQ,'b','LineWidth',lw)
legend(str3);
title('\bf Wireframe Plot of a Bezier Surface')
view(3); box;  view(az,el)
% %-----------------------------------------------
% % Plot of Surface using control points
figure, hold on
for k=1:np
    surface(S(:,:,1,k),S(:,:,2,k),S(:,:,3,k),'FaceColor','green')
end
title('\bf Bezier Surface using Control Points');
view(3); box;  view(az,el)
% %-----------------------------------------------
% % Plot of Surface using interpolation of control points
figure, hold on
for k=1:np
    surface(Q(:,:,1,k),Q(:,:,2,k),Q(:,:,3,k),'FaceColor','green')
end
title('\bf Bezier Surface using Interpolated Points');
view(3); box;  view(az,el)

% %-----------------------------------------------
% % Surface with interpolated shading
figure, hold on
for k=1:np
    surface(Q(:,:,1,k),Q(:,:,2,k),Q(:,:,3,k))
end
shading interp
title('\bf Bezier Surface using Interpolated Shading');
view(3); box;  view(az,el)
% %-----------------------------------------------%
% % Surface with faceted shading
figure, hold on
for k=1:np
    surface(Q(:,:,1,k),Q(:,:,2,k),Q(:,:,3,k))
end
shading faceted
title('\bf Bezier Surface using Faceted Shading');
view(3); box;  view(az,el)
% %-----------------------------------------------%

% % --------------------------------
% % This program or any other program(s) supplied with it does not provide any
% % warranty direct or implied.
% % This program is free to use/share for non-commerical purpose only.
% % Kindly reference the author.
% % Author: Dr. Murtaza Khan
% % URL : http://www.linkedin.com/pub/dr-murtaza-khan/19/680/3b3
% % --------------------------------


function cdf = inverse_gaussian_cdf ( x, a, b )

%*****************************************************************************80
%
%% INVERSE_GAUSSIAN_CDF evaluates the Inverse Gaussian CDF.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X, the argument of the CDF.
%    0.0 < X.
%
%    Input, real A, B, the parameters of the PDF.
%    0.0 < A,
%    0.0 < B.
%
%    Output, real CDF, the value of the CDF.
%
  if ( x <= 0.0 )

    cdf = 0.0;

  else

    x1 = sqrt ( b / x ) * ( x - a ) / a;
    cdf1 = normal_01_cdf ( x1 );

    x2 = - sqrt ( b / x ) * ( x + a ) / a;
    cdf2 = normal_01_cdf ( x2 );

    cdf = cdf1 + exp ( 2.0 * b / a ) * cdf2;

  end

  return
end


function x= BesseliRatio(nu,kappa,maxIter)
%%BESSELIRATIO Evaluate the ratio of modified Bessel functions of the first
%              kind of the form x=I_{nu}(kappa)/I_{nu-1}(kappa).
%
%INPUTS: nu The positive integer (upper) order of the modified Bessel
%           function of the first kind in the ratio; nu>=1.
%     kappa The real argument of the modified Bessel function of the first
%           kind; kappa>=0.
%   maxIter An optional parameter specifying the maximum number of
%           iterations to use for computing the ratio using an iterative
%           method. If this parameter is omitted or an empty matrix is
%           passed, the default value of 2000 is used. Convergence usually
%           occurs long before the maximum number of iterations is reached.
%
%OUTPUTS: x The value of the ratio I_{nu}(kappa)/I_{nu-1}(kappa).
%
%Numerical precision limitations can make the evaluation of Bessel function
%radios difficult if one tries to explicitly evaluate the functions. Here,
%the algorithm of Perron described in [1] is implemented.
%
%REFERENCES:
%[1] W. Gautschi and J. Slavik, "On the computation of modified Bessel
%    function ratios," Mathematics of Computation, vol. 32, no. 143, pp.
%    865-875, Jul. 1978.
%
%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

    if(nargin<3||isempty(maxIter))
        %It usually converges long before the maximum number of iterations.
        maxIterations=2000;
    end
    %tolerance for convergence. This should be suitable for double-
    %precision computations.
    tol=1e-15;

    k=1;
    cumProd=1;
    pCur=0.5*kappa*(nu+0.5)/((nu+kappa/2)*(nu+kappa+0.5)-0.5*kappa*(nu+0.5));
    cumProd=cumProd*pCur;
    cumSum=1+cumProd;
    while(k<maxIterations)
        pPrev=pCur;
        k=k+1;
        pCur=0.5*kappa*(nu+k-0.5)*(1+pPrev)/((nu+kappa+(k-1)/2)*(nu+kappa+k/2)-0.5*kappa*(nu+k-0.5)*(1+pPrev));
        cumProd=cumProd*pCur;

        cumSumNew=cumSum+cumProd;
        %If we have hit a precision limit; this usually happens before k
        %gets too big.
        if(abs(cumSumNew-cumSum)<tol)
            break;
        end
        cumSum=cumSumNew;
    end
    a0=(kappa+2*nu)/kappa;
    x=cumSum/a0;
end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.


function x = triangle_area_sample ( n, v )

%*****************************************************************************80
%
%% TRIANGLE_AREA_SAMPLE samples points from the interior of a triangle.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 May 2013
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Greg Turk,
%    Generating Random Points in a Triangle,
%    in Graphics Gems,
%    edited by Andrew Glassner,
%    AP Professional, 1990, pages 24-28.
%
%  Parameters:
%
%    Input, integer N, the number of samples to compute.
%
%    Input, real V(2,3), the vertices.
%
%    Output, real X(2,N), the points.
%
  r = rand ( 2, n );

  c = zeros ( 3, n );

  c(1,1:n) = 1.0                 - sqrt ( r(2,1:n) );
  c(2,1:n) = ( 1.0 - r(1,1:n) ) .* sqrt ( r(2,1:n) );
  c(3,1:n) =         r(1,1:n)   .* sqrt ( r(2,1:n) );

  x = v * c;

  return
end


function fx = p11_fun ( n, x )

%*****************************************************************************80
%
%% P11_FUN evaluates the integrand for problem 11.
%
%  Interval:
%
%    0 <= x <= 1
%
%  Integrand:
%
%    1 / ( 1 + exp ( x ) )
%
%  Antiderivative:
%
%    ln ( exp ( x ) / ( 1 + exp ( x ) ) )
%
%  Exact Integral:
%
%    ln ( 2 * E / ( 1 + E ) )
%
%  Approximate Integral (20 digits):
%
%    0.37988549304172247537...
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 November 2009
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    David Kahaner,
%    Comparison of Numerical Quadrature Formulas,
%    in Mathematical Software, edited by John R Rice,
%    Academic Press, 1971.
%
%  Parameters:
%
%    Input, integer N, the number of evaluation points.
%
%    Input, real X(N), the evaluation points.
%
%    Output, real FX(N), the integrand values.
%
  fx = 1.0 ./ ( 1.0 + exp ( x ) );

  return
end


function fx = p20_fun ( option, nvar, x )

%*****************************************************************************80
%
%% P20_FUN evaluates the function for problem 20.
%
%  Title:
%
%    The Buckling Spring
%
%  Description:
%
%    We are given three points A, B, and C.
%    A is at the origin (0,0).
%    B has coordinates (X,Y) with Y nonnegative, and the ray from A to B
%    makes an angle of THETA with the horizontal axis.
%    C is at the point (2*X,0).
%
%    A spring extends from A to B, and is normally of length 1,
%    and is currently of length L.
%    A spring extends from B to C, and is normally of length 1,
%    and is currently of length L.
%    A spring force is also exerted, which tends to draw the two
%    springs together, proportional to the angle between the two springs.
%
%    A vertical load MU is applied at point B (downward is positive).
%    A horizontal load is applied at point C (leftware is positive).
%    The spring force is applied perpendicularly to the axes of the two springs.
%
%    If we compute F(1), the force along the axis of one spring, and
%    F(2), the force perpendicular to the axis of one spring, we have that
%    F(L,THETA,LAMBDA,MU) is given by:
%
%    F(1) =  - 2 ( 1 - L ) + 2 * LAMBDA * cos ( THETA ) + MU * sin ( THETA )
%    F(2) =  0.5 * THETA - 2 * LAMBDA * L * sin ( THETA ) + MU * L * cos ( THETA )
%
%    The user must specify a third, augmenting equation, of the form
%
%    F(3) = X(HOLD_INDEX) - HOLD_VALUE.
%
%    Typically, HOLD_INDEX is 2, for the varlable THETA, and HOLD_VALUE is
%    an angle measured in radians and strictly between 0 and PI/2.
%
%    Another choice for HOLD_INDEX would be 1, for the variable L, with
%    HOLD_VALUE greater than 0.  Values of L less than 1 represent compressed
%    springs; values greater than 1 indicate extended springs.
%
%    L represents the length of a spring.
%    THETA represents the angle that the spring makes with the horizontal axis.
%    MU is a vertical load applied at the midpoint B.
%    LAMBDA is a horizontal load applied at the right endpoint C.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 October 2008
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Tim Poston, Ian Stewart,
%    Catastrophe Theory and its Applications,
%    Dover, 1996,
%    ISBN13: 978-0486692715,
%    LC: QA614.58.P66.
%
%  Parameters:
%
%    Input, integer OPTION, the option index.
%
%    Input, integer NVAR, the number of variables.
%
%    Input, real X(NVAR), the argument of the function.
%
%    Output, real FX(NVAR-1), the value of the function at X.
%
  l      = x(1);
  theta  = x(2);
  lambda = x(3);
  mu     = x(4);

  fx = zeros ( nvar - 1, 1 );

  fx(1) = - 2.0 * ( 1.0 - l ) ...
          + 2.0 * lambda * cos ( theta ) ...
          + mu * sin ( theta );

  fx(2) = 0.5 * theta ...
          - 2.0 * lambda * l * sin ( theta ) ...
          + mu * l * cos ( theta );

  hold_index = p20_i4_get ( 'hold_index' );
  hold_value = p20_r8_get ( 'hold_value' );

  fx(3) = x(hold_index) - hold_value;

  return
end


function [ xtab_new, ytab_new, weight_new ] = ...
  triangle_rule_adjust ( xval, yval, norder, xtab, ytab, weight )

%*****************************************************************************80
%
%% TRIANGLE_RULE_ADJUST adjusts a unit quadrature rule to an arbitrary triangle.
%
%  Integration region:
%
%    Points (X,Y) such that:
%
%      (X,Y) = ALPHA * (X1,Y1) + BETA * (X2,Y2) + ( 1 - ALPHA - BETA ) * (X3,Y3)
%      0 <= ALPHA <= 1 - BETA
%      0 <= BETA <= 1 - ALPHA
%
%  Discussion:
%
%    This routine accepts as input abscissas and weights appropriate for
%    quadrature in a unit triangle, and returns abscissas and weights
%    appropriate for quadrature in a given triangle.
%
%    Once this routine has been called, an integral over the given triangle
%    can be approximated as:
%
%      QUAD = Sum ( 1 <= I <= NORDER ) WTAB2(I) * FUNC ( XTAB2(I), YTAB2(I) )
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 May 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real XVAL(3), YVAL(3), the coordinates of the nodes.
%
%    Input, integer NORDER, the order of the rule.
%
%    Input, real XTAB(NORDER), YTAB(NORDER), the abscissas for
%    a unit triangle.
%
%    Input, real WEIGHT(NORDER), the weights for a unit triangle.
%
%    Output, real XTAB_NEW(NORDER), YTAB_NEW(NORDER), the adjusted
%    abscissas.
%
%    Output, real WEIGHT_NEW(NORDER), the adjusted weights.
%
  volume = triangle_volume ( xval, yval );

  xtab_new(1:norder) = ...
                  xtab(1:norder)                    * xval(1) ...
                                 + ytab(1:norder)   * xval(2) ...
    + ( 1.0E+00 - xtab(1:norder) - ytab(1:norder) ) * xval(3);

  ytab_new(1:norder) = ...
                  xtab(1:norder)                    * yval(1) ...
                                 + ytab(1:norder)   * yval(2) ...
    + ( 1.0E+00 - xtab(1:norder) - ytab(1:norder) ) * yval(3);

  weight_new(1:norder) = weight(1:norder) * 2.0E+00 * volume;

  return
end


function variance = r8vec_variance ( n, x )

%*****************************************************************************80
%
%% R8VEC_VARIANCE returns the variance of an R8VEC.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of entries in the vector.
%
%    Input, real X(N), the vector whose variance is desired.
%
%    Output, real VARIANCE, the variance of the vector entries.
%
  mean = r8vec_mean ( n, x );

  variance = sum ( ( x(1:n) - mean ).^2 );

  if ( 1 < n )
    variance = variance / ( n - 1 );
  else
    variance = 0.0;
  end

  return
end


function x = ACR(p,n,alpha);
%ACR Upper percentiles critical value for test of single multivariate normal outlier.
% From the method given by Wilks (1963) and approaching to a F distribution
% function by the Yang and Lee (1987) formulation, we provide an m-file to
% get the critical value of the maximun squared Mahalanobis distance to detect
% outliers from a normal multivariate sample.
%
% Syntax: function x = ACR(p,n,alpha)
%   $$ The function's name is giving as a gratefull to Dr. Alvin C. Rencher for his
%      unvaluable contribution to multivariate statistics with his text 'Methods of
%      Multivariate Analysis'.$$
%
%     Inputs:
%          p - number of independent variables.
%          n - sample size.
%      alpha - significance level (default = 0.05).
%
%     Output:
%          x - critical value of the maximun squared Mahalanobis distance.
%
% We can generate all the critical values of the maximun squared Mahalanobis
% distance presented on the Table XXXII of by Barnett and Lewis (1978) and
% Table A.6 of Rencher (2002). Also with any given significance level (alpha).
%
% Example: For p = 3; n = 25; alpha=0.01;
%
% Calling on Matlab the function:
%                ACR(p,n,alpha)
%
% Answer is:
%
%     13.1753
%
%  Created by A. Trujillo-Ortiz, R. Hernandez-Walls, A. Castro-Perez and K. Barba-Rojo
%             Facultad de Ciencias Marinas
%             Universidad Autonoma de Baja California
%             Apdo. Postal 453
%             Ensenada, Baja California
%             Mexico.
%             atrujo@uabc.mx
%
%  Copyright. August 20, 2006.
%
%  To cite this file, this would be an appropriate format:
%  Trujillo-Ortiz, A., R. Hernandez-Walls, A. Castro-Perez and K. Barba-Rojo. (2006).
%    ACR:Upper percentiles critical value for test of single multivariate normal outlier.
%    A MATLAB file. [WWW document]. URL http://www.mathworks.com/matlabcentral/
%    fileexchange/loadFile.do?objectId=12161
%
%  References:
%  Barnett, V. and Lewis, T. (1978), Outliers on Statistical Data.
%           New-York:John Wiley & Sons.
%  Rencher, A. C. (2002), Methods of Multivariate Analysis. 2nd. ed.
%            New-Jersey:John Wiley & Sons. Chapter 13 (pp. 408-450).
%  Wilks, S. S. (1963), Multivariate Statistical Outliers. Sankhya,
%            Series A, 25: 407-426.
%  Yang, S. S. and Lee, Y. (1987), Identification of a Multivariate
%            Outlier. Presented at the Annual  Meeting of the American
%            Statistical Association, San Francisco, August 1987.
%

if nargin < 3,
   alpha = 0.05; %(default)
end;

if (alpha <= 0 | alpha >= 1)
   fprintf('Warning: significance level must be between 0 and 1\n');
   return;
end;

if nargin < 2,
   error('Requires at least two input arguments.');
   return;
end;

a = alpha;
Fc = finv(1-a/n,p,n-p-1); %F distribution critical value with p and n-p-1 degrees of freedom using the Bonferroni correction.
ACR = (p*(n-1)^2*Fc)/(n*(n-p-1)+(n*p*Fc)); % = ((-1*((1/(1+(Fc*p/(n-p-1))))-1))*((n-1)^2))/n;
x = ACR;

return,


function value = angle_rad ( p1, p2, p3 )

%*****************************************************************************80
%
%% ANGLE_RAD returns the angle swept out between two rays.
%
%  Discussion:
%
%    Except for the zero angle case, it should be true that
%
%      ANGLE_RAD(P1,P2,P3) + ANGLE_RAD(P3,P2,P1) = 2 * PI
%
%        P1
%        /
%       /
%      /
%     /
%    P2--------->P3
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 December 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real P1(2,1), P2(2,1), P3(2,1), define the rays
%    P1 - P2 and P3 - P2 which in turn define the angle.
%
%    Output, real VALUE, the angle swept out by the rays, measured
%    in radians.  0 <= VALUE < 2*PI.  If either ray has zero length,
%    then VALUE is set to 0.
%
  p(1,1) = ( p3(1,1) - p2(1,1) ) * ( p1(1,1) - p2(1,1) ) ...
         + ( p3(2,1) - p2(2,1) ) * ( p1(2,1) - p2(2,1) );

  p(2,1) = ( p3(1,1) - p2(1,1) ) * ( p1(2,1) - p2(2,1) ) ...
         - ( p3(2,1) - p2(2,1) ) * ( p1(1,1) - p2(1,1) );

  if ( p(1,1) == 0.0 & p(2,1) == 0.0 )
    value = 0.0;
    return
  end

  value = atan2 ( p(2,1), p(1,1) );

  if ( value < 0.0 )
    value = value + 2.0 * pi;
  end

  return
end


function [phi,theta] = sphCoord(Coord3D)
% [phi,theta] = sphCoord(Coord3D)
%
% This function transforms spherical 3D XYZ spherical coordinates to 2D
% (theta,phi) spherical coordinates.
%
% Input
% Coord3D: Data Matrix with the spherical XYZ coordinates at the first
% three columns respectively.
%
% Output
% theta: Latitude
% phi: Longitud.
%
% $Revision: 1.2 $  $Date: 2015/01/06 17:14:55 $
% Original Author: Jorge Luis Bernal Rusiel
% CVS Revision Info:
%    $Author: mreuter $
%    $Date: 2015/01/06 17:14:55 $
%    $Revision: 1.2 $

% [theta,phi,r] = cart2sph(overlayData(:,1),overlayData(:,2),overlayData(:,3));
% //It was confusion

X=Coord3D(:,1); Y=Coord3D(:,2); Z=Coord3D(:,3);
phi=atan2(Y,X);
theta=atan2(sqrt(X.^2+Y.^2),Z);


function [fResult] = calc_log10poisspdf2(nX, fLambda)
    % Calculates the logarithm to the basis of 10 of the Poisson probability density function.
    % [fResult] = calc_log10poisspdf2(nX, fLambda)
    % --------------------------------------------------
    % Calculates the logarithm to the basis of 10 of the Poisson probability density function.
    % !!! Does not use zero values as input for fLambda!!!!!!
    %
    % Input parameters:
    %   nX          Parameter x (see help for 'poisspdf')
    %   fLambda     Parameter lambda (see help for 'poisspdf')
    %
    % Output parameters:
    %   fResult     Logarithm to the basis of 10 of the Poisson probability density
    %
    % J. Woessner, woessner@seismo.ifg.ethz.ch
    % updated: 03.12.2002

    % Create emtpy matrix for results
    fResult = zeros(size(nX));
    if isempty(fResult)
        return;
    end
    fResult(fLambda < 0) = NaN;

    % Select all computable elements
    vSel = (nX >= 0 & nX == round(nX) & fLambda > 0);

    % Adding of realmin to 0 cases is to get the effect of 0^0 = 1.
    if (any(vSel))
        fResult(vSel) = 1/log(10) * (-fLambda(vSel) + nX(vSel) .* log(fLambda(vSel) + realmin*(fLambda(vSel)==0)) ...
            - gammaln(nX(vSel) + 1));
        %fResult(vSel) = log10(poisspdf(nX(vSel),fLambda(vSel)));
    end
end


function theta = angle3Points(varargin)
%ANGLE3POINTS Compute oriented angle made by 3 points.
%
%   ALPHA = angle3Points(P1, P2, P3);
%   Computes the angle between the points P1, P2 and P3.
%   Pi are either [1*2] arrays, or [N*2] arrays, in this case ALPHA is a
%   [N*1] array. The angle computed is the directed angle between line
%   (P2P1) and line (P2P3).
%   Result is always given in radians, between 0 and 2*pi.
%
%   See Also:
%   points2d, angles2d, angle2points
%
%
%   ---------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% created the 23/02/2004.
% Copyright 2010 INRA - Cepia Software Platform.

%   HISTORY :
%   25/09/2005 : enable single parameter

if length(varargin)==3
    p1 = varargin{1};
    p2 = varargin{2};
    p3 = varargin{3};
elseif length(varargin)==1
    var = varargin{1};
    p1 = var(1,:);
    p2 = var(2,:);
    p3 = var(3,:);
end

% angle line (P2 P1)
theta = lineAngle(createLine(p2, p1), createLine(p2, p3));


function J = computeCostMulti(X, y, theta)
%COMPUTECOSTMULTI Compute cost for linear regression with multiple variables
%   J = COMPUTECOSTMULTI(X, y, theta) computes the cost of using theta as the
%   parameter for linear regression to fit the data points in X and y

% Initialize some useful values
m = length(y); % number of training examples

% You need to return the following variables correctly
J = 0;

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta
%               You should set J to the cost.

J = (((X*theta)-y)' * ((X*theta)-y))/(2*m);

% =========================================================================

end


function [U, S] = pca(X)
%PCA Run principal component analysis on the dataset X
%   [U, S, X] = pca(X) computes eigenvectors of the covariance matrix of X
%   Returns the eigenvectors U, the eigenvalues (on diagonal) in S
%

% Useful values
[m, n] = size(X);

% You need to return the following variables correctly.
U = zeros(n);
S = zeros(n);

% ====================== YOUR CODE HERE ======================
% Instructions: You should first compute the covariance matrix. Then, you
%               should use the "svd" function to compute the eigenvectors
%               and eigenvalues of the covariance matrix.
%
% Note: When computing the covariance matrix, remember to divide by m (the
%       number of examples).
%

sigma = X' * X / m;
[U,S,V] = svd(sigma);

% =========================================================================

end


function [data_mean,data_diff,md,sd] = bland_altman(data1,data2)
% Function to generate Bland Altman plots. Barry Greene, September 2008
% Bland, J.M., Altman, D.G. 'Statistical methods for assessing agreement ...
% between two methods of clinical measurement'(1986) Lancet, 1 (8476), pp. 307-310.
% Inputs: data1: Data from first instrument
%         data2: Data from second instument
% Produces Bland Altman plot with mean difference and mean difference +/-
% 2*SD difference lines.

[m,n] = size(data1);
if(n>m)
    data1 = data1';
end

if(size(data1)~=size(data2))
    error('Data matrices must be the same size')
end

data_mean = mean([data1,data2],2);  % Mean of values from each instrument
data_diff = data1 - data2;              % Difference between data from each instrument
md = mean(data_diff);               % Mean of difference between instruments
sd = std(data_diff);                % Std dev of difference between instruments

% figure;
plot(data_mean,data_diff,'ok','MarkerSize',3,'LineWidth',1);   % Bland Altman plot
hold on; x = [min(data_mean),max(data_mean)];
y = md*ones(1,2); plot(x,y,'-k'); % Mean difference line
y = md+2*sd*ones(1,2);
plot(x,y,'--k'); % Mean plus 2*SD line
% text(x(2),y(2),'+2 SD');
y = md-2*sd*ones(1,2);
plot(x,y,'--k'); % Mean minus 2*SD line

% text(x(2),y(2),'-2 SD');
% grid on
% title('Bland Altman plot','FontSize',9)
% xlabel('Mean of two measures','FontSize',8)
% ylabel('Difference between two measures','FontSize',8)


function a = forsythe ( alpha, beta, n )

%*****************************************************************************80
%
%% FORSYTHE returns the FORSYTHE matrix.
%
%  Discussion:
%
%    The Forsythe matrix represents a Jordan canonical matrix, perturbed
%    by a rank one update.
%
%  Formula:
%
%    If ( I = J )
%      A(I,J) = BETA
%    else if ( J = I+1 )
%      A(I,J) = 1
%    else if ( I = N and J = 1 ) then
%      A(I,J) = ALPHA
%    else
%      A(I,J) = 0
%
%  Example:
%
%    ALPHA = 2, BETA = 3, N = 5
%
%    3 1 0 0 0
%    0 3 1 0 0
%    0 0 3 1 0
%    0 0 0 3 1
%    2 0 0 0 3
%
%  Properties:
%
%    A is generally not symmetric: A' /= A.
%
%    A is Toeplitz: constant along diagonals.
%
%    A is persymmetric: A(I,J) = A(N+1-J,N+1-I).
%
%    The characteristic equation of A is
%
%      ( BETA - LAMBDA )^N - (-1)^N*ALPHA = 0
%
%    The eigenvalues of A are
%
%      LAMBDA(I) = BETA
%        + abs ( ALPHA )^1/N * exp ( 2 * I * PI * sqrt ( - 1 ) / N )
%
%    Gregory and Karney consider the special case where BETA is 0,
%    and ALPHA is a "small" value.  In that case, the characteristic
%    equation is LAMBDA^N - ALPHA = 0, and the eigenvalues are the
%    N-th root of ALPHA times the N roots of unity.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Robert Gregory, David Karney,
%    Example 5.22,
%    A Collection of Matrices for Testing Computational Algorithms,
%    Wiley, New York, 1969, page 103,
%    LC: QA263.G68.
%
%  Parameters:
%
%    Input, real ALPHA, BETA, define the matrix.  A typical
%    value of ALPHA is the square root of the machine precision; a typical
%    value of BETA is 0.0.
%
%    Input, integer N, the order of A.
%
%    Output, real A(N,N), the matrix.
%
  a = zeros ( n, n );

  for i = 1 : n
    for j = 1 : n

      if ( j == i )
        a(i,j) = beta;
      elseif ( j == i + 1 )
        a(i,j) = 1.0;
      elseif ( i == n & j == 1 )
        a(i,j) = alpha;
      else
        a(i,j) = 0.0;
      end

    end
  end

  return
end


function varargout = drawAngleBetweenVectors3d(o, v1, v2, r, varargin)
%DRAWANGLEBETWEENVECTORS3D Draw an arc between 2 vectors.
%
%   drawAngleBetweenVectors3d(ORIGIN, VECTOR1, VECTOR2, RADIUS)
%   draws the arc between VECTOR1 and VECTOR2.
%
%   drawAngleBetweenVectors3d(...,'ConjugateAngle',1) draws the conjugate
%   angle instead of the small angle. Default is false.
%
%   H = drawAngleBetweenVectors3d(...)
%   returns the handle of the created LINE object
%
%   Example
%     o=-100 + 200*rand(1,3);
%     v1=normalizeVector3d(-1 + 2*rand(1,3));
%     v2=normalizeVector3d(-1 + 2*rand(1,3));
%     r = rand;
%     figure('color','w'); view(3)
%     hold on; axis equal tight; xlabel X; ylabel Y; zlabel Z;
%     drawVector3d(o, v1, 'r')
%     drawVector3d(o, v2, 'g')
%     drawAngleBetweenVectors3d(o, v1, v2, r,'Color','m','LineWidth', 3)
%
%   See also
%     drawCircleArc3d

% ------
% Author: oqilipo
% E-mail: N/A
% Created: 2020-02-02
% Copyright 2020-2022

% parse axis handle
hAx = gca;
if isAxisHandle(o)
    hAx = o;
    o = v1;
    v1 = v2;
    v2 = r;
    r = varargin{1};
    varargin(1) = [];
end

p = inputParser;
p.KeepUnmatched = true;
logParValidFunc=@(x) (islogical(x) || isequal(x,1) || isequal(x,0));
addParameter(p,'ConjugateAngle',false,logParValidFunc);
parse(p, varargin{:});
conjugate=p.Results.ConjugateAngle;
drawOptions=p.Unmatched;

% Normal of the two vectors
normal=normalizeVector3d(crossProduct3d(v1, v2));
% Align normal with the z axis.
ROT = createRotationVector3d(normal,[0 0 1]);
% Align first vector with x axis
ROTv1 = createRotationVector3d(transformVector3d(v1,ROT),[1 0 0]);
% Get Euler angles of the arc.
% The arc is an flat object. Hence, use the 'ZYZ' convention.
[PHI, THETA, PSI] = rotation3dToEulerAngles((ROTv1*ROT)','ZYZ');
% Get angle between the vectors
angle=rad2deg(vectorAngle3d(v1, v2));
% Draw the arc
if ~conjugate
    h = drawCircleArc3d(hAx, [o r [THETA PHI PSI] 0 angle],drawOptions);
else
    h = drawCircleArc3d(hAx, [o r [THETA PHI PSI] 0 angle-360],drawOptions);
end

% Format output
if nargout > 0
    varargout{1} = h;
end


function probVal=bivarGaussRectangleCDF(rectMin,rectMax,mu,R)
%%BIVARGAUSSRECTANGLECDF Evaluate the an integral of the probability
%      density function of the bivariate normal distribution with a
%      specified mean and covariance matrix over a specified rectangular
%      region. In other words, it is the cumulative distribution function
%      (CDF) over a rectangular region.
%
%INPUTS: rectMin The 2X1 minimum bounds of the rectangular region.
%   rectMax The 2X1 maximum bounds of the rectangular region. Note that
%           rectMax>=rectMin.
%        mu The 2X1 mean of the distribution. If this is omitted or an
%           empty matrix is passed, then the default of [0;0] is used.
%         R The 2X2 covariance matrix of the distribution. If this is
%           omitted or an empty matrix is passed, then R=eye(2,2) is used.
%
%OUTPUTS: val The value of the integral.
%
%We can use the function bivarNormCDF to evaluate the probability of any
%region of the form Pr{x1<b(1), x2<b(2)). Consider 4 points of a rectangle
%dividing 2D space into 9 region.
%   a | b | c
% ----1---2---
%   d | e | f
% ----3---4---
%   g | h | i
%We would like to find the probability in region e. Well, if Pr{number} is
%the probability that everything is below and left of point specified by
%number (i.e. what one gets with the bivarNormCDF function), then one can
%write 4 equations in 4 unknowns:
% Pr{1}=Pr{d}+Pr{g}
% Pr{2}=Pr{d}+Pr{e}+Pr{g}+Pr{h}
% Pr{3}=Pr{g}
% Pr{4}=Pr{g}+Pr{h}
%where Pr{region name} is the probability of of that region. This is a
%system of 4 equation and 4 unknowns, and we solve it to find Pr{e}:
% Pr{e}=-Pr{1}+Pr{2}+Pr{3}-Pr{4}
%
%EXAMPLE 1:
%As a quick check, we know that the integral over the lower-left quadrant
%fof the bivarate normal distribution equals 0.25. That result is obtained
%here.
% mu=[0,;0];
% R=eye(2,2);
% rectMin=[-Inf;-Inf];
% rectMax=[0;0];
% P=bivarGaussRectangleCDF(rectMin,rectMax,mu,R)
%
%EXAMPLE 2:
%Here, we compare the result of this function with the lower-fidelity
%approximation from GaussianD.integralOverRegion. The values are in the
%general ballpark.
% mu=[1,;2];
% R=[3,-2;
%   -2, 4];
% rectMin=[-3;-2];
% rectMax=[2;1];
% P=bivarGaussRectangleCDF(rectMin,rectMax,mu,R)
% PApprox=GaussianD.integralOverRegion(mu,R,rectMin,rectMax)
%
%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public releas

if(nargin<4||isempty(R))
    R=eye(2,2);
end

if(nargin<3||isempty(mu))
    mu=[0;0];
end

p1=[rectMin(1);rectMax(2)];
p2=[rectMax(1);rectMax(2)];
p3=[rectMin(1);rectMin(2)];
p4=[rectMax(1);rectMin(2)];

Pr1=bivarNormCDF(p1,mu,R);
Pr2=bivarNormCDF(p2,mu,R);
Pr3=bivarNormCDF(p3,mu,R);
Pr4=bivarNormCDF(p4,mu,R);

%The min and max is just to handle finite precision effects making the
%result slightly invalid.
probVal=min(1,max(0,-Pr1+Pr2+Pr3-Pr4));

end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.


function AInterior=ellipsInsideConcEllips(A1,A2,gammaVal)
%%ELLIPSINSIDECONCELLIPS Given two concentric ellipsoids (they have the
%               same center), find the largest ellipsoid that fits inside
%               both of them. It will also have the same center.
%
%INPUTS: A1,A2 Two numDimXnumDim symmetric, positive definite matrices that
%           specify the size and shape of the ellipse or ellipsoid, where
%           a point zp is on the ellipse/ellipsoid if
%           (zp-z)'*A*(zp-z)=gammaVal.
%           %Both ellipsoids share the same center point, z.
%  gammaVal The threshold for declaring a point to be in the ellipsoid. If
%           this parameter is omitted or an empty matrix is passed, the
%           default value of 1 is used.
%
%OUTPUTS: AInterior A numDimXnumDim symmetric, positive definite matrix
%            that specifies the size and shape of the largest ellipse that
%            is within both of the ellipses.
%
%This function implements the algorithm that is given in Section 17 of [1].
%
%EXAMPLE:
% A1=[30,0;
%     0,1];
% A2=[1,0;
%     0,21];
% M=[0.413074198133900,  0.910697373904216;
%   -0.910697373904216,   0.413074198133900];%A rotation matrix
% A2=M*A2*M';
% AInterior=ellipsInsideConcEllips(A1,A2);
% figure(1)
% clf
% hold on
% drawEllipse([0;0],A1,1,'b','linewidth',4)
% drawEllipse([0;0],A2,1,'b','linewidth',4)
% drawEllipse([0;0],AInterior,1,'r','linewidth',2)
%
%REFERENCES:
%[1] S. B. Pope, "Algorithms for ellipsoids," Cornell University, Tech.
%    Rep. FDA-08-01, Feb. 2008. [Online].
%    Available: https://tcg.mae.cornell.edu/pubs/Pope_FDA_08.pdf
%
%May 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

if(nargin<3||isempty(gammaVal))
   gammaVal=1;
end

A1=A1/gammaVal;
A2=A2/gammaVal;

L1=chol(A1,'lower');
L2=chol(A2,'lower');

L2Prime=L1\L2;

[U,Sigma,~]=svd(L2Prime);
SigmaTilde=diag(max(diag(Sigma).^2,1));
APrime=U*SigmaTilde*U';
LPrime=chol(APrime,'lower');

L=L1*LPrime;
AInterior=L*L';

end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.


function area = triangle_area ( xa, ya, xb, yb, xc, yc )

%*****************************************************************************80
%
%% TRIANGLE_AREA computes the signed area of a triangle.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 February 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real XA, YA, XB, YB, XC, YC, the vertices.
%
%    Output, real AREA, the signed area of the triangle.
%
  area = 0.5 * ( ( xb - xa ) * ( yc - ya ) ...
               - ( xc - xa ) * ( yb - ya ) );

  return
end


function O = gs_orthonorm(M)
% O = gs_orthonorm(M)
%
% Classic Gram-Schmidt orthonormalization.
%
%                         PARAMETERS
%
% M A matrix with columns to be orthonormalized.
%
%                        RETURN VALUES
%
% O A matrix with orthonormal columns spanning the same
%   space as the columns in M. Linearly dependent vectors
%   are removed from the result.
%
% Author: Luca Vezzaro (elvezzaro@gmail.com)

	ncol = size(M, 2);

	% Zero threshold
	tol = 100 * eps;

	% Index to result column
	k = 1;

	for i=1:ncol
		% Column to orthogonalize
		v = M(:,i);

		% Subtract projections over previous vectors
		for j=1:k-1
			v = v - (O(:,j)' * v) * O(:,j);
		end

		% Only keep nonzero vectors
		n = norm(v);
		if n > tol
			% Normalize and store
			O(:,k) = v / n;
			k = k + 1;
		end
	end


function pdf = benford_pdf ( x )

%*****************************************************************************80
%
%% BENFORD_PDF returns the Benford probability of one or more significant digits.
%
%  Discussion:
%
%    Benford's law is an empirical formula explaining the observed
%    distribution of initial digits in lists culled from newspapers,
%    tax forms, stock market prices, and so on.  It predicts the observed
%    high frequency of the initial digit 1, for instance.
%
%    Note that the probabilities of digits 1 through 9 are guaranteed
%    to add up to 1, since
%      LOG10 ( 2/1 ) + LOG10 ( 3/2) + LOG10 ( 4/3 ) + ... + LOG10 ( 10/9 )
%      = LOG10 ( 2/1 * 3/2 * 4/3 * ... * 10/9 ) = LOG10 ( 10 ) = 1.
%
%    PDF(X) = LOG10 ( ( X + 1 ) / X ).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    F Benford,
%    The Law of Anomalous Numbers,
%    Proceedings of the American Philosophical Society,
%    Volume 78, pages 551-572, 1938.
%
%    T P Hill,
%    The First Digit Phenomenon,
%    American Scientist,
%    Volume 86, July/August 1998, pages 358 - 363.
%
%    R Raimi,
%    The Peculiar Distribution of First Digits,
%    Scientific American,
%    December 1969, pages 109-119.
%
%  Parameters:
%
%    Input, integer X, the string of significant digits to be checked.
%    If X is 1, then we are asking for the Benford probability that
%    a value will have first digit 1.  If X is 123, we are asking for
%    the probability that the first three digits will be 123, and so on.
%
%    Output, real PDF, the Benford probability that an item taken
%    from a real world distribution will have the initial digits X.
%
  if ( x <= 0 )
    pdf = 0.0;
  else
    pdf = log10 ( ( x + 1 ) / x );
  end

  return
end


function piece_num = slice ( dim_num, slice_num )

%*****************************************************************************80
%
%% SLICE: maximum number of pieces created by a given number of slices.
%
%  Discussion:
%
%    If we imagine slicing a pizza, each slice produce more pieces.
%    The position of the slice affects the number of pieces created, but there
%    is a maximum.
%
%    This function determines the maximum number of pieces created by a given
%    number of slices, applied to a space of a given dimension.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    31 March 2012
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Robert Banks,
%    Slicing Pizzas, Racing Turtles, and Further Adventures in
%    Applied Mathematics,
%    Princeton, 1999,
%    ISBN13: 9780691059471,
%    LC: QA93.B358.
%
%  Parameters:
%
%    Input, integer DIM_NUM, the spatial dimension.
%
%    Input, integer SLICE_NUM, the number of slices.
%
%    Input, integer PIECE_NUM, the maximum number of pieces that can
%    be created by the given number of slices applied in the given dimension.
%
  piece_num = 0;
  for j = 0 : min ( dim_num, slice_num )
    piece_num = piece_num + i4_choose ( slice_num, j );
  end

  return
end


%Example demonstrating peak interpolation (finds the peak of a function,
%interpolated between samples using the peak and its two neighbors).
%This example finds the peak of sin(2*pi*f*x+phi) for unevenly spaced x

N_p=10;%number of points
f=1/N_p;%frequency (relative to sampling frequency)

x=2*pi*rand(1,N_p);
x=sort(x);
y=sin(2*pi*f*x);

x_max_th=N_p/4;%theoretical x for maximum y
y_max_th=1;%theoretical maximum y

[y_max_int idx_max]=max(y);
x_max_int=x(idx_max);%integer estimate of peak position

%do a parabolic estimate
[x_max_p y_max_p A_p]=crit_interp_p(y(idx_max+(-1:1)),x(idx_max+(-1:1)));

%do a Gaussian estimate
[x_max_g y_max_g A_g]=crit_interp_g(y(idx_max+(-1:1)),x(idx_max+(-1:1)));

%plot the curves
N_plot=1000;%number of points to plot
x_plot=linspace(x(idx_max-2),x(idx_max+2),N_plot);
y_th=sin(2*pi*f*x_plot);
y_p=A_p(1)*x_plot.^2+A_p(2)*x_plot+A_p(3);
y_g=A_g(1)*exp(-A_g(2)*(x_plot-A_g(3)).^2);

fprintf('True: y_max=%f at x_max=%f\nParabolic Estimate: y_max=%f at x_max=%f\nGaussian Estimate: y_max=%f at x_max=%f\n',...
    y_max_th,x_max_th,y_max_p,x_max_p,y_max_g,x_max_g)

figure(1)
clf
subplot(2,1,1)
plot(x,y,'o',x_plot,y_th,'g',x_plot,y_p,'k',x_plot,y_g,'r')
xlabel('x')
ylabel('y')
legend('Sampled points','Theoretical Curve','Parabolic interpolation','Gaussian Interpolation','location','Best')

subplot(2,1,2)
plot(x(idx_max+(-1:1)),y(idx_max+(-1:1)),'o',x_plot,y_th,'g',x_plot,y_p,'k',x_plot,y_g,'r',x_max_p, y_max_p,'kx',x_max_g, y_max_g,'rx',x_max_th, y_max_th,'gx')
xlabel('x')
ylabel('y')
legend('Sampled points','Theoretical Curve','Parabolic interpolation','Gaussian Interpolation','location','Best')


function quality2 = tetrahedron_quality2_3d ( tetra )

%*****************************************************************************80
%
%% TETRAHEDRON_QUALITY2_3D: "quality" of a tetrahedron in 3D.
%
%  Discussion:
%
%    The quality measure #2 of a tetrahedron is:
%
%      QUALITY2 = 2 * sqrt ( 6 ) * RIN / LMAX
%
%    where
%
%      RIN = radius of the inscribed sphere;
%      LMAX = length of longest side of the tetrahedron.
%
%    An equilateral tetrahredron achieves the maximum possible quality of 1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 August 2005
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Qiang Du and Desheng Wang,
%    The Optimal Centroidal Voronoi Tesselations and the Gersho's
%    Conjecture in the Three-Dimensional Space,
%    Computers and Mathematics with Applications,
%    Volume 49, 2005, pages 1355-1373.
%
%  Parameters:
%
%    Input, real TETRA(3,4), the tetrahedron vertices.
%
%    Output, real QUALITY2, the quality of the tetrahedron.
%
  dim_num = 3;

  edge_length(1:6) = tetrahedron_edge_length_3d ( tetra );

  l_max = max ( edge_length(1:6) );

  [ r_in, pc ] = tetrahedron_insphere_3d ( tetra );

  quality2 = 2.0 * sqrt ( 6.0 ) * r_in / l_max;

  return
end


function theCombos=genAllRDCombinations(n,t,startVal)
%%GENALLRDCOMBINATIONS Generate all length t combinations of n elements
%                   (n>=t>1) in a resolving door gray-code order. This is
%                   such that the difference between each successiuve
%                   combination involves changing a single number.
%
%INPUTS: n The number of items from which t items are chosen; n>0.
%        t The number of items chosen, t<=n.
% startVal This is zero or 1, indicating which value the value at which the
%          elements in the combinations can start. The default if omitted
%          or an empty matrix is passed is 0;
%
%OUTPUTS: theCombos A tXnumCombos matrix containing all possible
%                   combinations of values in the "revolving door" order.
%
%This function implements algorithm R of Chapter 7.2.1.3 of [1].
%
%REFERENCES:
%[1] D. E. Knuth, The Art of Computer Programming. Vol. 4A: Combinatorial
%    Algorithms, Part I, Boston: Addison-Wesley, 2011.
%
%October 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

if(nargin<3||isempty(startVal))
    startVal=0;
end

if(n==t&&t==1)
    theCombos=startVal;
    return
end

numCombos=binomial(n,t);
theCombos=zeros(t,numCombos);

%Step R1, Initialization
c=[(0:(t-1)).';n];

for curCombo=1:numCombos
    %Step R2, visit the combination.
    theCombos(:,curCombo)=c(1:t);

    %Step R3
    if(mod(t,2)==1)
        if(c(1)+1<c(2))
            c(1)=c(1)+1;
            continue;
        else
            j=2;
            skip4=false;
        end
    else
        if(c(1)>0)
            c(1)=c(1)-1;
            continue;
        else
           j=2;
           skip4=true;
        end
    end

    while(1)
        if(skip4==false)
            %Step R4
            if(c(j)>=j)
                c(j)=c(j-1);
                c(j-1)=j-2;
                break;
            else
                j=j+1;
            end
        end
        skip4=false;

        %Step R5.
        if(c(j)+1<c(j+1))
            c(j-1)=c(j);
            c(j)=c(j)+1;
            break;
        end

        j=j+1;

        if(j<=t)
            continue;
        else
            if(startVal~=0)
                theCombos=theCombos+1;
            end

            return;
        end
    end
end

if(startVal~=0)
    theCombos=theCombos+1;
end

end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.


function bit = i4_bit_hi1 ( n )

%*****************************************************************************80
%
%% I4_BIT_HI1 returns the position of the high 1 bit base 2 in an integer.
%
%  Example:
%
%       N    Binary     BIT
%    ----    --------  ----
%       0           0     0
%       1           1     1
%       2          10     2
%       3          11     2
%       4         100     3
%       5         101     3
%       6         110     3
%       7         111     3
%       8        1000     4
%       9        1001     4
%      10        1010     4
%      11        1011     4
%      12        1100     4
%      13        1101     4
%      14        1110     4
%      15        1111     4
%      16       10000     5
%      17       10001     5
%    1023  1111111111    10
%    1024 10000000000    11
%    1025 10000000001    11
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 February 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the integer to be measured.
%    N should be nonnegative.  If N is nonpositive, the value will always be 0.
%
%    Output, integer BIT, the number of bits base 2.
%
  i = floor ( n );
  bit = 0;

  while ( 1 )

    if ( i <= 0 )
      break;
    end

    bit = bit + 1;
    i = floor ( i / 2 );

  end

  return
end


% Figure 8.11: Approximate linear discrimination via support vector classifier
% Section 8.6.1, Boyd & Vandenberghe "Convex Optimization"
% Original by Lieven Vandenberghe
% Adapted for CVX by Joelle Skaf - 10/16/05
% (a figure is generated)
%
% The goal is to find a function f(x) = a'*x - b that classifies the non-
% separable points {x_1,...,x_N} and {y_1,...,y_M} by doing a trade-off
% between the number of misclassifications and the width of the separating
% slab. a and b can be obtained by solving the following problem:
%           minimize    ||a||_2 + gamma*(1'*u + 1'*v)
%               s.t.    a'*x_i - b >= 1 - u_i        for i = 1,...,N
%                       a'*y_i - b <= -(1 - v_i)     for i = 1,...,M
%                       u >= 0 and v >= 0
% where gamma gives the relative weight of the number of misclassified
% points compared to the width of the slab.

% data generation
n = 2;
randn('state',2);
N = 50; M = 50;
Y = [1.5+0.9*randn(1,0.6*N), 1.5+0.7*randn(1,0.4*N);
     2*(randn(1,0.6*N)+1), 2*(randn(1,0.4*N)-1)];
X = [-1.5+0.9*randn(1,0.6*M),  -1.5+0.7*randn(1,0.4*M);
      2*(randn(1,0.6*M)-1), 2*(randn(1,0.4*M)+1)];
T = [-1 1; 1 1];
Y = T*Y;  X = T*X;
g = 0.1;            % gamma

% Solution via CVX
cvx_begin
    variables a(n) b(1) u(N) v(M)
    minimize (norm(a) + g*(ones(1,N)*u + ones(1,M)*v))
    X'*a - b >= 1 - u; %#ok
    Y'*a - b <= -(1 - v); %#ok
    u >= 0; %#ok
    v >= 0; %#ok
cvx_end

% Displaying results
linewidth = 0.5;  % for the squares and circles
t_min = min([X(1,:),Y(1,:)]);
t_max = max([X(1,:),Y(1,:)]);
tt = linspace(t_min-1,t_max+1,100);
p = -a(1)*tt/a(2) + b/a(2);
p1 = -a(1)*tt/a(2) + (b+1)/a(2);
p2 = -a(1)*tt/a(2) + (b-1)/a(2);

graph = plot(X(1,:),X(2,:), 'o', Y(1,:), Y(2,:), 'o');
set(graph(1),'LineWidth',linewidth);
set(graph(2),'LineWidth',linewidth);
set(graph(2),'MarkerFaceColor',[0 0.5 0]);
hold on;
plot(tt,p, '-r', tt,p1, '--r', tt,p2, '--r');
axis equal
title('Approximate linear discrimination via support vector classifier');
% print -deps svc-discr2.eps


function value = angle_rad_2d ( p1, p2, p3 )

%*****************************************************************************80
%
%% ANGLE_RAD_2D returns the angle swept out between two rays in 2D.
%
%  Discussion:
%
%    Except for the zero angle case, it should be true that
%
%      ANGLE_RAD_2D(P1,P2,P3) + ANGLE_RAD_2D(P3,P2,P1) = 2 * PI
%
%        P1
%        /
%       /
%      /
%     /
%    P2--------->P3
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 December 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real P1(2,1), P2(2,1), P3(2,1), define the rays
%    P1 - P2 and P3 - P2 which in turn define the angle.
%
%    Output, real VALUE, the angle swept out by the rays, measured
%    in radians.  0 <= VALUE < 2*PI.  If either ray has zero length,
%    then VALUE is set to 0.
%
  p(1,1) = ( p3(1,1) - p2(1,1) ) * ( p1(1,1) - p2(1,1) ) ...
         + ( p3(2,1) - p2(2,1) ) * ( p1(2,1) - p2(2,1) );

  p(2,1) = ( p3(1,1) - p2(1,1) ) * ( p1(2,1) - p2(2,1) ) ...
         - ( p3(2,1) - p2(2,1) ) * ( p1(1,1) - p2(1,1) );

  if ( p(1,1) == 0.0 & p(2,1) == 0.0 )
    value = 0.0;
    return
  end

  value = atan2 ( p(2,1), p(1,1) );

  if ( value < 0.0 )
    value = value + 2.0 * pi;
  end

  return
end


function value = h_hofstadter ( n )

%*****************************************************************************80
%
%% H_HOFSTADTER computes the Hofstadter H sequence.
%
%  Discussion:
%
%    H(N) = 0                          if N = 0
%         = N - H ( H ( H ( N - 1 ) ), otherwise.
%
%    H(N) is defined for all nonnegative integers.
%
%  Table:
%
%     N  H(N)
%    --  ----
%
%     0     0
%     1     1
%     2     1
%     3     2
%     4     3
%     5     4
%     6     4
%     7     5
%     8     5
%     9     6
%    10     7
%    11     7
%    12     8
%    13     9
%    14    10
%    15    10
%    16    11
%    17    12
%    18    13
%    19    13
%    20    14
%    21    14
%    22    15
%    23    16
%    24    17
%    25    17
%    26    18
%    27    18
%    28    19
%    29    20
%    30    20
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 July 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Douglas Hofstadter,
%    Goedel, Escher, Bach,
%    Basic Books, 1979.
%
%  Parameters:
%
%    Input, integer N, the argument of the function.
%
%    Output, integer VALUE, the value of the function.
%
  if ( n <= 0 )
    value = 0;
  else
    value = n - h_hofstadter ( h_hofstadter ( h_hofstadter ( n-1 ) ) );
  end

  return
end


function [x, y, z, it]=icosahedron_nodes(f, r)
% % Syntax;
% %
% % [x, y, z, it]=icosahedron_nodes(f, r);
% %
% % ***********************************************************
% %
% % Description
% %
% % Program makes the master triangle for an icosahedron of
% % f frequency of type 2.
% %
% % ***********************************************************
% %
% % Input Variables
% %
% % f is the frquency of the icosahedron.
% % f=2 is similar to a soccer ball.
% %
% % r is the radius of the icosahedron.
% %
% % ***********************************************************
% %
% % Output Variables
% %
% % x, y, and z are vectors with the rectangular coordinates for the nodes
% %             of a hemispherical icosahedron.
% %
% % it is the matrix of coordinate indices for the rectangular coordinate
% %    vectors.
% %
% % ***********************************************************
% %
%
% Example
%
% f=2;  % 2 frequency icosahedron.
%
% r=4;  % 4 meter radius.
%
% [x2, y2, z2, it]=icosahedron_nodes(f, r);
%
% %
% % ***********************************************************
% %
% % This program was written by Edward L. Zechmann
% %
% %     date     January 2007
% %
% % modified 11   March   2008  added examples
% %
% % ***********************************************************
% %
% % Feel free to modify this code.
% %

%calculate the coordinate indices
% i1 -> x
% i2 -> y
% i3 -> z

num_pts=0.5*((f+1)^2+(f+1));

it=zeros(3,num_pts);

for e1=1:(f+1);
    i1=f-e1+1;
    for e2=1:(e1);
        i2=(e2-1);
        i3=(f-i1-i2);

        a=e1+1;
        b=f+1;
        if a <= f+1;
            pt=0.5*(b^2+b-a^2+a)+i2+1;
        else
            pt=i2+1;
        end

        it(1, pt)=i1;
        it(2, pt)=i2;
        it(3, pt)=i3;
    end
end

x1=1:num_pts;
y1=1:num_pts;
z1=1:num_pts;

% Coordinate formulas for base pentagon
% Icosahedron class 1, type 2, frequency f
tau=0.5*(1+sqrt(5));

for e1=1:num_pts;

    i1=it(1, e1);
    i2=it(2, e1);
    i3=it(3, e1);

    x1(e1)=i1*sin(72/180*pi);
    y1(e1)=i2+i1*cos(72/180*pi);
    z1(e1)=f/2+i3/tau;

end

[rho, theta, phi]=spherical_angle_ed(x1, y1, z1);
[x, y, z]=spherical_to_rectangular(r, theta, phi);


[x,y,z]=peaks(7); figure(1),  mesh(x,y,z)

[xi,yi]=meshgrid(-3:0.2:3,-3:0.2:3);

z1=interp2(x,y,z,xi,yi,'nearest');

z2=interp2(x,y,z,xi,yi,'linear');

z3=interp2(x,y,z,xi,yi,'spline');

z4=interp2(x,y,z,xi,yi,'cubic');

figure(2),  subplot(2,2,1)

 mesh(xi,yi,z1)

title('nearest')

subplot(2,2,2)

mesh(xi,yi,z2)

 title('linear')

subplot(2,2,3)

 mesh(xi,yi,z3)

title('spiine')

subplot(2,2,4)

mesh(xi,yi,z4)

 title('cubic')