function val=sincFun(x)
%%SINCFUN Evaluate the sinc function. This is defined to be
%         sin(pi*x)/(pi*x). Note that some authors use the definition
%         sin(x)/x. This function accounts for the singularity at zero.
%
%INPUTS: x A matrix of the values at which to evaluate the sinc function.
%
%OUTPUTS: vals A matrix the same size as x where the sinc function has been
%              evaluted at each of the elements.
%
%The sinc function is described in [1]. It arises in many areas of signal
%processing.
%
%REFERENCES:
%[1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web
%    Resource. http://mathworld.wolfram.com/SincFunction.html
%
%November 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

    y=pi*x;
    sel=(y==0);
    val=sin(y)./y;
    val(sel)=1;
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 [rdiff, Z, pval, stats] = correl_compare_indep_inputr(r1, r2, N1, N2, varargin)
% Compare two Pearson's correlation values collected from independent samples
% :Based on: www.stat-help.com/
% :Usage:
% ::
%     [rdiff, Z, pval, stats] = correl_compare_indep_inputr(r1, r2, N1, N2, varargin)
%
% :Inputs:
%
%   **r1:**
%        Correlation coefficient for group 1
%
%   **r2:**
%        Correlation coefficient for group 2
%
%   **N1:**
%        Sample size for group 1
%
%   **N2:**
%        Sample size for group 2
%
% :Outputs:
%
%   **rdiff:**
%        Difference in correlation coefficient matrices (r1 - r2)
%
%   **Z:**
%        Z score for difference in correlation coefficients.
%
%   **pval:**
%        p value for two-tailed z-test
%
%   **stats:**
%        Structure of variables including r1, r2, N1, N2, rdiff, zdiff, Z,
%        pval, myalpha, sig
%
% :Examples:
% ::
%
%    %generate two random input matrices (20 subjects x 5 variables)
%    r1 = .77;
%    r2 = .33;
%    N1 = 100;
%    N2 = 100;
%
%   [rdiff, Z, pval, stats] = correl_compare_indep_inputr(r1, r2, N1, N2);
%
%
% :See also:
%   - correl_compare_indep_inputr, correl_compare_permute*
%
%
% ..
%    Tor Wager, March 2010
% ..

    if nargin == 0
        disp('Using sample values for r1 r2 N1 N2')
        N1 = 100;
        N2 = 100;
        r1 = .33;
        r2 = .77;
    end

    rdiff = r1 - r2;

    sediff = sqrt(1/(N1-3) + 1/(N2-3));  % Standard error of difference between two standard normals, with df = N - 3 for correlation coeff
    zdiff = fisherz(r1) - fisherz(r2);  % difference in Fisher's z values

    Z = zdiff ./ sediff;   % Z-score (inferential stat)

    pval = 2 * (1 - normcdf(abs(Z))); % p-value

    myalpha = .05;  % ROI
    sig = pval < myalpha;

    stats = struct('r1', r1, 'r2', r2, 'N1', N1, 'N2', N2, 'diff_r_values', rdiff, ...
        'fishers_z_diff', zdiff, 'Z_stat', Z, 'p', pval, 'alpha', myalpha, 'sig', sig);

end

%out = correl_compare_dep(y1,y2, 'alpha',myalpha)


function f = gaussfunction(x,p)
% f = gaussfunction(x,p)
% p(1) = mean
% p(2) = std deviation (sqrt(var))
% p(3) = scale coefficient (if p(3)==1 then it is normalised)
normconst = 1/(sqrt(2*pi*p(2)^2));
f = p(3)*normconst*exp(-((x-p(1)).^2)/(2*p(2)^2));


function bernstein_polynomial_test02 ( )

%*****************************************************************************80
%
%% BERNSTEIN_POLYNOMIAL_TEST02 tests BERNSTEIN_POLY_AB.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 July 2011
%
%  Author:
%
%    John Burkardt
%
  n = 10;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'BERNSTEIN_POLYNOMIAL_TEST02\n' );
  fprintf ( 1, '  BERNSTEIN_POLY_AB evaluates Bernstein polynomials over an\n' );
  fprintf ( 1, '  arbitrary interval [A,B].\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Here, we demonstrate that \n' );
  fprintf ( 1, '    BPAB(N,K,A1,B1)(X1) = BPAB(N,K,A2,B2)(X2)\n' );
  fprintf ( 1, '  provided only that\n' );
  fprintf ( 1, '    (X1-A1)/(B1-A1) = (X2-A2)/(B2-A2).\n' );

  x = 0.3;
  a = 0.0;
  b = 1.0;
  bern = bernstein_poly_ab ( n, a, b, x );

  fprintf ( 1, '\n' );
  fprintf ( 1, '     N     K     A        B        X       BPAB(N,K,A,B)(X)\n' );
  fprintf ( 1, '\n' );
  for k = 0 : n
    fprintf ( 1, '  %4d  %4d  %7.4f  %7.4f  %7.4f  %14.6g\n', n, k, a, b, x, bern(k+1) );
  end

  x = 1.3;
  a = 1.0;
  b = 2.0;
  bern = bernstein_poly_ab ( n, a, b, x );

  fprintf ( 1, '\n' );
  fprintf ( 1, '     N     K     A        B        X       BPAB(N,K,A,B)(X)\n' );
  fprintf ( 1, '\n' );
  for k = 0 : n
    fprintf ( 1, '  %4d  %4d  %7.4f  %7.4f  %7.4f  %14.6g\n', n, k, a, b, x, bern(k+1) );
  end

  x = 2.6;
  a = 2.0;
  b = 4.0;
  bern = bernstein_poly_ab ( n, a, b, x );

  fprintf ( 1, '\n' );
  fprintf ( 1, '     N     K     A        B        X       BPAB(N,K,A,B)(X)\n' );
  fprintf ( 1, '\n' );
  for k = 0 : n
    fprintf ( 1, '  %4d  %4d  %7.4f  %7.4f  %7.4f  %14.6g\n', n, k, a, b, x, bern(k+1) );
  end

  return
end


function [theta] = normalEqn(X, y)
%NORMALEQN Computes the closed-form solution to linear regression
%   NORMALEQN(X,y) computes the closed-form solution to linear
%   regression using the normal equations.

theta=pinv(X'*X)*X'*y;

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the code to compute the closed form solution
%               to linear regression and put the result in theta.
%

% ---------------------- Sample Solution ----------------------

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

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

end


function val=fallingFactorial(x,n)
%%FALLINGFACTORIAL Evaluate the falling factorial (x)_n, which for n>=0 is
%                  also known as the binomial polynomial, the lower
%                  factorial, the factorial power, and the falling
%                  factorial power. It is defined
%                  (x)_n=x*(x-1)*(x-2)*...*(x-(n-1)). It can be expressed
%                  as gamma(x+1)/gamma(x-n+1), which makes it continuous.
%                  It is implemented using logarthmic functions to reduce
%                  problems with overflows in intermediate results.
%
%INPUTS: x A scalar or matrix of first values in the product series of
%          x*(x-1)*...*(x-(n-1)). x cannot be negative.
%        n The scalar or matrix n value in the product series of
%          x*(x-1)*...*(x-(n-1)). If x is a matrix, n can be a scalar or a
%          matrix of the same size. If x is a scalar, n can be a scalar or
%          a matrix.
%
%OUTPUTS: val The falling factorial (x)_n for each x and the corresponding
%             n/ for each n and a single x depending on what is a matrix
%             and what is scalar. Note that if n>x, the falling factorial
%             is defined to be 0.
%
%The falling factorial is discussed in [1]. Note that
%fallingFactorial(n,n)=factorial(n);
%
%REFERENCES:
%[1] Weisstein, Eric W. "Falling Factorial." From MathWorld--A Wolfram Web
%    Resource. http://mathworld.wolfram.com/FallingFactorial.html
%
%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

val=exp(gammaln(x+1)-gammaln(max(0,x-n+1)));

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 value = cone_volume_3d ( r, h )

%*****************************************************************************80
%
%% CONE_VOLUME_3D returns the volume of a cone in 3D.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 May 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real R, the radius of the base of the cone.
%
%    Input, real H, the height of the cone.
%
%    Output, real CONE_VOLUME_3D, the volume of the cone.
%
  value = ( pi / 3.0 ) * h * r * r;

  return
end


function J = computeCost(X, y, theta)
%COMPUTECOST Compute cost for linear regression
%   J = COMPUTECOST(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 = (1/(2*m))*sum(((X*theta) - y).^2)

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

end


function [ n_data, n, area ] = hypersphere_01_area_values ( n_data )

%*****************************************************************************80
%
%% HYPERSPHERE_01_AREA_VALUES returns some areas of the unit sphere in ND.
%
%  Discussion:
%
%    The formula for the surface area of the unit sphere in N dimensions is:
%
%      Sphere_Unit_Area ( N ) = 2 * PI^(N/2) / Gamma ( N / 2 )
%
%    Some values of the function include:
%
%       N   Area
%
%       2    2        * PI
%       3  ( 4 /    ) * PI
%       4  ( 2 /   1) * PI^2
%       5  ( 8 /   3) * PI^2
%       6  ( 1 /   1) * PI^3
%       7  (16 /  15) * PI^3
%       8  ( 1 /   3) * PI^4
%       9  (32 / 105) * PI^4
%      10  ( 1 /  12) * PI^5
%
%    For the unit sphere, Area(N) = N * Volume(N)
%
%    In Mathematica, the function can be evaluated by:
%
%      2 * Pi^(n/2) / Gamma[n/2]
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Stephen Wolfram,
%    The Mathematica Book,
%    Fourth Edition,
%    Wolfram Media / Cambridge University Press, 1999.
%
%  Parameters:
%
%    Input/output, integer N_DATA.
%    On input, if N_DATA is 0, the first test data is returned, and
%    N_DATA is set to the index of the test data.  On each subsequent
%    call, N_DATA is incremented and that test data is returned.  When
%    there is no more test data, N_DATA is set to 0.
%
%    Output, integer N, the spatial dimension.
%
%    Output, real AREA, the area of the unit sphere
%    in that dimension.
%
  n_max = 20;

  area_vec = [ ...
     0.2000000000000000E+01, ...
     0.6283185307179586E+01, ...
     0.1256637061435917E+02, ...
     0.1973920880217872E+02, ...
     0.2631894506957162E+02, ...
     0.3100627668029982E+02, ...
     0.3307336179231981E+02, ...
     0.3246969701133415E+02, ...
     0.2968658012464836E+02, ...
     0.2550164039877345E+02, ...
     0.2072514267328890E+02, ...
     0.1602315322625507E+02, ...
     0.1183817381218268E+02, ...
     0.8389703410491089E+01, ...
     0.5721649212349567E+01, ...
     0.3765290085742291E+01, ...
     0.2396678817591364E+01, ...
     0.1478625959000308E+01, ...
     0.8858104195716824, ...
     0.5161378278002812 ];

  n_vec = [ ...
     1, ...
     2, ...
     3, ...
     4, ...
     5, ...
     6, ...
     7, ...
     8, ...
     9, ...
    10, ...
    11, ...
    12, ...
    13, ...
    14, ...
    15, ...
    16, ...
    17, ...
    18, ...
    19, ...
    20 ];

  if ( n_data < 0 )
    n_data = 0;
  end

  n_data = n_data + 1;

  if ( n_max < n_data )
    n_data = 0;
    n = 0;
    area = 0.0;
  else
    n = n_vec(n_data);
    area = area_vec(n_data);
  end

  return
end


%% Radix-4 FFT Test Script
% This file runs three versions of a Radix-4 FFT written in MATLAB:
%
%   radix4FFT1_Float.m computes a radix-4 FFT for floating point data types
%
%   radix4FFT2_FixPt.m computes a fixed point radix-4 FFT (requires Fixed
%   Point Toolbox)
%
%   radix4FFT3_FixPtEML.m is an Embedded MATLAB version of the radix-4 FFT
%   that can be used in Simulink.  You can also generate C code for this
%   code (using Real Time Workshop).  This version can also be compiled
%   into a MEX'd executable that runs significantly faster than the fixed
%   point code.
%
% For a description of the radix-4 FFT algorithm see the following link to
% DSPDesignLine.com:
%
%       http://www.dspdesignline.com/showArticle.jhtml;jsessionid=5DBROAJQ3
%       SIWCQSNDLOSKHSCJUNN2JVN?articleID=204400676&queryText=freescale+fft
%
%% Set up a signal
% The test signal is the sum of 2 sinusoids plus some noise.  The test
% signal is a complex signal with real and imaginary components.
a=256;   % FFT Length
t=0:1/a:(a-1)/a;
s=(sin(2*pi*12*t)+.8*j*sin(2*pi*4.25*t)+.01*randn(size(t)))/2;
s = floor(s*16384)/16384;   %Quantized sum of 2 sines plus noise
subplot(211)
plot(t,real(s))
xlabel('time (sec)');ylabel('Amplitude');title('Test Signal - Real Component')
subplot(212)
plot(t,imag(s))
xlabel('time (sec)');ylabel('Amplitude');title('Test Signal - Imag Component')

%% Test Original Floating Point Code
% Run the Radix-4 algorithm as a floating point implementation.
%
% The function radix4FFT1_Float.m accepts real or complex floating point
% inputs and calculates the FFT.
S = radix4FFT1_Float(s);
S = bitrevorder(S);

% Calculate FFT using MATLAB function
Y = fft(s);

% Compare accuracy of Radix-4 FFT to MATLAB's FFT
errs = double(S) - Y;
Sig = sum(abs(Y).^2)/a;
Noise = sum(abs(errs).^2)/a;
SNR = 10*log10(Sig/Noise);
sprintf('SNR for 2 floating point FFT methods is: %6.2f dB', SNR)

figure
plotPYYf(s,a)

% The radix-4 FFT is nearly identical in accuracy to MATLAB's built in FFT
% computation.
%% Set Fixed Point Parameters
% The Fixed Point Toolbox can convert a test signal to a true fixed point
% data type with specified word lengths and fractional scaling. In this
% case the test signal is a 16 bit integer with 15 fractional bits.
wl = 16;
sfi=fi(s,1,wl,wl-1);    % Data is Q16,15
sfi.RoundMode = 'nearest';        % Fixed Point Rounding, etc.
sfi.OverflowMode = 'wrap';
sfi.ProductMode = 'KeepMSB';
sfi.ProductWordLength = wl*2;
sfi.SumMode = 'KeepMSB';
sfi.SumWordLength = wl*2;
plot(t,real(sfi))
xlabel('time (sec)');ylabel('Amplitude');title('Test Signal - Real Component')

%% Fixed Point Test
% Run the Radix-4 algorithm as a fixed point implementation.
%
% The function radix4FFT2_FixPt.m accepts fixed or floating point inputs
% and calculates the FFT
SFI = radix4FFT2_FixPt(sfi);
SFI = bitrevorder(SFI);

% Calculate FFT using MATLAB function
y = fft(s);

% Compare results
errs = double(SFI) - y;
Sig = sum(abs(y).^2)/a;
Noise = sum(abs(errs).^2)/a;
SNR = 10*log10(Sig/Noise);
sprintf('SNR for fixed vs floating point methods is: %6.2f dB', SNR)

plotPYYf(double(sfi),a)

% As expected, the accuracy of the fixed point FFT is reduced compared to
% the floating point computation.
%% Set Fixed Point Parameters
% The accuracy of the FFT for a shorter word length can be tested by
% changing the input signal to a 14 bit integer with 13 fractional bits.
wl = 14;
sfi=fi(s,1,wl,wl-1);    % Data is Q16,15
sfi.RoundMode = 'nearest';        % Fixed Point Rounding, etc.
sfi.OverflowMode = 'wrap';
sfi.ProductMode = 'KeepMSB';
sfi.ProductWordLength = wl*2;
sfi.SumMode = 'KeepMSB';
sfi.SumWordLength = wl*2;
plot(t,real(sfi))
xlabel('time (sec)');ylabel('Amplitude');title('Test Signal - Real Component')

%% Fixed Point Test
% Run the Radix-4 FFT algorithm with a lower precision data type.
%
SFI = radix4FFT2_FixPt(sfi);
SFI = bitrevorder(SFI);

% Calculate FFT using MATLAB function
y = fft(s);

% Compare results
errs = double(SFI) - y;
Sig = sum(abs(y).^2)/a;
Noise = sum(abs(errs).^2)/a;
SNR = 10*log10(Sig/Noise);
sprintf('SNR for fixed vs floating point methods is: %6.2f dB', SNR)

plotPYYf(double(sfi),a)

% In this case there is an approximate loss of 12 dB of accuracy compared
% to the 16 bit FFT computation

%% Use emlmex to compile code into executable
% The fixed point FFT code can be accelerated by changing the algorithm to
% an EML-compliant algorithm and compiling it with the emlmex command. The
% emlmex command will produce a mex'd version of the MATLAB algorithm.
emlmex -o radix4FFT3_MX -eg {sfi}  radix4FFT3_FixPtEML

%% Show speed of non-compiled code
tic;SFI = radix4FFT3_FixPtEML(sfi);toc
tic;SFI = radix4FFT3_FixPtEML(sfi);toc
tic;SFI = radix4FFT3_FixPtEML(sfi);toc

%% Show speed of compiled code
tic;SFI = radix4FFT3_MX(sfi);toc
tic;SFI = radix4FFT3_MX(sfi);toc
tic;SFI = radix4FFT3_MX(sfi);toc

% The MEX'd version of the FFT code runs over 600 times faster than the
% fixed point MATLAB algorithm.
%
%% Generate C source code for radix-4 FFT
% EML compliant algorithms can be used to generate C source code using Real
% Time Workshop.
rtwcfg = emlcoder.RTWConfig

emlc -v -s rtwcfg -eg {sfi} -o radix4FFT_C radix4FFT3_FixPtEML

% The source code can be inspected in the emcprj directory

%% Use the EML compliant FFT code in Simulink
% The attached Simulink model hiperman_4_2007b_FixPt.mdl uses the radix-4
% FFT algorithm in the OFDM_RX block (requires Simulink and Communications
% Blockset).


%--- help for sym/jacobian ---
%
% JACOBIAN Jacobian matrix.
%    JACOBIAN(f,x) computes the Jacobian of the scalar or vector f
%    with respect to the vector x. The (i,j)-th entry of the result
%    is df(i)/dx(j). Note that when f is scalar, the Jacobian of f
%    is the gradient of f. Also, note that scalar x is allowed,
%    although this is just DIFF(f,x).
%
%    Example:
%        syms x y z u v; jacobian([x*y*z; y; x+z],[x y z])
%        returns  [y*z, x*z, x*y; 0, 1, 0; 1, 0, 1]
%
%        jacobian(u*exp(v),[u;v])
%        returns  [exp(v), u*exp(v)]
%
%    See also SYM/CURL, SYM/DIFF, SYM/DIVERGENCE, SYM/GRADIENT, SYM/HESSIAN,
%    SYM/POTENTIAL, CURL, DIVERGENCE, HESSIAN, LAPLACIAN, VECTORPOTENTIAL,
%    SUBS.
%


function y  = laprnd(m, n, mu, sigma)
%LAPRND generate i.i.d. laplacian random number drawn from laplacian distribution
%   with mean mu and standard deviation sigma.
%   mu      : mean
%   sigma   : standard deviation
%   [m, n]  : the dimension of y.
%   Default mu = 0, sigma = 1.
%   For more information, refer to
%   http://en.wikipedia.org./wiki/Laplace_distribution

%   Author  : Elvis Chen (bee33@sjtu.edu.cn)
%   Date    : 01/19/07

%Check inputs
if nargin < 2
    error('At least two inputs are required');
end

if nargin == 2
    mu = 0; sigma = 1;
end

if nargin == 3
    sigma = 1;
end

% Generate Laplacian noise
u = rand(m, n)-0.5;
b = sigma / sqrt(2);
y = mu - b * sign(u).* log(1- 2* abs(u));


function [ X,h,R ] = generate_test_data(~)
% GENERATE_TEST_DATA creates a sample data set for demonstration of the
% Abel inversion algorithm. Based on the density distribution f
% (polynomial function), the virtual measurement result h is calculated
% via Abel transform:
%
%           h(x) = 2* int_x^R f(r)*r/sqrt(r^2-x^2) dr                  (1)
%
%
%                                         written by C. Killer, Sept. 2013

R=3;                        % radius
X=(0:0.01:R-0.01)';         % spatial coordinates

%polynomial distribution function
f= (17.*(X./R).^4-32.*(X./R).^3+14.*(X./R).^2+1);

h=zeros(length(X),1);    % allocate result vector

for c=1:length(X)
    x=X(c);
    % evaluate Abel-transform equation (1)
    fun = @(r) (17.*(r./R).^4-32.*(r./R).^3+14.*(r./R).^2+1).*r./sqrt(r.^2 - x.^2);
    h(c,1)=2*integral(fun,x,R);
end

figure;
plot(X,f./max(f),'k','Linewidth',1.5);
hold on;
plot(X,h./max(h),'b','Linewidth',1.5);
grid on; box on;
legend('initial density distribution f(r)','measurement result h(r) (Abel-Transform of f(r))','Location','SouthWest')
title('example with polynomial data sample (normalized for better comparison)')


function [g, c, tmp, m]=kMeansCluster(m,k,isRand)
% kMeansCluster - Simple k means clustering algorithm
% Author: Kardi Teknomo, Ph.D.
%
% Purpose: classify the objects in data matrix based on the attributes
% Criteria: minimize Euclidean distance between centroids and object points
% For more explanation of the algorithm, see http://people.revoledu.com/kardi/tutorial/kMean/index.html
% Output: matrix data plus an additional column represent the group of each object
%
% Example: m = [ 1 1; 2 1; 4 3; 5 4]  or in a nice form
%          m = [ 1 1;
%                2 1;
%                4 3;
%                5 4]
%          k = 2
% kMeansCluster(m,k) produces m = [ 1 1 1;
%                                   2 1 1;
%                                   4 3 2;
%                                   5 4 2]
% Input:
%   m      - required, matrix data: objects in rows and attributes in columns
%   k      - optional, number of groups (default = 1)
%   isRand - optional, if using random initialization isRand=1, otherwise input any number (default)
%            it will assign the first k data as initial centroids
%
% Local Variables
%   f      - row number of data that belong to group i
%   c      - centroid coordinate size (1:k, 1:maxCol)
%   g      - current iteration group matrix size (1:maxRow)
%   i      - scalar iterator
%   maxCol - scalar number of rows in the data matrix m = number of attributes
%   maxRow - scalar number of columns in the data matrix m = number of objects
%   temp   - previous iteration group matrix size (1:maxRow)
%   z      - minimum value (not needed)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin<3,        isRand=0;   end
if nargin<2,        k=1;        end
tmp = [];

[maxRow, maxCol]=size(m);
if maxRow<=k,
    y=[m, 1:maxRow];
else

	% initial value of centroid
    if isRand,
        p = randperm(size(m,1));      % random initialization
        for i=1:k
            c(i,:)=m(p(i),:)
    	end
    else
        for i=1:k
           c(i,:)=m(i,:);        % sequential initialization
    	end
    end

	temp=zeros(maxRow,1);   % initialize as zero vector

	while 1,
        d=DistMatrix(m,c);  % calculate objcets-centroid distances
        [z,g]=min(d,[],2);  % find group matrix g
        if g==temp,
            break;          % stop the iteration
        else
            temp=g;         % copy group matrix to temporary variable
        end
        for i=1:k
            f=find(g==i);
            if f            % only compute centroid if f is not empty
                c(i,:)=mean(m(find(g==i),:),1);
            end
        end
	end

	y=[m,g];

end

%The Matlab function kMeansCluster above call function DistMatrix as shown in the code below. It works for multi-dimensional Euclidean distance. Learn about other type of distance here.

    function d=DistMatrix(A,B)
                 %%%%%%%%%%%%%%%%%%%%%%%%%
                 % DISTMATRIX return distance matrix between points in A=[x1 y1 ... w1] and in B=[x2 y2 ... w2]
                 % Copyright (c) 2005 by Kardi Teknomo,  http://people.revoledu.com/kardi/
                 %
                 % Numbers of rows (represent points) in A and B are not necessarily the same.
                 % It can be use for distance-in-a-slice (Spacing) or distance-between-slice (Headway),
                 %
                 % A and B must contain the same number of columns (represent variables of n dimensions),
                 % first column is the X coordinates, second column is the Y coordinates, and so on.
                 % The distance matrix is distance between points in A as rows
                 % and points in B as columns.
                 % example: Spacing= dist(A,A)
                 % Headway = dist(A,B), with hA ~= hB or hA=hB
                 %          A=[1 2 3; 4 5 6; 2 4 6; 1 2 3]; B=[4 5 1; 6 2 0]
                 %          dist(A,B)= [ 4.69   5.83;
                 %                       5.00   7.00;
                 %                       5.48   7.48;
                 %                       4.69   5.83]
                 %
                 %          dist(B,A)= [ 4.69   5.00     5.48    4.69;
                 %                       5.83   7.00     7.48    5.83]
                 %%%%%%%%%%%%%%%%%%%%%%%%%%%
                 [hA,wA]=size(A);
                 [hB,wB]=size(B);
                 if wA ~= wB,  error(' second dimension of A and B must be the same'); end
                 for k=1:wA
                      C{k}= repmat(A(:,k),1,hB);
                      D{k}= repmat(B(:,k),1,hA);
                 end
                 S=zeros(hA,hB);
                 for k=1:wA
                      S=S+(C{k}-D{k}').^2;
                 end
                 d=sqrt(S);


% In this small MATLAB script, we compute the least squares solution to a
% regression problem subject to L1 regularization, which rewards "sparse"
% models that have regression coefficients of zero. See, for instance,
% the work in the "Lasso" by the statistician Robert Tibshirani.
%
% Copyright (C) 2008 Peter Carbonetto. All Rights Reserved.
% This code is published under the Eclipse Public License.
%
% Author: Peter Carbonetto
%         Dept. of Computer Science
%         University of British Columbia
%         September 18, 2008

% Experiment parameters.
lambda = 1;                      % Level of L1 regularization.
n      = 100;                    % Number of training examples.
e      = 1;                      % Std. dev. in noise of outputs.
beta   = [ 0 0 2 -4 0 0 -1 3 ]'; % "True" regression coefficients.

% Set the random number generator seed.
seed = 7;
rand('state',seed);
randn('state',seed);

% CREATE DATA SET.
% Generate the input vectors from the standard normal, and generate the
% binary responses from the regression with some additional noise, and then
% transform the results using the logistic function. The variable "beta" is
% the set of true regression coefficients.
m     = length(beta);      % Number of features.
A     = randn(n,m);        % The n x m matrix of examples.
noise = e * randn(n,1);    % Noise in outputs.
y     = A * beta + noise;  % The binary outputs.

% COMPUTE SOLUTION WITH IPOPT.
% Compute the L1-regularized maximum likelihood estimator.
w = lasso(A,y,lambda);
fprintf('Solution:\n');
disp(w);


% Euclidean projection on a halfspace
% Sec. 8.1.1, Boyd & Vandenberghe "Convex Optimization"
% Joelle Skaf - 10/04/05
%
% The projection of x0 on a halfspace C = {x | a'*x <= b} is given by
%           minimize || x - x0 ||^2
%               s.t.    a'*x <= b
% It is also given by P_C(x0) = x0 + (b - a'*x0)*a/||a||^2 if a'*x0 > b
%                           and x0                         if a'*x0 <=b

% Input data
randn('seed',0);
n  = 10;
a  = randn(n,1);
b  = randn(1);
x0 = randn(n,1);    % a'*x0 <=b
x1 = x0 + a;        % a'*x1 > b

% Analytical solution
fprintf(1,'Computing the analytical solution for the case where a^T*x0 <=b...');
pc_x0 = x0;
fprintf(1,'Done! \n');
fprintf(1,'Computing the analytical solution for the case where a^T*x0 > b...');
pc_x1 = x1 + (b - a'*x1)*a/norm(a)^2;
fprintf(1,'Done! \n');

% Solution via QP
fprintf(1,'Computing the solution of the QP for the case where a^T*x0 <=b...');
cvx_begin quiet
    variable xs0(n)
    minimize ( norm(xs0 - x0).^2 )
    a'*xs0 <= b; %#ok
cvx_end
fprintf(1,'Done! \n');

fprintf(1,'Computing the solution of the QP for the case where a^T*x0 > b...');
cvx_begin quiet
    variable xs1(n)
    minimize ( norm(xs1 - x1).^2 )
    a'*xs1 <= b; %#ok
cvx_end
fprintf(1,'Done! \n');

% Verification
disp('-----------------------------------------------------------------');
disp('Verifying that p_C(x0) and x0_star are equal in the case where a^T*x0 <=b');
disp(['||p_C(x0) - x0_star|| = ' num2str(norm(xs0 - pc_x0))]);
disp('They should be equal to working precision');
disp('Verifying that p_C(x1) and x1_star are equal in the case where a^T*x1 > b');
disp(['||p_C(x1) - x1_star|| = ' num2str(norm(xs1 - pc_x1))]);
disp('They should be equal to working precision');


function [ r, center ] = sphere_dia2imp_3d ( p1, p2 )

%*****************************************************************************80
%
%% SPHERE_DIA2IMP_3D converts a diameter to an implicit sphere in 3D.
%
%  Discussion:
%
%    An implicit sphere in 3D satisfies the equation:
%
%      ( X - CENTER(1) )**2 + ( Y - CENTER(2) )**2 + ( Z - CENTER(3) )**2 = R**2
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 May 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real P1(3), P2(3), are two points which form a diameter
%    of the sphere.
%
%    Output, real R, the computed radius of the sphere.
%
%    Output, real CENTER(3), the computed center of the sphere.
%
  dim_num = 3;

  r = 0.5 * sqrt ( sum ( ( p2(1:dim_num) - p1(1:dim_num) ).^2 ) );

  center(1:dim_num) = 0.5 * ( p1(1:dim_num) + p2(1:dim_num) );

  return
end


function dot = permutation_puzzle ( n )

%*****************************************************************************80
%
%% PERMUTATION_PUZZLE exhibits a peculiar property of permutations.
%
%  Discussion:
%
%    Let P1 and P2 be arbitrary permutations of the integers from 1 to 10.
%
%    Pair corresponding entries of the permutations to create the set of 10
%    points (P1(1),P2(1)) through (P1(10),P2(10)).  Now subtract 5, that is,
%    N/2, from the X and Y coordinates of each point so that their average value
%    is zero.  Then apply a rotation of 45 degrees to each vector.
%
%    Now instead of looking at 10 vectors (X(I),Y(I)), each of length 2, consider
%    the data as two vectors X and Y, each of length 10.  If the instructions have
%    been followed correctly, then X are Y are perpendicular to each other in
%    10-dimensional space.
%
%    In fct, this seems to be true for all the permutations you try.
%    You can even set P1 and P2 equal.
%    You can try other values of N.
%
%    It does not work for most other rotation angles.  For example, a 30 degree
%    rotation will not work.
%
%    Once you've picked P1 and P2, you can take an arbitrary vector Q,
%    set Q1 = Q(P1) and Q2 = Q(P2) and carry out the transformation on Q1 and
%    Q2 instead of on P1 and P2, and it will still work.
%
%    The question is, can you show that all these statements are true, and
%    can you explain why?
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 September 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the vector length.
%
%    Output, real DOT, the dot product of the two vectors.
%
  p1 = randperm ( n );
  p2 = randperm ( n );

  xy = [ p1; p2 ];

  xy = xy - ( n / 2 );

  angle = pi / 4;

  A = [ cos ( angle ), - sin ( angle ); ...
        sin ( angle ),   cos ( angle ) ];

  xy = A * xy;

  dot = xy(1,1:n) * xy(2,1:n)';

  return
end


function d = chord2arclen(d, R)
% CHORD2ARCLEN  Euclidean chord length distances to sphere arc length
% distances.
%
% DARCLEN = chord2arclen(DCHORD, R)
%
%   DCHORD is a scalar, vector, matrix or general array with Euclidean
%   chord length distances. Units are metres.
%
%   R is the radius of the sphere. Units are metres. By default, R=1.
%
%   DARCLEN has the same size as DCHORD, with the corresponding geodesic
%   (great circle) distances. Units are metres.
%
% See also: arclen2chord.

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

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

% defaults
if (nargin < 2 || isempty(R))
    R = 1.0;
end

% convert chord length distances to arc length distances (both in metres)
d = 2*R * asin(d/(2*R));


function x = circle01_to_circle ( alpha, r, c, n, x )

%*****************************************************************************80
%
%% CIRCLE01_TO_CIRCLE maps points from the unit circle to a general one.
%
%  Discussion:
%
%    To map data, defined in the unit circle, to a circle with radius R
%    and center C, and to rotate the original data by an angle of ALPHA first,
%
%      X = R * ( cos(alpha) -sin(alpha) ) * X + CX
%      Y       ( sin(alpha)  cos(alpha) )   Y   CY
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 May 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real ALPHA, the angle, in radians, by which the unit circle
%    data should be rotated.
%
%    Input, real R, the scale factor by which the unit circle data
%    should be stretched.
%
%    Input, real C(2,1), the translation to be applied.
%
%    Input, integer N, the number of points to transform.
%
%    Input/output, real X(2,N), the points to be transformed.
%

%
%  Rotation:
%
%  Don't write "cos ( alpha )" instead of "cos(alpha)" because Matlab's
%  bebuggered automatic array creator thinks blanks separate matrix elements!
%
  rot = [ cos(alpha), -sin(alpha); ...
          sin(alpha),  cos(alpha) ];

  x(1:2,1:n) = c(1:2,1:2) * x(1:2,1:n);
%
%  Dilation:
%
  x(1:2,1:n) = r * x(1:2,1:n);
%
%  Translation:
%
  x(1:2,1:n) = x(1:2,1:n) + repmat ( c(1:2,1), 1, n );

  return
end


function varargout = circleArcToPolyline(arc, N)
%CIRCLEARCTOPOLYLINE Convert a circle arc into a series of points
%
%   P = circleArcToPolyline(ARC, N);
%   convert the circle ARC into a series of N points.
%   ARC is given in the format: [XC YC R THETA1 DTHETA]
%   where XC and YC define the center of the circle, R its radius, THETA1
%   is the start of the arc and DTHETA is the angle extent of the arc. Both
%   angles are given in degrees.
%   N is the number of vertices of the resulting polyline, default is 65.
%
%   The result is a N-by-2 array containing coordinates of the N points.
%
%   [X Y] = circleArcToPolyline(ARC, N);
%   Return the result in two separate arrays with N lines and 1 column.
%
%
%   See also:
%   circles2d, circleToPolygon, drawCircle, drawPolygon
%
%
% ---------
% author : David Legland
% created the 22/05/2006.
% Copyright 2010 INRA - Cepia Software Platform.
%

% HISTORY
% 2011-03-30 use angles in degrees, add default value for N
% 2011-12-09 rename to circleArcToPolyline

% default value for N
if nargin < 2
    N = 65;
end

% vector of positions
t0 = deg2rad(arc(4));
t1 = t0 + deg2rad(arc(5));
t = linspace(t0, t1, N)';

% compute coordinates of vertices
x = arc(1) + arc(3) * cos(t);
y = arc(2) + arc(3) * sin(t);

% format output
if nargout <= 1
    varargout = {[x y]};
else
    varargout = {x, y};
end


function d = dsphere ( p, xc, yc, zc, r )

%*****************************************************************************80
%
%% DSPHERE returns the signed distance of one or more points to a sphere.
%
%  Discussion:
%
%    The corresponding routine in 2D is called DCIRCLE.
%
%  Licensing:
%
%    (C) 2004 Per-Olof Persson.
%    See COPYRIGHT.TXT for details.
%
%  Reference:
%
%    Per-Olof Persson and Gilbert Strang,
%    A Simple Mesh Generator in MATLAB,
%    SIAM Review,
%    Volume 46, Number 2, June 2004, pages 329-345.
%
%  Parameters:
%
%    Input, real P(NP,3), the point coordinates.
%
%    Input, real XC, YC, ZC, the coordinates of the center of the sphere.
%
%    Input, real R, the radius of the sphere.
%
%    Output, real D(NP), the signed distance of each point to the
%    sphere.  The point is inside, on, or outside the sphere depending
%    on whether D is negative, zero, or positive.
%
  d = sqrt ( ( p(:,1) - xc ).^2 ...
           + ( p(:,2) - yc ).^2 ...
           + ( p(:,3) - zc ).^2 ) - r;

  return
end


function li = lagrange_value ( nd, xd, ni, xi )

%*****************************************************************************80
%
%% LAGRANGE_VALUE evaluates the Lagrange basis polynomials.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 November 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer ND, the number of data points.
%
%    Input, real XD(ND,1), the data nodes.
%
%    Input, integer NI, the number of evaluation points.
%
%    Input, real XI(NI,1), the evaluation points.
%
%    Output, real LI(NI,ND), the value, at the I-th point XI, of the
%    Jth basis function.
%
  li = zeros ( ni, nd );

  for i = 1 : ni
    for j = 1 : nd
      li(i,j) = prod ( ( xi(i) - xd(1:j-1)  ) ./ ( xd(j) - xd(1:j-1)  ) ) ...
              * prod ( ( xi(i) - xd(j+1:nd) ) ./ ( xd(j) - xd(j+1:nd) ) );
    end
  end

  return
end


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.

y_pred = X * theta; % X.shape=(m,3) theta.shape=(3,1)
J = 1/(2*m) * sum((y_pred - y).^2);

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

end


function [phi,dphi]=pt2BarycentricTriangCoords(x,v1,v2,v3)
%%PT2BARYCENTRICTIANGCOORDS Convert a point into barycentric points with
%           respect to the vertices of a triangle in 2D. This solves for a
%           specific set of phi such that
%           x=phi(1)*v1+phi(2)*v2+phi(3)*v3
%           and sum(phi)=1. If x is inside the triangle, then phi>=0.
%
%INPUTS: x The 2X1 point whose barycentric coordiantes are desired.
% v1,v2,v3 The three 2X1 vertices of the triangle. It doens't matter if
%          they are in clockwise or counterclockwise order.
%
%OUTPUTS: phi The 3X1 set of barycentric coordinates of x.
%        dPhi A 3X2 set of partial derivatives of phi (rows) with respect
%             to the components of x (columns).
%
%The barycentric coordinate system on a triangle is described in Section 2
%of [1].
%
%EXAMPLE:
%In this example, coordinates inside a triangle are obtained. It is
%verified that the returned derivatives are (within finite precision
%limits) within the bounds of what one gets with finite diferencing. Also,
%the normalization of the weights is verified and the relative error of the
%interpolated values is computed and is also negligible within finite
%precision limits.
% v1=[-2;3];
% v2=[11;0];
% v3=[1;1];
% x=[4;1.5];
% [phi,dphi]=pt2BarycentricTriangCoords(x,v1,v2,v3);
%
% f=@(y)pt2BarycentricTriangCoords(y,v1,v2,v3);
% dPhiNumDiff=numDiff(x,f,3);
%
% RelDerivError=max(max(abs((dPhiNumDiff-dphi)./dPhiNumDiff)))
% normalizationError=sum(phi)-1
%
% interpPoint=phi(1)*v1+phi(2)*v2+phi(3)*v3;
% RelErrVal=max(abs((interpPoint-x)./x))
%
%REFERENCES:
%[1] M. S. Floater, "Generalized barycentric coordinates and applications,"
%    Acta Numerica, vol. 24, pp. 161-214, 1 May 2015.
%
%September 2021 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

Av=triangleArea(v1,v2,v3);

phi=zeros(3,1);
phi(1)=triangleArea(x,v2,v3)/Av;
phi(2)=triangleArea(x,v3,v1)/Av;
phi(3)=triangleArea(x,v1,v2)/Av;

if(nargout>1)
    dphi=zeros(3,2);

    dphi(1,:)=[(v2(2)-v3(2)),(v3(1)-v2(1))]/(2*Av);
    dphi(2,:)=[(v3(2)-v1(2)),(v1(1)-v3(1))]/(2*Av);
    dphi(3,:)=[(v1(2)-v2(2)),(v2(1)-v1(1))]/(2*Av);
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.


clear;
		% Setarea formatului de scriere a randurilor
format compact
        % Definirea functiei de integrat
F=inline('1./x');
		% Incarcarea vectorului x cu elementele cuprinse
		% intre limitele de integrare
x=1:1e-2:2;
		% Evaluarea functiei de integrat in aceste puncte
y=feval(F,x);
		% Incarcarea solutiei exacte
sol_exact=log(2);
        % Calcularea aproximativa a integralei cu
		% ajutorul metodei lui Simpson
I_S=quad(F,1,2);
		% Calcularea erorii relative la aceasta metoda
eroare_S=abs(I_S-sol_exact)/sol_exact*100;
		% Afisarea rezultatelor
disp(['Solutia exacta a integralei= ',num2str(sol_exact)]);
disp(' ');
disp('Solutia aproximativa a integralei');
disp(['prin metoda lui Simpson=', num2str(I_S)]);
disp(['Eroarea relativa= ',num2str(eroare_S),' %']);
		% Calcularea aproximativa a integralei cu
		% ajutorul metodei lui Lobatto
I_L=quadl(F,1,2);
		% Calcularea erorii relative la aceasta metoda
eroare_L=abs(I_L-sol_exact)/sol_exact*100;
		% Afisarea rezultatelor
disp(' ');
disp('Solutia aproximativa a integralei ');
disp(['prin metoda lui Lobatto=', num2str(I_L)]);
disp(['Eroarea relativa= ',num2str(eroare_L),' %']);
		% Calcularea aproximativa a integralei cu
		% ajutorul metodei trapezelor
I_t=trapz(x,y);
		% Calcularea erorii relative la aceasta metoda
eroare_t=abs(I_t-sol_exact)/sol_exact*100;
		% Afisarea rezultatelor
disp(' ');
disp('Solutia aproximativa a integralei ');
disp(['prin metoda trapezelor=', num2str(I_t)]);
disp(['Eroarea relativa= ',num2str(eroare_t),' %']);
		% Generarea unui vector cu erorile obtinute
		% la diferite metode
eror=[eroare_S, eroare_L,eroare_t];
		% Determinarea erorii minime
		%  - val_eroare contine valoarea minima
		%    din vectorul eror
		%  - nr_eroare contine numarul elementului
		%    minim din vectorul eror
[val_eroare, nr_eroare]=min(eror);
		% Afisarea erorii minime si a metodei cu ajutorul
		% careia s-a obtinut
disp(' ');
disp(['Eroarea cea mai mica de ',num2str(val_eroare)]);
switch nr_eroare
    case 1
	    disp('s-a obtinut cu ajutorul metodei Simpson');
    case 2
	    disp('s-a obtinut cu ajutorul metodei Lobatto');
    case 3
	    disp('s-a obtinut cu ajutorul metodei trapezelor');
end;


function [ p1, p2, p3 ] = plane_imp2exp_3d ( a, b, c, d )

%*****************************************************************************80
%
%% PLANE_IMP2EXP_3D converts an implicit plane to explicit form in 3D.
%
%  Discussion:
%
%    The implicit form of a plane in 3D is
%
%      A * X + B * Y + C * Z + D = 0.
%
%    The explicit form of a plane in 3D is
%
%      the plane through P1, P2 and P3.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 December 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real A, B, C, D, the implicit plane parameters.
%
%    Output, real P1(3,1), P2(3,1), P3(3,1), three points on the plane.
%
  [ pp, normal ] = plane_imp2normal_3d ( a, b, c, d );

  [ p1, p2, p3 ] = plane_normal2exp_3d ( pp, normal );

  return
end


function v = cheby_t_poly ( m, n, x )

%*****************************************************************************80
%
%% CHEBY_T_POLY evaluates Chebyshev polynomials T(n,x).
%
%  Discussion:
%
%    Chebyshev polynomials are useful as a basis for representing the
%    approximation of functions since they are well conditioned, in the sense
%    that in the interval [-1,1] they each have maximum absolute value 1.
%    Hence an error in the value of a coefficient of the approximation, of
%    size epsilon, is exactly reflected in an error of size epsilon between
%    the computed approximation and the theoretical approximation.
%
%    Typical usage is as follows, where we assume for the moment
%    that the interval of approximation is [-1,1].  The value
%    of N is chosen, the highest polynomial to be used in the
%    approximation.  Then the function to be approximated is
%    evaluated at the N+1 points XJ which are the zeroes of the N+1-th
%    Chebyshev polynomial.  Let these values be denoted by F(XJ).
%
%    The coefficients of the approximation are now defined by
%
%      C(I) = 2/(N+1) * sum ( 1 <= J <= N+1 ) F(XJ) T(I,XJ)
%
%    except that C(0) is given a value which is half that assigned
%    to it by the above formula,
%
%    and the representation is
%
%    F(X) approximated by sum ( 0 <= J <= N ) C(J) T(J,X)
%
%    Now note that, again because of the fact that the Chebyshev polynomials
%    have maximum absolute value 1, if the higher order terms of the
%    coefficients C are small, then we have the option of truncating
%    the approximation by dropping these terms, and we will have an
%    exact value for maximum perturbation to the approximation that
%    this will cause.
%
%    It should be noted that typically the error in approximation
%    is dominated by the first neglected basis function (some multiple of
%    T(N+1,X) in the example above).  If this term were the exact error,
%    then we would have found the minimax polynomial, the approximating
%    polynomial of smallest maximum deviation from the original function.
%    The minimax polynomial is hard to compute, and another important
%    feature of the Chebyshev approximation is that it tends to behave
%    like the minimax polynomial while being easy to compute.
%
%    To evaluate a sum like
%
%      sum ( 0 <= J <= N ) C(J) T(J,X),
%
%    Clenshaw's recurrence formula is recommended instead of computing the
%    polynomial values, forming the products and summing.
%
%    Assuming that the coefficients C(J) have been computed
%    for J = 0 to N, then the coefficients of the representation of the
%    indefinite integral of the function may be computed by
%
%      B(I) = ( C(I-1) - C(I+1))/2*(I-1) for I=1 to N+1,
%
%    with
%
%      C(N+1)=0
%      B(0) arbitrary.
%
%    Also, the coefficients of the representation of the derivative of the
%    function may be computed by:
%
%      D(I) = D(I+2)+2*I*C(I) for I=N-1, N-2, ..., 0,
%
%    with
%
%      D(N+1) = D(N)=0.
%
%    Some of the above may have to adjusted because of the irregularity of C(0).
%
%  Differential equation:
%
%    (1-X*X) Y'' - X Y' + N N Y = 0
%
%  Formula:
%
%    T(N,X) = COS(N*ARCCOS(X))
%
%  First terms:
%
%    T(0,X) =  1
%    T(1,X) =  1 X
%    T(2,X) =  2 X^2 -   1
%    T(3,X) =  4 X^3 -   3 X
%    T(4,X) =  8 X^4 -   8 X^2 +  1
%    T(5,X) = 16 X^5 -  20 X^3 +  5 X
%    T(6,X) = 32 X^6 -  48 X^4 + 18 X^2 - 1
%    T(7,X) = 64 X^7 - 112 X^5 + 56 X^3 - 7 X
%
%  Inequality:
%
%    abs ( T(N,X) ) <= 1 for -1 <= X <= 1
%
%  Orthogonality:
%
%    For integration over [-1,1] with weight
%
%      W(X) = 1 / sqrt(1-X*X),
%
%    if we write the inner product of T(I,X) and T(J,X) as
%
%      < T(I,X), T(J,X) > = integral ( -1 <= X <= 1 ) W(X) T(I,X) T(J,X) dX
%
%    then the result is:
%
%      0 if I /= J
%      PI/2 if I == J /= 0
%      PI if I == J == 0
%
%    A discrete orthogonality relation is also satisfied at each of
%    the N zeroes of T(N,X):  sum ( 1 <= K <= N ) T(I,X) * T(J,X)
%                              = 0 if I /= J
%                              = N/2 if I == J /= 0
%                              = N if I == J == 0
%
%  Recursion:
%
%    T(0,X) = 1,
%    T(1,X) = X,
%    T(N,X) = 2 * X * T(N-1,X) - T(N-2,X)
%
%    T'(N,X) = N * ( -X * T(N,X) + T(N-1,X) ) / ( 1 - X^2 )
%
%  Special values:
%
%    T(N,1) = 1
%    T(N,-1) = (-1)^N
%    T(2N,0) = (-1)^N
%    T(2N+1,0) = 0
%    T(N,X) = (-1)^N * T(N,-X)
%
%  Zeroes:
%
%    M-th zero of T(N,X) is cos((2*M-1)*PI/(2*N)), M = 1 to N
%
%  Extrema:
%
%    M-th extremum of T(N,X) is cos(PI*M/N), M = 0 to N
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 March 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the number of evaluation points.
%
%    Input, integer N, the highest polynomial to compute.
%
%    Input, real X(M,1), the evaluation points.
%
%    Output, real V(M,N+1), the values of the Chebyshev polynomials
%    0 through N at X(1:M).
%
  if ( n < 0 )
    c = [];
    return
  end

  v = zeros ( m, n + 1 );

  v(1:m,1) = 1.0;

  if ( n < 1 )
    return
  end

  x = x(:);

  v(1:m,2) = x(1:m,1);

  for i = 2 : n
    v(1:m,i+1) = 2.0 * x(1:m,1) .* v(1:m,i) - v(1:m,i-1);
  end

  return
end


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

% FS of periodic signals

%x(t)= 1, 0<t<1   , T=2
%     -1, 1<t<2

%x(t), 0<t<5T
t1=0:.01:1;
t2=1.01:.01:2;
x1=ones(size(t1));
x2=-ones(size(t2));
x=[x1 x2];
xp=repmat(x,1,5);
t=linspace(0,10,length(xp));
plot(t,xp)

%x(t), 0<t<T
figure
syms t
x=heaviside(t)-2*heaviside(t-1);
ezplot(x,[0 2]);

%exponential FS
figure
k=-2:2;
t0 =0;
T=2;
w=2*pi/T;
a=(1/T)*int(x*exp(-j*k*w*t),t,t0,t0+T)
xx=sum(a.*exp(j*k*w*t))
ezplot(xx,[0 10])
title('approximation with 5 terms')
figure
k=-5:5;
a=(1/T)*int(x*exp(-j*k*w*t),t,t0,t0+T);
xx=sum(a.*exp(j*k*w*t));
ezplot(xx,[0 10])
title('approximation with 11 terms')
figure
k=-10:10;
a=(1/T)*int(x*exp(-j*k*w*t),t,t0,t0+T);
xx=sum(a.*exp(j*k*w*t));
ezplot(xx,[0 10])
title('approximation with 21 terms')
figure
k=-30:30;
a=(1/T)*int(x*exp(-j*k*w*t),t,t0,t0+T);
xx=sum(a.*exp(j*k*w*t));
ezplot(xx,[0 10])
title('approximation with 61 terms')

%trigonometric FS
figure
a0=(1/T)*int(x,t0,t0+T);
n=1:2;
b=(2/T)*int(x*cos(n*w*t),t,t0,t0+T);
c=(2/T)*int(x*sin(n*w*t),t,t0,t0+T);
xx=a0+sum(b.*cos(n*w*t))+sum(c.*sin(n*w*t));
ezplot(xx,[0 10])
title('approximation with 3 terms')
figure
n=1:5;
b=(2/T)*int(x*cos(n*w*t),t,t0,t0+T);
c=(2/T)*int(x*sin(n*w*t),t,t0,t0+T);
xx=a0+sum(b.*cos(n*w*t))+sum(c.*sin(n*w*t));
ezplot(xx,[0 10])
title(' approximation with 6 terms')
figure
n=1:40;
b=(2/T)*int(x*cos(n*w*t),t,t0,t0+T);
c=(2/T)*int(x*sin(n*w*t),t,t0,t0+T);
xx=a0+sum(b.*cos(n*w*t))+sum(c.*sin(n*w*t));
ezplot(xx,[0 10])
title('approximation with 41 terms')

%FS in cosine with phase form
figure
for n=1:2
A(n)=sqrt(b(n)^2+c(n)^2);
thita(n)=atan2(-eval(c(n)),eval(b(n)));
end
k=1:2;
xx=a0+sum(A.*cos(k*w*t+thita))
ezplot(xx,[0 10])
title('approximation with 3 terms')
figure
for n=1:5
A(n)=sqrt(b(n)^2+c(n)^2);
thita(n)=atan2(-eval(c(n)),eval(b(n)));
end
k=1:5;
xx=a0+sum(A.*cos(k*w*t+thita));
ezplot(xx,[0 10])
title('approximation with 6 terms')
figure
for n=1:40
A(n)=sqrt(b(n)^2+c(n)^2);
thita(n)=atan2(-eval(c(n)),eval(b(n)));
end
k=1:40;
xx=a0+sum(A.*cos(k*w*t+thita));
ezplot(xx,[0 10])
title('approximation with 41 terms')


%% Spherical Harmonics
%
%%
% The spherical harmonics are special functions on the 2-sphere $\mathbb S^2$.
% In terms of polar coordinates
% ${\bf \xi} = (\sin \theta \cos \rho, \sin \theta \sin \rho, \cos \theta)$ the
% spherical harmonic of degree $m$ and order $l$ is defined by
%
% $$ Y_m^l({\bf \xi}) = \sqrt{\frac{2m+1}{4\pi}}P_m^{|l|}(\cos\rho)\mathrm e^{\mathrm i l\theta} $$
%
% where $P_m^{|l|}$, $m \in {\bf N_0}$, and $ l = -m, \ldots m$ denote the
% associated Legendre-Polynomials.
%
% We get the function values of the spherical harmonics of degree 1 in a
% point v by the command |sphericalY|, i.e.

v = vector3d.X
sphericalY(1,v)

%%
% The spherical harmonics form an orthonormal basis in $L_2(\mathbb S^2)$.
% Hence we describe functions on the 2-sphere by there harmonic
% representation using the class <S2FunHarmonicRepresentation.html
% S2FunHarmonic>.
%
% With that we define the spherical harmonic $Y_1^1$ by

Y = S2FunHarmonic([0;0;0;1])
Y.eval(v)

%%
% Various normalizations for the sperical harmonics are common in the
% literature.
%
% Here we define the $L_2$-norm by
%
% $$ \| f \|_2 = \left(\int_{\mathrm{sphere}} |f(\xi)|^2 \,\mathrm d\xi\right)^{1/2} $$
%
% such that $ \| 1 \|_2^2 = 1$. Take a look on the section
% <S2FunOperations.html#5 Integration of S2Fun's>.
%
% Using that definition the spherical harmonics in MTEX fulfill
%
% $$\| Y_m^l \|_2 = 1$$ for all $m,l$.
%

norm(Y)

%%
% To concluse this section we plot the first ten spherical harmonics

surf(S2FunHarmonic(eye(10)))


function value = factorial_log ( n )

%*****************************************************************************80
%
%% FACTORIAL_LOG returns the logarithm of N!.
%
%  Discussion:
%
%    N! = Product ( 1 <= I <= N ) I
%
%    N! = Gamma(N+1).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the argument of the function.
%    0 <= N.
%
%    Output, real FACTORIAL_LOG, the logarithm of N!.
%
  if ( n < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'FACTORIAL_LOG - Fatal error!\n' );
    fprintf ( 1, '  N < 0.\n' );
    error ( 'FACTORIAL_LOG - Fatal error!' );
  end

  value = 0.0;

  for i = 2 : n
    value = value + log ( i );
  end

  return
end


function [ ra, dec ] = xyz_to_radec ( p )

%*****************************************************************************80
%
%% XYZ_TO_RADEC converts (X,Y,Z) to right ascension/declination coordinates.
%
%  Discussion:
%
%    Given an XYZ point, compute its distance R from the origin, and
%    regard it as lying on a sphere of radius R, whose axis is the Z
%    axis.
%
%    The right ascension of the point is the "longitude", measured in hours,
%    between 0 and 24, with the X axis having right ascension 0, and the
%    Y axis having right ascension 6.
%
%    Declination measures the angle from the equator towards the north pole,
%    and ranges from -90 (South Pole) to 90 (North Pole).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 December 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real P(3,1), the coordinates of a point in 3D.
%
%    Output, real RA, DEC, the corresponding right ascension
%    and declination.
%
  p_norm = sqrt ( sum ( p(1:3,1).^2 )  );

  phi = r8_asin ( p(3,1) / p_norm );

  if ( cos ( phi ) == 0.0 )
    theta = 0.0;
  else
    theta = r8_atan ( p(2,1), p(1,1) );
  end

  dec = radians_to_degrees ( phi );
  ra = radians_to_degrees ( theta ) / 15.0;

  return
end


function rphiList=Cart2Hypersphere(x)
%%HYPERSPHERE2CART Given a point in n-dimensional Cartesian coordinates
%                  convert the point to n-dimensional spherical coordinates
%                  (hyperspherical coordinates.
%
%INPUTS: x An nXN matrix of the values converted into n-dimensional
%          Cartesian coordinates. n>=2.
%
%OUTPUTS: rPhiList The nXN values convert from Cartesian coordinates to
%                 hyperspherical coordinates. Each value is a range r
%                 (0<=r<Inf) followed by (n-1) angular values. The first
%                 (n-2) values are bound from 0 to pi and the final one can
%                 span the entire circle (-pi to pi).
%
%Hyperspherical coordinates are derived in [1]. The definition here is
%nearly identical, except the final two coordinates are switched (the final
%term is all sines). Hyperspherical coordinates arise in tracking, for
%example, when generating false measurements in gates in simulations, such
%as in [2]. Note that in [2], yet another definition of the system is used.
%
%The definition here is
% x(1)=cos(phi(1));
% x(2)=sin(phi(1))*cos(phi(2));
% x(3)=sin(phi(1))*sin(phi(2))*cos(phi(3));
% ...
% x(n-1)=sin(phi(1))*...*sin(phi(n-2))*cos(phi(n-1));
% x(n)=sin(phi(1))*...*sin(phi(n-2))*sin(phi(n-1));
%
%The definition of the angles differs in 3D from those use in the
%Cart2Sphere function.
%
%REFERENCES:
%[1] L. E. Blumenson, "A derivation of n-dimensional spherical
%    coordinates," The American Mathematical Monthly, no. 1, pp. 63-66,
%    Jan. 1960.
%[2] H. Sun and M. Farooq, "Note on the generation of random points
%    uniformly distributed in hyper-ellipsoids," in Proceedings of the
%    Fifth International Conference on Information Fusion, Annapolis, MD,
%    8-11 Jul. 2002, pp. 489-496.
%
%October 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

n=length(x);

phiList=zeros(n-1,1);
r=norm(x);

for curDim=1:(n-1)
    normVal=norm(x(curDim:n));

    if(normVal==0)
        if(x(curDim)>=0)
            phiList(curDim)=0;
        else
            phiList(curDim)=pi;
        end
    else
        phiList(curDim)=acos(x(curDim)/normVal);
    end
end

if(x(n)<0)
    phiList(n-1)=2*pi-phiList(n-1);
end
phiList(n-1)=wrapRange(phiList(n-1),-pi,pi);

rphiList=[r;phiList];
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 = power_mod ( a, n, m )

%*****************************************************************************80
%
%% POWER_MOD computes mod ( A^N, M ).
%
%  Discussion:
%
%    Some programming tricks are used to speed up the computation, and to
%    allow computations in which A**N is much too large to store in a
%    real word.
%
%    First, for efficiency, the power A**N is computed by determining
%    the binary expansion of N, then computing A, A**2, A**4, and so on
%    by repeated squaring, and multiplying only those factors that
%    contribute to A**N.
%
%    Secondly, the intermediate products are immediately "mod'ed", which
%    keeps them small.
%
%    For instance, to compute mod ( A^13, 11 ), we essentially compute
%
%       13 = 1 + 4 + 8
%
%       A^13 = A * A^4 * A^8
%
%       mod ( A^13, 11 ) = mod ( A, 11 ) * mod ( A^4, 11 ) * mod ( A^8, 11 ).
%
%    Fermat's little theorem says that if P is prime, and A is not divisible
%    by P, then ( A^(P-1) - 1 ) is divisible by P.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 November 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer A, the base of the expression to be tested.
%    A should be nonnegative.
%
%    Input, integer N, the power to which the base is raised.
%    N should be nonnegative.
%
%    Input, integer M, the divisor against which the expression is tested.
%    M should be positive.
%
%    Output, integer X, the remainder when A^N is divided by M.
%
  if ( a < 0 )
    x = -1;
    return
  end

  if ( floor ( a ) ~= a )
    x = -1;
    return
  end

  if ( n < 0 )
    x = -1;
    return
  end

  if ( floor ( n ) ~= n )
    x = -1;
    return
  end

  if ( m <= 0 )
    x = -1;
    return
  end

  if ( floor ( m ) ~= m )
    x = -1;
    return
  end
%
%  A contains the successive squares of A.
%
  x = 1;

  while ( 0 < n )

    d = mod ( n, 2 );

    if ( d == 1 )
      x = mod ( x * a, m );
    end

    a = mod ( a * a, m );
    n = floor ( ( n - d ) / 2 );

  end
%
%  Ensure that 0 <= X.
%
  while ( x < 0 )
    x = x + m;
  end

  return
end


function out = OrthNorm(n)
% =======================================================================
% Compute a [n x n] random orthonormal matrix
% =======================================================================
% out = OrthNorm(n)
% -----------------------------------------------------------------------
% INPUT
%   - n: size of the matrix
% -----------------------------------------------------------------------
% OUTPUT
%   - out: [n x n] random orthonormal matrix
% =======================================================================
% Ambrogio Cesa Bianchi, March 2015
% ambrogio.cesabianchi@gmail.com

% [n x n]  matrix of N(0,1) random variables
X = randn(n,n);

% QR decomposition of X
[Q, ~] = qr(X);

% Check precision
if sum(sum(Q*Q'))> n + 1.0e-5
    error('Q*transpose(Q) is not equal to identity')
end

% Random orthonormal matrix such that Q*Q'=I
out = Q;


function cdf = logistic_cdf ( x, a, b )

%*****************************************************************************80
%
%% LOGISTIC_CDF evaluates the Logistic CDF.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    13 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X, the argument of the CDF.
%
%    Input, real A, B, the parameters of the PDF.
%    0.0 < B.
%
%    Output, real CDF, the value of the CDF.
%
  cdf = 1.0 / ( 1.0 + exp ( ( a - x ) / b ) );

  return
end


function Pr = gbm_upcrossing_prob(X0, K, T, mu, sigma)
%gbm_upcrossing_prob - Compute probability of an upcrossing of a geometric Brownian motion.
%
%	Pr = gbm_upcrossing_prob(X0, K, T, mu, sigma);
%
% Inputs:
%	X0 - Almost surely known initial value of geometric Brownian motion process [scalar].
%	K - Level for upcrossing of geometric Brownian motion during a specified period [scalar].
%	T - Duration of the period of observation in a specified unit of time [scalar].
%	mu - Drift of geometric Brownian motion in rate of change per specified unit of time [scalar].
%	sigma - Diffusion of geometric Brownian motion in rate of change per specified unit of time
%		[scalar].
%
% Outputs:
%	Pr - Probability of an upcrossing of a geometric Brownian motion during the period T in the
%		specified units of time [scalar].
%
% Comments:
%	1) This function computes the probability that a geometric Brownian motion crosses at or above a
%		specified level at any time during a specified fixed period of time.
%	2) The term "unit of time" indicates that all times and rates must be in the same units of time.

% Copyright (C) 2012 The MathWorks, Inc.

if K <= X0
	Pr = 1;
else
	d0 = log(X0/K);
	d1 = (d0 + (mu - 0.5*sigma^2)*T)/(sigma*sqrt(2*T));
	d2 = (d0 - (mu - 0.5*sigma^2)*T)/(sigma*sqrt(2*T));
	d3 = -0*(mu - 0.5*sigma^2)/(0.5*sigma^2);

	Pr = 0.5*(1 + erf(d1)) + 0.5*exp(-d3)*(1 + erf(d2));
end


function val=multinomial(repList)
%%MULTINOMIAL Compute a multinomial coefficient. The multinomial
%           coefficient is the number of permutation of a multiset. A
%           multiset is a set with repeated elements. Multinomial
%           coefficients are usually written like binomial coefficients but
%           with multiple terms below.
%
%INPUTS: repList A numUniqueX1 list of how many times each unique item in
%                the multiset is repeated. All elements >=1 and
%                n=sum(repList), where n is the total number of elements in
%                the multiset.
%
%OUTPUTS: val The value of the multinomial coefficient.
%
%The multinomial coefficient is factorial(n)/prod(factorial(repList)).
%However, that formulation is subject to overflow issues. Thus, it is
%implemented here as a product of boinomial coefficients.
%
%September 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

    numUniqueEls=length(repList);
    val=1;
    cumSum=0;
    for curEl=1:numUniqueEls
       cumSum=cumSum+repList(curEl);
       val=val*binomial(cumSum,repList(curEl));
    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 fx = p21_fun ( n, x )

%*****************************************************************************80
%
%% P21_FUN evaluates the integrand for problem 21.
%
%  Interval:
%
%    0 <= X <= 1
%
%  Integrand:
%
%       ( sech (   10.0 * ( x - 0.2 ) ) )^2
%     + ( sech (  100.0 * ( x - 0.4 ) ) )^4
%     + ( sech ( 1000.0 * ( x - 0.6 ) ) )^6
%
%  Exact Integral:
%
%    ( 1 + tanh ( 8 ) * tanh ( 2 ) ) / 10.0 + 2 / 150 + 2 / 1875
%
%  Approximate Integral (20 digits):
%
%    0.21080273631018169851...
%
%  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 = ...
      ( sech (   10.0 * ( x - 0.2 ) ) ).^2 ...
    + ( sech (  100.0 * ( x - 0.4 ) ) ).^4 ...
    + ( sech ( 1000.0 * ( x - 0.6 ) ) ).^6;

  return
end


function num_dist = dist_enum ( k, m )

%*****************************************************************************80
%
%% DIST_ENUM returns the number of distributions of indistinguishable objects.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 January 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer K, the number of distinguishable "slots".
%
%    Input, integer M, the number of indistinguishable objects.
%
%    Output, integer NUM_DIST, the number of distributions of M
%    indistinguishable objects about K distinguishable slots.
%
  cnk = combin ( m + k - 1, m );

  num_dist = round ( cnk );

  return
end


function [w,x]=fclencurt(N1,a,b)
% Fast Clenshaw Curtis Quadrature

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% fclencurt.m - Fast Clenshaw Curtis Quadrature
%
% Compute the N nodes and weights for Clenshaw-Curtis
% Quadrature on the interval [a,b]. Unlike Gauss
% quadratures, Clenshaw-Curtis is only exact for
% polynomials up to order N, however, using the FFT
% algorithm, the weights and nodes are computed in linear
% time. This script will calculate for N=2^20+1 (1048577
% points) in about 5 seconds on a normal laptop computer.
%
% Written by: Greg von Winckel - 02/12/2005
% Contact: gregvw(at)chtm(dot)unm(dot)edu
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

N=N1-1; bma=b-a;
c=zeros(N1,2);
c(1:2:N1,1)=(2./[1 1-(2:2:N).^2 ])'; c(2,2)=1;
f=real(ifft([c(1:N1,:);c(N:-1:2,:)]));
w=bma*([f(1,1); 2*f(2:N,1); f(N1,1)])/2;
x=0.5*((b+a)+N*bma*f(1:N1,2));


function y = r8vec_sqstb ( n, x )

%*****************************************************************************80
%
%% R8VEC_SQSTB computes a "slow" quarter sine transform backward of an R8VEC.
%
%  Discussion:
%
%    This routine is provided for illustration and testing.  It is inefficient
%    relative to optimized routines that use fast Fourier techniques.
%
%    For 0 <= I <= N-1,
%
%      Y(I) = -2 Sum ( 1 <= J <= N-1 ) X(J) * sin ( PI * J * (I+1/2) / N )
%             - X(N) * cos ( pi * I )
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    William Briggs, Van Emden Henson,
%    The Discrete Fourier Transform,
%    SIAM, 1995,
%    QA403.5 B75
%
%  Parameters:
%
%    Input, integer N, the number of data values.
%
%    Input, real X(N), the data sequence.
%
%    Output, real Y(N), the transformed data.
%
  y(1:n) = 0.0;

  for i = 1 : n

    for j = 1 : n - 1
      theta = 0.5 * pi * j * ( 2 * i - 1 ) / n;
      y(i) = y(i) - 2.0 * x(j) * sin ( theta  );
    end

    theta = pi * ( i - 1 );
    y(i) = y(i) - x(n) * cos ( theta );

  end

  return
end


function f = p30_fun ( n, x )

%*****************************************************************************80
%
%% P30_FUN evaluates the integrand for problem 30.
%
%  Interval:
%
%    2 <= x <= 7
%
%  Integrand:
%
%          cos (       x )
%    + 5 * cos ( 1.6 * x )
%    - 2 * cos ( 2.0 * x )
%    + 5 * cos ( 4.5 * x )
%    + 7 * cos ( 9.0 * x )
%
%  Antiderivative:
%
%          sin (       x )
%    + 5 * sin ( 1.6 * x ) / 1.6
%    - 2 * sin ( 2.0 * x ) / 2.0
%    + 5 * sin ( 4.5 * x ) / 4.5
%    + 7 * sin ( 9.0 * x ) / 9.0
%
%  Exact Integral:
%
%    -4.5275696251606720278
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    05 November 2009
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Dianne OLeary,
%    Scientific Computing with Case Studies,
%    SIAM, 2008,
%    ISBN13: 978-0-898716-66-5,
%     LC: QA401.O44.
%
%  Parameters:
%
%    Input, integer N, the number of evaluation points.
%
%    Input, real X(N), the evaluation points.
%
%    Output, real FX(N), the integrand values.
%
  f =     cos (       x ) ...
    + 5 * cos ( 1.6 * x ) ...
    - 2 * cos ( 2.0 * x ) ...
    + 5 * cos ( 4.5 * x ) ...
    + 7 * cos ( 9.0 * x );

  return
end


function y=log10p1(x)
%%LOG10P1 Evaluate the function log10(x+1) without a loss of precision for
%         values of x near 0.
%
%INPUTS: x A vector of matrix of real values at which the function should
%          be evaluated.
%
%OUTPUTS: y The value(s) of the function log10(x+1) at the point(s) in x.
%
%For values of x having magnitude over 1e-2 and for complex values, the
%function is evaluated as written. For smaller values, a Taylor series
%expansion is used to avoid the singularity near the origin.
%
%EXAMPLE:
%Compare
% log10(1e-16+1)
% log10p1(1e-16)
%For the first one, one will get 0, for the second,
%4.342944819032518e-17. Compare this to a value computed using
%higher-precision arithmetic of 4.3429448190325180593640482375402*10^-17
%and it is clear that this function is more accurate than explicitly
%evaluating the expression.
%
%November 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

%Allocate space
y=zeros(size(x));

%For large enough values, use the standard function.
sel=abs(x)>1e-2|~isreal(x);
x1=x(sel);
y(sel)=log10(x1+1);

%For smaller magnitude values, use an ninth-order Taylor series expansion.
%The relative error at 10^-2 is on the order of 1e-20, which is less than
%the precision of a double floating point number at that value. The series
%is given in Horner form.
log10Val=log(10);
x1=x(~sel);
y(~sel)=x1.*(x1.*(x1.*(x1.*(x1.*(x1.*(x1.*(x1.*(-(1/(8*log10Val))+x/(9*log10Val))+1/(7*log10Val))-1/(6*log10Val))+1/(5*log10Val))-1/(4*log10Val))+1/(3*log10Val))-1/(2*log10Val))+1/log10Val);
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 [weights,location] = GaussQuad1d(ngp)
% Guass weights and abscissas.
% Taken from http://en.wikipedia.org/wiki/Gaussian_quadrature

% Data Table
switch ngp
    case{1} % ngp =1
        location = 0;
        weights = 2;
    case{2} % ngp =2
        location = [-sqrt(3)/3,sqrt(3)/3]';
        weights = [1,1]';
    case{3} % ngp =3
        location = [-sqrt(3/5),0,sqrt(3/5)]';
        weights = [5/9,8/9,5/9]';
    case{4} % ngp =4
        x1 = sqrt((3-2*sqrt(6/5))/7);
        x2 = sqrt((3+2*sqrt(6/5))/7);
        location = [-x1,-x2,x2,x1]';
        w1 = (18+sqrt(30))/36;
        w2 = (18-sqrt(30))/36;
        weights = [w1,w2,w2,w1]';
    case{5} % ngp =5
        x1 = (1/3)*sqrt(5-2*sqrt(10/7));
        x2 = (1/3)*sqrt(5+2*sqrt(10/7));
        x3 = 0;
        location = [-x1,-x2,x3,x2,x1]';
        w1 = (322 + 13*sqrt(70))/900;
        w2 = (322 - 13*sqrt(70))/900;
        w3 = 128/225;
        weights = [w1,w2,w3,w2,w1]';
    otherwise
        error('ngp max value = 5')
end


function M_rice=imrician(M,s)

% function M_rice=imrician(M,s)
% ------------------------------------------------------------------------
% IMCRICIAN Random samples from the Rice/Rician probability distribution.
%
% R ~ Rice(v, s) if R = sqrt(X^2 + Y^2), where X ~ N(v*cos(a), s^2) and
% Y ~ N(v*sin(a), s^2) are independent normal distributions (any real a).
%
% Reference: http://en.wikipedia.org/wiki/Rice_distribution
%
% Kevin Mattheus Moerman
% kevinmoerman@hotmail.com
% 15/04/2009
% ------------------------------------------------------------------------

X_GAUSS=s.*randn(size(M))+M;
Y_GAUSS=s.*randn(size(M));
M_rice = hypot(X_GAUSS,Y_GAUSS);

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


function xval = r8vec_even_select ( xlo, xhi, n, ival )

%*****************************************************************************80
%
%% R8VEC_EVEN_SELECT returns the I-th of N evenly spaced values in [ XLO, XHI ].
%
%  Formula:
%
%    XVAL = ( (N-IVAL) * XLO + (IVAL-1) * XHI ) / dble ( N - 1 )
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 November 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real XLO, XHI, the low and high values.
%
%    Input, integer N, the number of values.
%
%    Input, integer IVAL, the index of the desired point.
%    IVAL is normally between 1 and N, but may be any
%    integer value.
%
%    Output, real XVAL, the IVAL-th of N evenly spaced values
%    between XLO and XHI.
%
%    Unless N = 1, X(1) = XLO and X(N) = XHI.
%
%    If N = 1, then X(1) = 0.5*(XLO+XHI).
%
  if ( n == 1 )

    xval = 0.5 * ( xlo + xhi );

  else

    xval = ( ( n - ival     ) * xlo   ...
           + (     ival - 1 ) * xhi ) ...
           / ( n        - 1 );

  end

  return
end


function GameOfLife
% This is a simple simulation of Conway Game of life GoL
% it is good for understanding Cellular Automata (CA) concept
% GoL Rules:
%   1. Survival: an alive cell live if it has 2 or 3 alive neighbors
%   2. Birth: a dead cell will be alive if it has 3 alive neighbors
%   3. Deaths:
%        Lonless: alive cell dies if it has 0 or 1 alive neighbors
%        Overcrowding: alive cell dies if it has 4 or more alive neighbors
% Any questions related to CA are welcome
% By: Ibraheem Al-Dhamari

clc;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%      Initialization
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% size= 500x500
% different random initial values
%A= rand(500,500);
%A= ones(500,500);

% periodic configuration
%A= zeros(500,500);
% A(100,200)=1;
% A(100,201)=1;
% A(100,202)=1;

% initial from image
 A=imread('CA02.JPG');

% convert to binary--> % states={0,1}
A=im2bw(A);
% visualize the initial states
disp('the binary image')
imshow(A);
pause
% boundary type: 0= reflection
%                1= doublication
%                2= null, zeros

% this step enlarge A with 4 virtual vectors
A=Bnd(A,0);
[d1,d2]=size(A);
disp('the extended binary image')
whos A
imshow(A);
pause
B=A;
t=0;
stp=false; % to stop when if no new configrations
%B is the CA in time t
%A is the CA in time t+1
%t is the number of generations

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   Play ^_^
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while ~stp & (t<10) % repeat for 10 generations
    % for each cell in the CA
    for i=2:d1-1
        for j=2:d2-1
            % apply Game of life rule
            A(i,j)=GOL(A,B,i,j)            ;
        end
    end
    % visualize what happened
    disp('the CA image')
    imshow(A);
    drawnow;
%    pause
    % save B
    if A==B
       stp=true; % no more new states
    end
    B=A;
    t=t+1
end

%==========================================
%   Game of Life Rules
%==========================================
function s=GOL (A,B,i,j)
% game of life rule
sm=0;
% count number of alive neighbors
sm=sm+ B(i-1,j-1)+B(i-1,j)+B(i-1,j+1);
sm=sm+ B(i,j-1)+           B(i,j+1);
sm=sm+ B(i+1,j-1)+B(i+1,j)+B(i+1,j+1);

% compute the new state of the current cell
s=B(i,j);
if B(i,j)==1
    if (sm>1)&&(sm<4)
        s=1;
    else
        s=0 ;
    end
else
    if sm==3
       s=1;
    end
end

%==========================================
%   Boundary Type
%==========================================
function bA= Bnd(A,k)
% add new four vectors based on boundary type
[d1, d2]=size(A);
d1=d1+2; d2=d2+2;
X=ones(d1,d2);
X=im2bw(X);
X(2:d1-1,2:d2-1)=A;
imshow(X);
whos A X
if k==0 % Reflection
   X(  1  , 2:d2-1)=A(end , :);
   X(  d1 , 2:d2-1)=A( 1  , :);
   X( 2:d1-1 , 1  )=A(: , end);
   X( 2:d1-1 , d2 )=A(: ,  1 );

   X(1,1)    =A(end,end);
   X(1,end)  =A(end,1);
   X(end,1)  =A(1,end);
   X(end,end)=A(1,1);
elseif k==1 % Double
   X(  1  , 2:d2-1)=A( 1  , :);
   X(  d1 , 2:d2-1)=A(end , :);
   X( 2:d1-1 , 1  )=A(: ,  1 );
   X( 2:d1-1 , d2 )=A(: , end);

   X(1,1)    =A(end,1);
   X(1,end)  =A(end,end);
   X(end,1)  =A(1,1);
   X(end,end)=A(1,end);

else % k==2 % zeros
   X(  1  ,:)=0;
   X( end ,:)=0;
   X(: ,  1  )=0;
   X(: , end )=0;
end
bA=X;


function [mu sigma2] = estimateGaussian(X)
%ESTIMATEGAUSSIAN This function estimates the parameters of a
%Gaussian distribution using the data in X
%   [mu sigma2] = estimateGaussian(X),
%   The input X is the dataset with each n-dimensional data point in one row
%   The output is an n-dimensional vector mu, the mean of the data set
%   and the variances sigma^2, an n x 1 vector
%

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

% You should return these values correctly
mu = zeros(n, 1);
sigma2 = zeros(n, 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the mean of the data and the variances
%               In particular, mu(i) should contain the mean of
%               the data for the i-th feature and sigma2(i)
%               should contain variance of the i-th feature.
%

mu=1./m.*sum(X)

%for i=1:n
%	sigma2(i)=1./m.*sum((X-mu(i)).^2);
%end
sigma2=var(X).*(m-1)./m;

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

end


%% Demonstration of the 2D Discrete Gram Transformation
%
% (C) 2013 Matthew harker and Paul O'Leary
% Institute for Automation
% University of Leoben
% A-8700 Leoben
% Austria
%
% email: office@harkeroleary.org
%
% This file produces a demonstration of the 2D discrete gram polynomial
% transformation of an image and the corresponding inverse transformation.
% It used the function |dgt| to compute the discrete Gram transformation
% and the function |idgt| to compute the inverse transformation.
%
% It is also demonstarted that the error in the reconstrcuted image ins
% negligible, i.e., approaching the numerical accuracy available in MATLAB.
% This demonstrates that the polynomial basis functions are free from error
% evant at very high degrees in this example d = 1024.
%
% This tool requires the discrete orthogonal toolbox: dopBox:
%
%   http://www.mathworks.com/matlabcentral/fileexchange/41250
%
%%
close all;
clear all;
%
% Set some defaults
%
FontSize = 12;
set(0,'DefaultaxesFontName','Times');
set(0,'DefaultaxesFontSize',FontSize);
set(0,'DefaulttextFontName','Times');
set(0,'DefaulttextFontSize',FontSize);
set(0,'DefaultTextInterpreter', 'latex');
%
%% Load an image and convert to a double gray data set
%
% This is an image of an art object. The snails are modelled in modelling
% material, they are not real animals.
%
[pic, map] = imread('snails1.jpg');
%
% Make the data mean free so that the spectrum is better viwible
%
D = double( rgb2gray( pic ));
D = D - mean(D(:));
%% View the Test Image
%
% View the image
%
fig1 = figure;
imagesc( pic );
axis image;
%
title('Photo Finish ($$\copyright$$ 2012 Paul O''Leary and Wolfgang Trettnak)');
xlabel('These are artificial snails and not real animals');
%
%% Compute the Gram Spectrum
%
% Call the |dgt2| function to compute the two dimensional Gram polynomial
% transformation. This is akin to the fft2 for the Fourier basis.
%
[S, Bx, By] = dgt2( D );
%
[ny,nx] = size( S );
%
% Compute the degrees in x and y directions.
%
xScale = 0:(nx-1);
yScale = 0:(ny-1);
%% View the 2D Polynomial Spectrum
%
% This is the complete 2D spectrum for the complete image.
%
fig2 = figure;
imagesc( xScale, yScale, S );
axis image;
colorbar
title('2D Gram Spectrum (information is at lower degrees)');
xlabel('Polynomial degree in $$x$$');
ylabel('Polynomial degree in $$y$$');
%
%% Zoomed Section of Spectrum
%
% Virtually all of the Information of the test image is concentrated at
% lower degrees. This can be shown by zooming in on the relevant portion
% of the spectrum.
%
fig3 = figure;
imagesc( xScale, yScale, S);
axis image;
colorbar
title('2D Gram Spectrum');
xlabel('Polynomial degree in $$x$$');
ylabel('Polynomial degree in $$y$$');
axis([0,20,0,20]);
%
%
%% Reconstruct the Image and Test for Errors
%
% The aim here is to reconstruct the image from its spectrum and then to
% compute a norm for the total error. This gives a measure for the quality
% of the transform inverse-transform pair.
%
% Note: the basis functions computed for the transform are passed to the
% inverse transform. this avoids the necessity to recompute the polynomial
% basis functions.
%
% As can be seen in the final figure, the Frobeneus norm of the error is in
% the order of $10^{-15}$, consequently, the polynomial transformation can
% be regarded as free from error.
%
Dr = idgt2( S, Bx, By );
%
% Calculate the difference between the original gray scale image and its
% reconstruction.
%
E = D - Dr;
%
% Compute the ratio of the Frobenius of the error to the norm of the data.
%
normE = norm( E, 'fro');
normD = norm( D, 'fro');
normEtoD = normE / normD;
%
%% View the Reconstructed Image.
%
fig3 = figure;
imagesc( Dr );
axis image;
colormap gray;
axis off;
title(['Reconstructed Gray Image ($$ \epsilon = ',num2str(normEtoD),' $$)']);
xlabel('These are artificial snails and not real animals');


function I = percentile2i(h,P)
%PERCENTILE2I Computes an intensity value given a percentile.
%   I = PERCENTILE2I(H,P) Given a percentile, P, and a histogram, H,
%   this function computes an intensity, I, representing the Pth
%   percentile and returns the value in I. P must be in the range [0, 1]
%   and I is returned as a value in the range [0, 1] also.
%
%   Example:
%
%   Suppose that h is a uniform histogram of an 8-bit image.  Typing
%
%       I = percentile2i(h,0.5)
%
%   would output I = 0.5. To convert to the (integer) 8-bit range
%   [0, 255], we let I = floor(255*I).
%
%   See also I2PERCENTILE.
%
%   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

% Check value of P.
if P < 0 || P > 1
   error('The percentile must be in the range [0, 1].')
end

% Normalized the histogram to unit area. If it is already normalized
% the following computation has no effect.
h = h/sum(h);

% Cumulative distribution.
C = cumsum(h);

% Calculations.
idx = find(C >= P,1,'first');
% Subtract 1 from idx because indexing starts at 1, but intensities
% start at 0. Also, normalize to the range [0, 1].
I = (idx - 1)/(numel(h) - 1);


function ng = ellipsoid_grid_count ( n, r, c )

%*****************************************************************************80
%
%% ELLIPSOID_GRID_COUNT counts the grid points inside an ellipsoid.
%
%  Discussion:
%
%    The ellipsoid is specified as
%
%      ( ( X - C1 ) / R1 )^2
%    + ( ( Y - C2 ) / R2 )^2
%    + ( ( Z - C3 ) / R3 )^2 = 1
%
%    The user supplies a number N.  There will be N+1 grid points along
%    the shortest axis.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    05 September 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of subintervals.
%
%    Input, real R(3), the half axis lengths.
%
%    Input, real C(3), the center of the ellipsoid.
%
%    Output, integer NG, the number of grid points inside the ellipsoid.
%
  if ( r(1) == min ( r ) )
    h = 2 * r(1) / ( 2 * n + 1 );
    ni = n;
    nj = ceil ( r(2) / r(1) ) * n;
    nk = ceil ( r(3) / r(1) ) * n;
  elseif ( r(2) == min ( r ) )
    h = 2 * r(2) / ( 2 * n + 1 );
    nj = n;
    ni = ceil ( r(1) / r(2) ) * n;
    nk = ceil ( r(3) / r(2) ) * n;
  else
    h = 2 * r(3) / ( 2 * n + 1 );
    nk = n;
    ni = ceil ( r(1) / r(3) ) * n;
    nj = ceil ( r(2) / r(3) ) * n;
  end

  ng = 0;

  for k = 0 : nk
    z = c(3) + k * h;
    for j = 0 : nj
      y = c(2) + j * h;
      for i = 0 : ni
        x = c(1) + i * h;
        if ( 1 < ( ( x - c(1) ) / r(1) ).^2 ...
               + ( ( y - c(2) ) / r(2) ).^2 ...
               + ( ( z - c(3) ) / r(3) ).^2 )
          break
        end
%
%  At least one point is generated, but more possible by symmetry.
%
        np = 1;
        if ( 0 < i )
          np = 2 * np;
        end
        if ( 0 < j )
          np = 2 * np;
        end
        if ( 0 < k )
          np = 2 * np;
        end
        ng = ng + np;

      end
    end
  end

  return
end


function [ n_data_new, n, c ] = sigma_values ( n_data )

%*****************************************************************************80
%
%% SIGMA_VALUES returns some values of the Sigma function.
%
%  Definition:
%
%    SIGMA(N) is the sum of the distinct divisors of N, including 1 and N.
%
%  First values:
%
%     N  SIGMA(N)
%
%     1    1
%     2    3
%     3    4
%     4    7
%     5    6
%     6   12
%     7    8
%     8   15
%     9   13
%    10   18
%    11   12
%    12   28
%    13   14
%    14   24
%    15   24
%    16   31
%    17   18
%    18   39
%    19   20
%    20   42
%
%  Formula:
%
%    SIGMA(U*V) = SIGMA(U) * SIGMA(V) if U and V are relatively prime.
%
%    SIGMA(P**K) = ( P**(K+1) - 1 ) / ( P - 1 ) if P is prime.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 May 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Milton Abramowitz and Irene Stegun,
%    Handbook of Mathematical Functions,
%    US Department of Commerce, 1964.
%
%  Parameters:
%
%    Input, integer N_DATA, indicates the index of the previous test data
%    returned, or is 0 if this is the first call.  For repeated calls,
%    set the input value of N_DATA to the output value of N_DATA_NEW
%    from the previous call.
%
%    Output, integer N_DATA_NEW, the index of the test data.
%
%    Output, integer N, the argument of the Sigma function.
%
%    Output, integer C, the value of the Sigma function.
%
  n_max = 20;
  c_vec = [ ...
     1,    3,    4,    7,    6,   12,    8,   15,   13,   18, ...
    72,  128,  255,  176,  576, 1170,  618,  984, 2232, 2340 ];
  n_vec = [ ...
      1,   2,   3,   4,   5,   6,   7,   8,   9,  10, ...
     30, 127, 128, 129, 210, 360, 617, 815, 816,1000 ];

  n_data_new = n_data;

  if ( n_data_new < 0 )
    n_data_new = 0;
  end

  n_data_new = n_data_new + 1;

  if ( n_max < n_data_new )
    n_data_new = 0;
    n = 0;
    c = 0;
  else
    n = n_vec(n_data_new);
    c = c_vec(n_data_new);
  end

  return
end


function out = slidingavg(in, N)
%   OUTPUT_ARRAY = SLIDINGAVG(INPUT_ARRAY, N)
%
%  The function 'slidingavg' implements a one-dimensional filtering, applying a sliding window to a sequence. Such filtering replaces the center value in
%  the window with the average value of all the points within the window. When the sliding window is exceeding the lower or upper boundaries of the input
%  vector INPUT_ARRAY, the average is computed among the available points. Indicating with nx the length of the the input sequence, we note that for values
%  of N larger or equal to 2*(nx - 1), each value of the output data array are identical and equal to mean(in).
%
%  *  The input argument INPUT_ARRAY is the numerical data array to be processed.
%  *  The input argument N  is the number of neighboring data points to average over for each point of IN.
%
%  *  The output argument OUTPUT_ARRAY is the output data array.
%
%     Š 2002 - Michele Giugliano, PhD and Maura Arsiero
%     (Bern, Friday July 5th, 2002 - 21:10)
%    (http://www.giugliano.info) (bug-reports to michele@giugliano.info)
%
% Two simple examples with second- and third-order filters are
%  slidingavg([4 3 5 2 8 9 1],2)
%  ans =
%   3.5000  4.0000  3.3333  5.0000  6.3333  6.0000  5.0000
%
%  slidingavg([4 3 5 2 8 9 1],3)
%  ans =
%   3.5000  4.0000  3.3333  5.0000  6.3333  6.0000  5.0000
%

if (isempty(in)) | (N<=0)                                              % If the input array is empty or N is non-positive,
 disp(sprintf('SlidingAvg: (Error) empty input data or N null.'));     % an error is reported to the standard output and the
 return;                                                               % execution of the routine is stopped.
end % if

if (N==1)                                                              % If the number of neighbouring points over which the sliding
 out = in;                                                             % average will be performed is '1', then no average actually occur and
 return;                                                               % OUTPUT_ARRAY will be the copy of INPUT_ARRAY and the execution of the routine
end % if                                                               % is stopped.

nx   = length(in);             % The length of the input data structure is acquired to later evaluate the 'mean' over the appropriate boundaries.

if (N>=(2*(nx-1)))                                                     % If the number of neighbouring points over which the sliding
 out = mean(in)*ones(size(in));                                        % average will be performed is large enough, then the average actually covers all the points
 return;                                                               % of INPUT_ARRAY, for each index of OUTPUT_ARRAY and some CPU time can be gained by such an approach.
end % if                                                               % The execution of the routine is stopped.

out = zeros(size(in));         % In all the other situations, the initialization of the output data structure is performed.

if rem(N,2)~=1                 % When N is even, then we proceed in taking the half of it:
 m = N/2;                      % m = N     /  2.
else                           % Otherwise (N >= 3, N odd), N-1 is even ( N-1 >= 2) and we proceed taking the half of it:
 m = (N-1)/2;                  % m = (N-1) /  2.
end % if

for i=1:nx,                                                 % For each element (i-th) contained in the input numerical array, a check must be performed:
 if ((i-m) < 1) & ((i+m) <= nx)                             % If not enough points are available on the left of the i-th element..
  out(i) = mean(in(1:i+m));                                 % then we proceed to evaluate the mean from the first element to the (i + m)-th.
 elseif ((i-m) >= 1) & ((i+m) <= nx)                        % If enough points are available on the left and on the right of the i-th element..
  out(i) = mean(in(i-m:i+m));                               % then we proceed to evaluate the mean on 2*m elements centered on the i-th position.
elseif ((i-m) >= 1) & ((i+m) > nx)                          % If not enough points are available on the rigth of the i-th element..
  out(i) = mean(in(i-m:nx));                                % then we proceed to evaluate the mean from the element (i - m)-th to the last one.
 elseif ((i-m) < 1) & ((i+m) > nx)                          % If not enough points are available on the left and on the rigth of the i-th element..
  out(i) = mean(in(1:nx));                                  % then we proceed to evaluate the mean from the first element to the last.
 end % if
end % for i


function Angles = FindAngles(vertices)

% Purpose: To find the angles of Triangle or Quadrilateral
% Synopsis: Angles = FindAngles(vertices)
% Variable description:
% INPUT: vertices - coordinates of Triangle and Quadrilateral
%                   order 3X2 if vertices are of Triangle and 4X2 if vertices
%                   are of Quadrilateral. The vertices are given input in
%                   anticlock wise direction.
% OUTPUT: Angles - Row vector of angles of Triangle/ Quadrilateral in degrees.
%                  3X1 for Trianle and 4X1 for Quadrilateral
% Example: vertices = [4 0;5 1;4 1]                 } Triangle vertices
%          angles = FindAngles(vertices);
%          angles = [45.0000   45.0000   90.0000]
%
%          vertices = [4  4;4  6;5 6; 5  4]         } Quadrilateral vertices
%          angles = FindAngles(vertices);
%          angles = [90 90 90 90]
%
% Algorithm: Calculates the angles using dot product
%            theta = arccos((a.b)/(|a||b|)
% Release : 1.0
% Release Date: 03/07/2012
%---------------------------------------------------------------------------
% Author : Siva Srinivas Kolukula
%          Senior Research Fellow
%          Structural Mechanics Laboratory
%          Indira Gandhi Center for Atomic Research
%          India
% E-mail : allwayzitzme@gmail.com
%          http://sites.google.com/site/kolukulasivasrinivas/
%---------------------------------------------------------------------------

N = length(vertices) ;
if N == 3
    disp('vertices are of Triangle')
    order = [1 2 3; 2 1 3;3 1 2] ;
elseif N == 4
    disp('Vertices are of Quadrilateral')
    order = [ 1 2 4; 2 1 3; 3 4 2;4 3 1] ;
else
    error('Wrong input')
end

    Angles = zeros(1,N) ;

for i = 1:N
    % Form the vectors along the vertices
    vec1 = [vertices(i,:); vertices(order(i,2),:)];
    vec2 = [vertices(i,:); vertices(order(i,3),:)];
    % Use dor ptodict to find the angle between vector1 and vector2
    Angles(i) = acos((diff(vec1)*diff(vec2)')/.....
        (sqrt(sum(diff(vec1,[],1).^2,2))*sqrt(sum(diff(vec2,[],1).^2,2)))) ;
end

% Convert the angles in radians to degrees
Angles = Angles*180./pi ;        %


function [J, grad] = costFunction(theta, X, y)
%COSTFUNCTION Compute cost and gradient for logistic regression
%   J = COSTFUNCTION(theta, X, y) computes the cost of using theta as the
%   parameter for logistic regression and the gradient of the cost
%   w.r.t. to the parameters.

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

% You need to return the following variables correctly
J = 0;
grad = zeros(size(theta));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta.
%               You should set J to the cost.
%               Compute the partial derivatives and set grad to the partial
%               derivatives of the cost w.r.t. each parameter in theta
%
% Note: grad should have the same dimensions as theta
%

htheta = sigmoid(X * theta);
J = 1 / m * sum(-y .* log(htheta) - (1 - y) .* log(1 - htheta));
for i = 1:size(theta, 1)
    grad(i) = 1 / m * sum((htheta - y) .* X(:, i));
end

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

end