Result:
best_fit_for_X1 =
DistName: \'tlocationscale\'
NLogL: 2.1206e+03
BIC: 4.2620e+03
AIC: 4.2472e+03
AICc: 4.2473e+03
ParamNames: {\'mu\' \'sigma\' \'nu\'}
ParamDescription: {\'location\' \'scale\' \'degrees of freedom\'}
Params: [1.0071 1.9637 37.4643]
Paramci: [2x3 double]
ParamCov: [3x3 double]
Support: [1x1 struct]
best_fit_for_X2 =
DistName: \'generalized extreme value\'
NLogL: 2.4968e+03
BIC: 5.0142e+03
AIC: 4.9995e+03
AICc: 4.9995e+03
ParamNames: {\'k\' \'sigma\' \'mu\'}
ParamDescription: {\'shape\' \'scale\' \'location\'}
Params: [-0.2802 2.9571 1.0858]
Paramci: [2x3 double]
ParamCov: [3x3 double]
Support: [1x1 struct]
correlation_between_X1_X2 = 0.0084 (hence X1 and X2 are independent)
meanY = 3.1394
varY = 12.8269
meanZ = 4.1492
varZ = 25.1576
correlation_between_Y_Z = 0.9438 (Hence Y and Z are dependent)
Code:
function main
load X.mat
[D PD]=allfitdist(X1,\'NLogL\');
[D2 PD2]=allfitdist(X2,\'NLogL\');
%best fit using maximum likelihood
best_fit_for_X1=D(1)
best_fit_for_X2=D2(1)
correlation_between_X1_X2=correlation(X1,X2)
Y=X1+X2;
Z=2*X1+X2;
meanY=mean(Y)
varY=var(Y)
meanZ=mean(Z)
varZ=var(Z)
correlation_between_Y_Z=correlation(Y,Z)
end
function[r]=correlation(x,y)
avx = mean(x); ex2 = sum((x - avx).^2); %Wasteful multiple passes are a pain,
avy = mean(y); ey2 = sum((y - avy).^2); %But explicit loops
exy = sum((x - avx).*(y - avy)); %Are interpreted slowly.
r = exy/sqrt(ex2*ey2); %Division by N cancels; ignoring the N - 1 ritual.
end
function [D PD] = allfitdist(data,sortby,varargin)
%ALLFITDIST Fit all valid parametric probability distributions to data.
% [D PD] = ALLFITDIST(DATA) fits all valid parametric probability
% distributions to the data in vector DATA, and returns a struct D of
% fitted distributions and parameters and a struct of objects PD
% representing the fitted distributions. PD is an object in a class
% derived from the ProbDist class.
%
% [...] = ALLFITDIST(DATA,SORTBY) returns the struct of valid distributions
% sorted by the parameter SORTBY
% NLogL - Negative of the log likelihood
% BIC - Bayesian information criterion (default)
% AIC - Akaike information criterion
% AICc - AIC with a correction for finite sample sizes
%
% [...] = ALLFITDIST(...,\'DISCRETE\') specifies it is a discrete
% distribution and does not attempt to fit a continuous distribution
% to the data
%
% [...] = ALLFITDIST(...,\'PDF\') or (...,\'CDF\') plots either the PDF or CDF
% of a subset of the fitted distribution. The distributions are plotted in
% order of fit, according to SORTBY.
%
% List of distributions it will try to fit
% Continuous (default)
% Beta
% Birnbaum-Saunders
% Exponential
% Extreme value
% Gamma
% Generalized extreme value
% Generalized Pareto
% Inverse Gaussian
% Logistic
% Log-logistic
% Lognormal
% Nakagami
% Normal
% Rayleigh
% Rician
% t location-scale
% Weibull
%
% Discrete (\'DISCRETE\')
% Binomial
% Negative binomial
% Poisson
%
% Optional inputs:
% [...] = ALLFITDIST(...,\'n\',N,...)
% For the \'binomial\' .
The document describes several programs to solve problems related to quadratic equations, reversing integers, finding square roots, and determining if a year is a leap year. It includes algorithms and C code to:
1) Take coefficients of a quadratic equation as input and compute all possible roots, handling real, equal, and complex cases.
2) Reverse an integer number and check if it is a palindrome.
3) Find the square root of a number without using library functions.
4) Read a year and determine if it is a leap year, considering end of century rules.
The document contains code for several C programs that demonstrate different programming concepts like calculating the roots of a quadratic equation, converting between Fahrenheit and Celsius, finding the largest of three numbers, calculating the harmonic series, checking for a leap year, calculating the area of a circle, and calculating the factorial of a number. Each code sample is preceded by a brief description and followed by the output when the code is run.
The document describes arrays and array operations like sorting and computing statistics. It defines arrays as structures that hold related data items of the same type. Arrays can be passed to functions by reference so the function can modify the original array. The document provides examples of using arrays to compute the mean, median, and mode of survey response data by sorting the array and counting frequencies. Functions are defined to calculate each statistic and sort the array using bubble sort.
The document describes 5 common mathematical functions in C programming - atan(), cos(), div(), modf(), and sin(). It provides the purpose, syntax, parameters, and examples of how to use each function. The atan() function computes the inverse tangent of a value. The cos() function computes the cosine of an angle in radians. The div() function performs integer division and returns the quotient and remainder. The sin() function computes the sine of an angle in radians.
This document discusses pointers and strings in C programming. It covers defining strings as character arrays, common string functions like strlen(), strcpy(), comparing strings with strcmp(), and 2D character arrays. It also explains pointers in detail including declaring pointer variables, dereferencing with *, address of operator &, passing pointers to functions, pointer arithmetic, and dynamic memory allocation using malloc(). The key drawbacks of pointers discussed are that they are complicated to use and debug, can cause issues if not initialized or memory freed properly, and updating pointers incorrectly can lead to memory corruption.
The document contains code snippets demonstrating various programming concepts in C including:
- Hello world program
- Infinite loops using while and for loops
- For and while loops to iterate from 0 to 5
- Increment and decrement operators
- Functions to add two numbers and using pointers
- Conditional operators to check odd/even
- Switch statements
- Checking leap years
- Palindrome, perfect, and factorial numbers using recursion
- Greatest common divisor and least common multiple
- Converting between binary and decimal
- Permutations and combinations using functions
- Pattern matching using loops and variables
The document describes a project involving image processing and boundary analysis. It includes:
1. Smoothing an image, thresholding it to binary, extracting the outer boundary, subsampling the boundary, and computing the Freeman chain code and descriptors of the subsampled boundary.
2. Extracting the boundary of an image of a chromosome, computing the Fourier descriptors of the boundary, and reconstructing the boundary using different percentages of the descriptors.
3. The provided code computes Freeman chain codes, Fourier descriptors, and performs other boundary analysis tasks like subsampling and reconstruction from descriptors.
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019corehard_by
LLVM содержит огромное количество оптимизаций и подходит в качестве бэкенда для многих языков программирования. Но все немного усложняется для Managed языков и JIT сценариев. В этом докладе Егор расскажет о трудностях, с которыми столкнулись в C# при реализации LLVM бэкенда.
The document describes several programs to solve problems related to quadratic equations, reversing integers, finding square roots, and determining if a year is a leap year. It includes algorithms and C code to:
1) Take coefficients of a quadratic equation as input and compute all possible roots, handling real, equal, and complex cases.
2) Reverse an integer number and check if it is a palindrome.
3) Find the square root of a number without using library functions.
4) Read a year and determine if it is a leap year, considering end of century rules.
The document contains code for several C programs that demonstrate different programming concepts like calculating the roots of a quadratic equation, converting between Fahrenheit and Celsius, finding the largest of three numbers, calculating the harmonic series, checking for a leap year, calculating the area of a circle, and calculating the factorial of a number. Each code sample is preceded by a brief description and followed by the output when the code is run.
The document describes arrays and array operations like sorting and computing statistics. It defines arrays as structures that hold related data items of the same type. Arrays can be passed to functions by reference so the function can modify the original array. The document provides examples of using arrays to compute the mean, median, and mode of survey response data by sorting the array and counting frequencies. Functions are defined to calculate each statistic and sort the array using bubble sort.
The document describes 5 common mathematical functions in C programming - atan(), cos(), div(), modf(), and sin(). It provides the purpose, syntax, parameters, and examples of how to use each function. The atan() function computes the inverse tangent of a value. The cos() function computes the cosine of an angle in radians. The div() function performs integer division and returns the quotient and remainder. The sin() function computes the sine of an angle in radians.
This document discusses pointers and strings in C programming. It covers defining strings as character arrays, common string functions like strlen(), strcpy(), comparing strings with strcmp(), and 2D character arrays. It also explains pointers in detail including declaring pointer variables, dereferencing with *, address of operator &, passing pointers to functions, pointer arithmetic, and dynamic memory allocation using malloc(). The key drawbacks of pointers discussed are that they are complicated to use and debug, can cause issues if not initialized or memory freed properly, and updating pointers incorrectly can lead to memory corruption.
The document contains code snippets demonstrating various programming concepts in C including:
- Hello world program
- Infinite loops using while and for loops
- For and while loops to iterate from 0 to 5
- Increment and decrement operators
- Functions to add two numbers and using pointers
- Conditional operators to check odd/even
- Switch statements
- Checking leap years
- Palindrome, perfect, and factorial numbers using recursion
- Greatest common divisor and least common multiple
- Converting between binary and decimal
- Permutations and combinations using functions
- Pattern matching using loops and variables
The document describes a project involving image processing and boundary analysis. It includes:
1. Smoothing an image, thresholding it to binary, extracting the outer boundary, subsampling the boundary, and computing the Freeman chain code and descriptors of the subsampled boundary.
2. Extracting the boundary of an image of a chromosome, computing the Fourier descriptors of the boundary, and reconstructing the boundary using different percentages of the descriptors.
3. The provided code computes Freeman chain codes, Fourier descriptors, and performs other boundary analysis tasks like subsampling and reconstruction from descriptors.
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019corehard_by
LLVM содержит огромное количество оптимизаций и подходит в качестве бэкенда для многих языков программирования. Но все немного усложняется для Managed языков и JIT сценариев. В этом докладе Егор расскажет о трудностях, с которыми столкнулись в C# при реализации LLVM бэкенда.
There are so many mathematical symbols that are important for students. To make it easier for you we’ve given here the mathematical symbols table with definitions and examples
Unit: Curve-Fitting
Introduction: The document discusses using the least squares method to fit curves to data points by finding polynomial functions that minimize the errors between the fitted curve and data points.
It provides examples of fitting first degree (linear) and second degree (parabolic) polynomial curves to data sets. For linear curves, it shows calculating the constants c0 and c1 using sums and determinants to find the best fit line Y=c0+c1X. For parabolic curves, it similarly calculates constants c0, c1, and c2 to find the best fit quadratic curve Y=c0+c1X+c2X^2.
It also provides a worked example
gptips1.0/concrete.mat
Concrete_Data:[1030x9 double array]
tr_ind:[1030x1 uint8 (logical) array]
te_ind:[1030x1 uint8 (logical) array]
tr_ind2:[773x1 uint8 (logical) array]
val_ind:[773x1 uint8 (logical) array]
gptips1.0/crossover.m
function [son,daughter]=crossover(mum,dad,gp)
%CROSSOVER GPTIPS function to crossover 2 GP expressions to produce 2 new
%GP expressions.
%
% [SON,DAUGHTER]=CROSSOVER(MUM,DAD,GP) uses standard subtree
% crossover on the expressions MUM and DAD to produce the offspring
% expressions SON and DAUGHTER.
%
% (c) Dominic Searson 2009
%
% v1.0
%
% See also MUTATE
% select random crossover nodes in mum and dad expressions
m_position=picknode(mum,0,gp);
d_position=picknode(dad,0,gp);
% extract main and subtree expressions
[m_main,m_sub]=extract(m_position,mum);
[d_main,d_sub]=extract(d_position,dad);
%combine to form 2 new GPtrees
daughter=strrep(m_main,'$',d_sub);
son=strrep(d_main,'$',m_sub);
gptips1.0/demo2data.mat
gptips1.0/displaystats.m
function displaystats(gp)
%DISPLAYSTATS GPTIPS function to display run stats periodically.
%
% DISPLAYSTATS(GP) updates the screen with run stats at the interval
% specified in GP.RUN.VERBOSE
%
% (c) Dominic Searson 2009
%
% v1.0
%
% See also: UPDATESTATS
%only display info if required
if ~gp.runcontrol.verbose || gp.runcontrol.quiet || mod(gp.state.count-1,gp.runcontrol.verbose)
return
end
gen=gp.state.count-1;
disp(['Generation ' num2str(gen)]);
disp(['Best fitness: ' num2str(gp.results.best.fitness)]);
disp(['Mean fitness: ' num2str(gp.state.meanfitness)]);
disp(['Best nodecount: ' num2str(gp.results.best.numnodes)]);
disp(' ');
gptips1.0/evalfitness.m
function [gp]=evalfitness(gp)
%EVALFITNESS GPTIPS function to call the user specified fitness function.
%
% [GP]=EVALFITNESS(GP) evaluates the the fitnesses of individuals stored
% in the GP structure and updates various other fields of GP accordingly.
%
% (c) Dominic Searson 2009
%
% v1.0
%
% See also TREE2EVALSTR
% Loop through population and calculate fitnesses
for i=1:gp.runcontrol.pop_size
% update state to reflect the index of the individual that is about to
% be evaluated
gp.state.current_individual=i;
%First preprocess the cell array of string expressions into a form that
%Matlab can evaluate
evalstr=tree2evalstr(gp.pop{i},gp);
%store number of nodes (sum total for all genes)
gp.fitness.numnodes(i,1)=getnumnodes(gp.pop{i});
% Evaluate gp individual using fitness function
% (the try catch is to assign a poor fitness value
% to trees that violate Matlab's
% daft 'Nesting of {, [, and ( cannot exceed a depth of 32.' error.
try
[fitness,gp]=feval(gp.fitness.fitfun,evalstr,gp);
gp.fitness.values(i)=fitness;
catch
if ~strncmpi(lasterr,'Nesting of {',12);
error(lasterr);
...
The document discusses various techniques for curve fitting data, including interpolation, linear regression, and higher-order polynomial fitting. It begins by explaining the motivation for curve fitting as creating a single function to represent trends in observed data. Linear regression finds the best-fit straight line by minimizing the squared errors between data points and the line. Higher-order polynomials allow fitting nonlinear trends by finding coefficients for polynomial functions up to a given order, such as quadratic, that also minimize the squared errors.
This document contains code to solve quadratic equations and find roots of functions using the bisection method. The quadratic equation code calculates the discriminant and uses it to determine the number and type of roots, printing the result. The bisection method code iteratively calculates the midpoint between guesses for a root and determines if the next guess should be the lower or upper value based on the sign of the function at each point until convergence within a set tolerance.
The document summarizes topics covered in a programming for problem solving (PPS) class, including control structures like if/else statements, loops, and switch cases. Example programs are provided to find the largest of three numbers, determine if a character is a vowel or consonant, and identify the type of triangle based on angle or side lengths. The last example uses nested if/else and switch statements to classify triangles as equilateral, isosceles, right-angled, or scalene depending on the problem constraints.
Switch case statements can be used as a substitute for long if-else statements when comparing an integral value. The switch statement allows executing different blocks of code based on the value of a variable. It contains case labels that match values and an optional default case to handle unexpected values. Break statements are used to exit each case block and prevent falling through to the next block.
The document describes building regression and classification models in R, including linear regression, generalized linear models, decision trees, and random forests. It uses examples of CPI data to demonstrate linear regression and predicts CPI values in 2011. For classification, it builds a decision tree model on the iris dataset using the party package and visualizes the tree. The document provides information on evaluating and comparing different models.
MH prediction modeling and validation in r (2) classification 190709Min-hyung Kim
This document presents code for modeling mortality risk from patient data. It:
1) Loads and preprocesses a training dataset, including imputing missing values;
2) Fits two logistic regression models to predict mortality from age and BMI: a simple model with linear terms and a more complex model with quadratic terms;
3) Visualizes the models by plotting predictions against the data and applying classification thresholds;
4) Calculates the area under the receiver operating characteristic curve (AUROC) on the training data to evaluate model performance.
The AUROC is 0.778 for the simple model and 0.779 for the complex model, indicating modest predictive ability.
The document contains summaries of several C programming examples:
1. Programs to calculate the area and circumference of a circle, find simple interest, convert temperatures between Celsius and Fahrenheit, calculate subject marks and percentages, and calculate gross salary.
2. Additional programs demonstrate swapping values with and without a third variable, finding the greatest of three numbers, determining if a year is a leap year, and identifying integers as odd or even, positive or negative.
3. Further programs check if an integer is divisible by 5 and 11, compare two integers for equality, use a switch statement to print days of the week, and perform arithmetic operations using a switch case.
PyData NYC 2015 - Automatically Detecting Outliers with Datadog Datadog
Monitoring even a modestly-sized systems infrastructure quickly becomes untenable without automated alerting. For many metrics it is nontrivial to define ahead of time what constitutes “normal” versus “abnormal” values. This is especially true for metrics whose baseline value fluctuates over time. To make this problem more tractable, Datadog provides outlier detection functionality to automatically identify any host (or group of hosts) that is behaving abnormally compared to its peers.
These slides cover the algorithms we use for outlier detection, and show how easy they are to implement using Python. This presentation also covers the lessons we've learned from using outlier detection on our own systems, along with some real-life examples on how to avoid false positives and negatives.
Learn more at www.datadoghq.com.
The document discusses hacking the Ruby parser parse.y to add new syntax features to the Ruby language. It covers several cases:
1. Adding :-) as an alias for => in hash literals.
2. Treating single quotes as symbol literals under certain conditions.
3. Adding ++ as an incremental operator.
4. Parsing the A#b syntax for defining instance methods.
The document analyzes how parse.y and the lexer deal with colons, quotes, comments and other syntax elements, and shows the changes needed to parse the new syntax features. It also discusses Ruby internals like the parser generator bison, and MRI implementation details like the parse.y file size.
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th.
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th.
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th.
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th.
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th.
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th.
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th..
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th.
When two data sets are pooled together the pooled mean will alway.pdfaparnatiwari291
When two data sets are pooled together the pooled mean will always be more accurate, between
original mean values and more precise.
Ans: (e)
Solution
When two data sets are pooled together the pooled mean will always be more accurate, between
original mean values and more precise.
Ans: (e).
DELTOID flexes and medially rotates arm; prime mover of arm abduct.pdfaparnatiwari291
DELTOID : flexes and medially rotates arm; prime mover of arm abduction; extends and
laterally rotates arm. LATISSIMUS DORI : prime mover of arm extension; adducts and medially
rotates arm (big muscle). PECTORALIS MAJOR : prime mover of arm flexion, adducts and
medially rotates arm ( big muscle). TERES MAJOR : Extends, adducts and medially rotates arm.
Solution
DELTOID : flexes and medially rotates arm; prime mover of arm abduction; extends and
laterally rotates arm. LATISSIMUS DORI : prime mover of arm extension; adducts and medially
rotates arm (big muscle). PECTORALIS MAJOR : prime mover of arm flexion, adducts and
medially rotates arm ( big muscle). TERES MAJOR : Extends, adducts and medially rotates arm..
More Related Content
Similar to Resultbest_fit_for_X1 =DistName tlocationscaleNLogL 2.1.pdf
There are so many mathematical symbols that are important for students. To make it easier for you we’ve given here the mathematical symbols table with definitions and examples
Unit: Curve-Fitting
Introduction: The document discusses using the least squares method to fit curves to data points by finding polynomial functions that minimize the errors between the fitted curve and data points.
It provides examples of fitting first degree (linear) and second degree (parabolic) polynomial curves to data sets. For linear curves, it shows calculating the constants c0 and c1 using sums and determinants to find the best fit line Y=c0+c1X. For parabolic curves, it similarly calculates constants c0, c1, and c2 to find the best fit quadratic curve Y=c0+c1X+c2X^2.
It also provides a worked example
gptips1.0/concrete.mat
Concrete_Data:[1030x9 double array]
tr_ind:[1030x1 uint8 (logical) array]
te_ind:[1030x1 uint8 (logical) array]
tr_ind2:[773x1 uint8 (logical) array]
val_ind:[773x1 uint8 (logical) array]
gptips1.0/crossover.m
function [son,daughter]=crossover(mum,dad,gp)
%CROSSOVER GPTIPS function to crossover 2 GP expressions to produce 2 new
%GP expressions.
%
% [SON,DAUGHTER]=CROSSOVER(MUM,DAD,GP) uses standard subtree
% crossover on the expressions MUM and DAD to produce the offspring
% expressions SON and DAUGHTER.
%
% (c) Dominic Searson 2009
%
% v1.0
%
% See also MUTATE
% select random crossover nodes in mum and dad expressions
m_position=picknode(mum,0,gp);
d_position=picknode(dad,0,gp);
% extract main and subtree expressions
[m_main,m_sub]=extract(m_position,mum);
[d_main,d_sub]=extract(d_position,dad);
%combine to form 2 new GPtrees
daughter=strrep(m_main,'$',d_sub);
son=strrep(d_main,'$',m_sub);
gptips1.0/demo2data.mat
gptips1.0/displaystats.m
function displaystats(gp)
%DISPLAYSTATS GPTIPS function to display run stats periodically.
%
% DISPLAYSTATS(GP) updates the screen with run stats at the interval
% specified in GP.RUN.VERBOSE
%
% (c) Dominic Searson 2009
%
% v1.0
%
% See also: UPDATESTATS
%only display info if required
if ~gp.runcontrol.verbose || gp.runcontrol.quiet || mod(gp.state.count-1,gp.runcontrol.verbose)
return
end
gen=gp.state.count-1;
disp(['Generation ' num2str(gen)]);
disp(['Best fitness: ' num2str(gp.results.best.fitness)]);
disp(['Mean fitness: ' num2str(gp.state.meanfitness)]);
disp(['Best nodecount: ' num2str(gp.results.best.numnodes)]);
disp(' ');
gptips1.0/evalfitness.m
function [gp]=evalfitness(gp)
%EVALFITNESS GPTIPS function to call the user specified fitness function.
%
% [GP]=EVALFITNESS(GP) evaluates the the fitnesses of individuals stored
% in the GP structure and updates various other fields of GP accordingly.
%
% (c) Dominic Searson 2009
%
% v1.0
%
% See also TREE2EVALSTR
% Loop through population and calculate fitnesses
for i=1:gp.runcontrol.pop_size
% update state to reflect the index of the individual that is about to
% be evaluated
gp.state.current_individual=i;
%First preprocess the cell array of string expressions into a form that
%Matlab can evaluate
evalstr=tree2evalstr(gp.pop{i},gp);
%store number of nodes (sum total for all genes)
gp.fitness.numnodes(i,1)=getnumnodes(gp.pop{i});
% Evaluate gp individual using fitness function
% (the try catch is to assign a poor fitness value
% to trees that violate Matlab's
% daft 'Nesting of {, [, and ( cannot exceed a depth of 32.' error.
try
[fitness,gp]=feval(gp.fitness.fitfun,evalstr,gp);
gp.fitness.values(i)=fitness;
catch
if ~strncmpi(lasterr,'Nesting of {',12);
error(lasterr);
...
The document discusses various techniques for curve fitting data, including interpolation, linear regression, and higher-order polynomial fitting. It begins by explaining the motivation for curve fitting as creating a single function to represent trends in observed data. Linear regression finds the best-fit straight line by minimizing the squared errors between data points and the line. Higher-order polynomials allow fitting nonlinear trends by finding coefficients for polynomial functions up to a given order, such as quadratic, that also minimize the squared errors.
This document contains code to solve quadratic equations and find roots of functions using the bisection method. The quadratic equation code calculates the discriminant and uses it to determine the number and type of roots, printing the result. The bisection method code iteratively calculates the midpoint between guesses for a root and determines if the next guess should be the lower or upper value based on the sign of the function at each point until convergence within a set tolerance.
The document summarizes topics covered in a programming for problem solving (PPS) class, including control structures like if/else statements, loops, and switch cases. Example programs are provided to find the largest of three numbers, determine if a character is a vowel or consonant, and identify the type of triangle based on angle or side lengths. The last example uses nested if/else and switch statements to classify triangles as equilateral, isosceles, right-angled, or scalene depending on the problem constraints.
Switch case statements can be used as a substitute for long if-else statements when comparing an integral value. The switch statement allows executing different blocks of code based on the value of a variable. It contains case labels that match values and an optional default case to handle unexpected values. Break statements are used to exit each case block and prevent falling through to the next block.
The document describes building regression and classification models in R, including linear regression, generalized linear models, decision trees, and random forests. It uses examples of CPI data to demonstrate linear regression and predicts CPI values in 2011. For classification, it builds a decision tree model on the iris dataset using the party package and visualizes the tree. The document provides information on evaluating and comparing different models.
MH prediction modeling and validation in r (2) classification 190709Min-hyung Kim
This document presents code for modeling mortality risk from patient data. It:
1) Loads and preprocesses a training dataset, including imputing missing values;
2) Fits two logistic regression models to predict mortality from age and BMI: a simple model with linear terms and a more complex model with quadratic terms;
3) Visualizes the models by plotting predictions against the data and applying classification thresholds;
4) Calculates the area under the receiver operating characteristic curve (AUROC) on the training data to evaluate model performance.
The AUROC is 0.778 for the simple model and 0.779 for the complex model, indicating modest predictive ability.
The document contains summaries of several C programming examples:
1. Programs to calculate the area and circumference of a circle, find simple interest, convert temperatures between Celsius and Fahrenheit, calculate subject marks and percentages, and calculate gross salary.
2. Additional programs demonstrate swapping values with and without a third variable, finding the greatest of three numbers, determining if a year is a leap year, and identifying integers as odd or even, positive or negative.
3. Further programs check if an integer is divisible by 5 and 11, compare two integers for equality, use a switch statement to print days of the week, and perform arithmetic operations using a switch case.
PyData NYC 2015 - Automatically Detecting Outliers with Datadog Datadog
Monitoring even a modestly-sized systems infrastructure quickly becomes untenable without automated alerting. For many metrics it is nontrivial to define ahead of time what constitutes “normal” versus “abnormal” values. This is especially true for metrics whose baseline value fluctuates over time. To make this problem more tractable, Datadog provides outlier detection functionality to automatically identify any host (or group of hosts) that is behaving abnormally compared to its peers.
These slides cover the algorithms we use for outlier detection, and show how easy they are to implement using Python. This presentation also covers the lessons we've learned from using outlier detection on our own systems, along with some real-life examples on how to avoid false positives and negatives.
Learn more at www.datadoghq.com.
The document discusses hacking the Ruby parser parse.y to add new syntax features to the Ruby language. It covers several cases:
1. Adding :-) as an alias for => in hash literals.
2. Treating single quotes as symbol literals under certain conditions.
3. Adding ++ as an incremental operator.
4. Parsing the A#b syntax for defining instance methods.
The document analyzes how parse.y and the lexer deal with colons, quotes, comments and other syntax elements, and shows the changes needed to parse the new syntax features. It also discusses Ruby internals like the parser generator bison, and MRI implementation details like the parse.y file size.
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th.
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th.
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th.
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th.
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th.
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th.
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th..
#include
#include
#include
using namespace std;
template //For Template
void bogosort(std::vector& array) //For bogosort
{
while (! is_sorted(array))
{
std::random_shuffle(array.begin(), array.end());
}
}
template
bool is_sorted(const std::vector& array) //Conforming for display
{
for (typename std::vector::size_type i = 1; i < array.size(); ++i)
{
if (array[i] < array[i-1])
{
return false;
}
}
return true;
}
std::vector a (10); //Creates a vector of size 10
int arr[10];
template
void accept(std::vector& array) //Accepts data to a vector
{
int c;
for(c = 0; c < 10; c++)
cin>>arr[c];
a.assign (arr,arr+10); //Assign array data to the vector
}
template
void display(std::vector& array) //Display the vector contents
{
for (std::vector::iterator it = array.begin(); it != array.end(); ++it)
std::cout << \' \' << *it;
}
template
void selection(std::vector& arr) //Selection soring operation
{
int mini, loc, temp, x, y;
mini = arr[0];
for(x = 0; x <= arr.size()-1; x++)
{
mini = arr[x]; //x position value of array is considered as minimum value
loc = x; //Stores the location of the minimum value
for(y = x + 1; y <= arr.size()-1; y++)
{
if(arr[y] < mini) //Checks the already minimum value with the array contents
{
mini = arr[y]; //Stores the new minimum value
loc = y; //Stores the location of the minimum value
}
}
if(loc != x) //If it is not the same location
{
temp = arr[x];
arr[x] = arr[loc];
arr[loc] = temp;
}
}
}
template
void bubble(std::vector &ar) //Bubble sort operation
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < ar.size()-1; i++)
{
if (ar[i]>ar[i+1] )
{
ar[i] += ar[i+1];
ar[i+1] = ar[i] - ar[i+1];
ar[i] -=ar[i+1];
swapp = true;
}
}
}
}
int main()
{
char ch;
do
{
cout<<\"\ MENU\";
cout<<\"\ a Fill the array with user input\";
cout<<\"\ b Display the array\";
cout<<\"\ c Suffel the array element randomly\";
cout<<\"\ d Sort the array using bubble sort\";
cout<<\"\ e Sort the array using Selection Sort\";
cout<<\"\ f Exit Program\";
cout<<\"\ Enter your choice: \";
cin>>ch;
switch(ch)
{
case \'a\':
case \'A\':
accept(a);
cout<<\"\ Accept data operation completed \ \";
break;
case \'b\':
case \'B\':
display(a);
cout<<\"\ Display data operation completed \ \";
break;
case \'c\':
case \'C\':
bogosort(a);
bool b = is_sorted(a);
if(b == true)
display(a);
cout<<\"\ Bugg Sorting operation completed \ \";
break;
case \'d\':
case \'D\':
bubble(a);
display(a);
cout<<\"\ Bubble Sort operation completed \ \";
break;
case \'e\':
case \'E\':
selection(a);
display(a);
cout<<\"\ Selection Sort operation completed \ \";
break;
case \'f\':
case \'F\':
exit(0);
default:
cout<<\"\ Wrong Choice\";
}
}while(1); //Loop will continue infinitely till F or f is pressed
}
Output
MENU
a Fill the array with user input
b Display the array
c Suffel the array element randomly
d Sort the array using bubble sort
e Sort the array using Selection Sort
f Exit Program
Enter your choice: a
10
5
4
78
9
65
3
1
45
66
Accept data operation completed
MENU
a Fill th.
Similar to Resultbest_fit_for_X1 =DistName tlocationscaleNLogL 2.1.pdf (20)
When two data sets are pooled together the pooled mean will alway.pdfaparnatiwari291
When two data sets are pooled together the pooled mean will always be more accurate, between
original mean values and more precise.
Ans: (e)
Solution
When two data sets are pooled together the pooled mean will always be more accurate, between
original mean values and more precise.
Ans: (e).
DELTOID flexes and medially rotates arm; prime mover of arm abduct.pdfaparnatiwari291
DELTOID : flexes and medially rotates arm; prime mover of arm abduction; extends and
laterally rotates arm. LATISSIMUS DORI : prime mover of arm extension; adducts and medially
rotates arm (big muscle). PECTORALIS MAJOR : prime mover of arm flexion, adducts and
medially rotates arm ( big muscle). TERES MAJOR : Extends, adducts and medially rotates arm.
Solution
DELTOID : flexes and medially rotates arm; prime mover of arm abduction; extends and
laterally rotates arm. LATISSIMUS DORI : prime mover of arm extension; adducts and medially
rotates arm (big muscle). PECTORALIS MAJOR : prime mover of arm flexion, adducts and
medially rotates arm ( big muscle). TERES MAJOR : Extends, adducts and medially rotates arm..
We know that Molarity = No . of moles Volume of.pdfaparnatiwari291
We know that Molarity = No . of moles / Volume of solution in L 0.5 M = n / 1.0 L
---> n = 0.5 mol Li2SO4 ---> 2Li+ + SO4 2- So 1 mole of Li2SO4 produces 1 mole of SO4 2- &
2 moles of Li+ So No . of moles of SO4 2- ions present in 0.5 mol of Li2SO4 is 1 * 0.5 = 0.5
mol
Solution
We know that Molarity = No . of moles / Volume of solution in L 0.5 M = n / 1.0 L
---> n = 0.5 mol Li2SO4 ---> 2Li+ + SO4 2- So 1 mole of Li2SO4 produces 1 mole of SO4 2- &
2 moles of Li+ So No . of moles of SO4 2- ions present in 0.5 mol of Li2SO4 is 1 * 0.5 = 0.5
mol.
The false statement is Oxygen forms binary compou.pdfaparnatiwari291
The false statement is Oxygen forms binary compounds with nonmetals called acid
anhydrides.
Solution
The false statement is Oxygen forms binary compounds with nonmetals called acid
anhydrides..
The document states that the concentration is 0.1550. It then repeats that the concentration is 0.1550. The key information is that the concentration is 0.1550.
The area is how many Hydrogens are on the graph. .pdfaparnatiwari291
The area is how many Hydrogens are on the graph. You would need a correlation
table to determine what groups are on the figure. First, calculate the degrees of saturation. (18-
10)/2 = 4 degrees this could be a ring wth 3 pi bonds maybe benxene
Solution
The area is how many Hydrogens are on the graph. You would need a correlation
table to determine what groups are on the figure. First, calculate the degrees of saturation. (18-
10)/2 = 4 degrees this could be a ring wth 3 pi bonds maybe benxene.
This very short document appears to be discussing chemical bonds, mentioning oxygen and a double bond. It provides a solution related to the chemical structure of oxygen double bonded to oxygen but does not give any further details. The document is too brief to extract much meaningful information in a summary.
Once HCl is added in solution, the ions would dis.pdfaparnatiwari291
Once HCl is added in solution, the ions would dissociate into their component parts
(H+ and Cl-). As per the second equation, adding more H+ would initially increase the quantity
of products, thusly shifting the reaction towards the reactants by LeChatlier\'s Principle. If
NaOH was added, the dissociation would create OH- anions that would soak up H+ cations. By
removing products, the equlibrium is shifted towards the products by LeChatlier\'s Principle.
Best of wishes! (:
Solution
Once HCl is added in solution, the ions would dissociate into their component parts
(H+ and Cl-). As per the second equation, adding more H+ would initially increase the quantity
of products, thusly shifting the reaction towards the reactants by LeChatlier\'s Principle. If
NaOH was added, the dissociation would create OH- anions that would soak up H+ cations. By
removing products, the equlibrium is shifted towards the products by LeChatlier\'s Principle.
Best of wishes! (:.
H and F are identical, you just need to rotate H .pdfaparnatiwari291
H and F are identical, you just need to rotate H until it matches F, I is also identical
to G. H and F are enantiomers of I and G, this also means that they are Chiral (non super
imposable on their mirror image) to each other.
Solution
H and F are identical, you just need to rotate H until it matches F, I is also identical
to G. H and F are enantiomers of I and G, this also means that they are Chiral (non super
imposable on their mirror image) to each other..
From weakest to strongest A, B, C Butanal is an .pdfaparnatiwari291
From weakest to strongest: A, B, C Butanal is an aldehyde which means it has the
C=O so it cannot hydrogen bond, only dipole-dipole interactions. However, butanol can
hydrogen-bond because of the OH group so it would have the strongest intermolecular force.
Pentane would have weakest because it has no electronegative atoms.
Solution
From weakest to strongest: A, B, C Butanal is an aldehyde which means it has the
C=O so it cannot hydrogen bond, only dipole-dipole interactions. However, butanol can
hydrogen-bond because of the OH group so it would have the strongest intermolecular force.
Pentane would have weakest because it has no electronegative atoms..
Benzoin and methanol both have an alcohol group, .pdfaparnatiwari291
Benzoin and methanol both have an alcohol group, but benzoin has a ketone group
and phenyl groups within it also. The interesting part about benzoin is that it is a conjugated pi
system, meaning that electrons from the phenyl groups can shift around the double bonds
throughout the whole molecule without effecting anything; this also impacts the ketone group.
This is also known as resonance, you can see an example here
http://alevelchem.com/drop/peptide_angles.gif Because of this effect, the whole rest of the
benzoin moiety (besides the alcohol group) can be considered one giant add-on (Let\'s call it R)
If methanol looks like this... H3C-OH Then our benzoin because of its delocalized resonant
electrons will, in comparison, just look like... R-OH When placed side by side this is how both
molecules will act with each other. Therefore the polarities of both molecules are similar because
electronically both molecules function the same way (Methanol with a CH3, and Benzoin with a
conjugated R group).
Solution
Benzoin and methanol both have an alcohol group, but benzoin has a ketone group
and phenyl groups within it also. The interesting part about benzoin is that it is a conjugated pi
system, meaning that electrons from the phenyl groups can shift around the double bonds
throughout the whole molecule without effecting anything; this also impacts the ketone group.
This is also known as resonance, you can see an example here
http://alevelchem.com/drop/peptide_angles.gif Because of this effect, the whole rest of the
benzoin moiety (besides the alcohol group) can be considered one giant add-on (Let\'s call it R)
If methanol looks like this... H3C-OH Then our benzoin because of its delocalized resonant
electrons will, in comparison, just look like... R-OH When placed side by side this is how both
molecules will act with each other. Therefore the polarities of both molecules are similar because
electronically both molecules function the same way (Methanol with a CH3, and Benzoin with a
conjugated R group)..
When acid and base react together they form salt and water.This reac.pdfaparnatiwari291
When acid and base react together they form salt and water.This reaction is known as
Neutralization Reaction. ForExample
HCl+NaOH ---------> NaCl + H2O
HCl is acid while NaOH is a base, when they react with eachother they form NaCl, that is a salt
(table salt)
These reactions are also reversible reactions.
Solution
When acid and base react together they form salt and water.This reaction is known as
Neutralization Reaction. ForExample
HCl+NaOH ---------> NaCl + H2O
HCl is acid while NaOH is a base, when they react with eachother they form NaCl, that is a salt
(table salt)
These reactions are also reversible reactions..
There are 37 classes in java.lang package as per Java SE7 The java.pdfaparnatiwari291
There are 37 classes in java.lang package as per Java SE7
The java.lang package contains classes that are fundamental to the design of the Java language.
1) Object, Class, ClassLoader, System and Compiler classes
2) Wrapper classes:- Boolean, Character, Byte, Short, Integer, Long, Float, and Double
3) Math, StrictMath classes
4) String, StringBuffer and StringBuilder classes
5) Process, ProcessBuilder, Runtime, RuntimePermission classes
6) Enum>, Throwable, Void classes
----------------------------------------------
1) Object, Class, ClassLoader, System and Compiler classes
----------------------------------------------
Object: The Object class is the root of the class hierarchy. Every class has Object as a
superclass. All objects, including arrays, implement the methods of this class.
Class: The Class class instance represent classes and interfaces in a running Java application.It
has no public constructor.
ClassLoader: The ClassLoader class is an object that is responsible for loading classes. This class
is an abstract class. It may be used by security managers to indicate security domains.
System: The System class contains several useful class fields and methods. It cannot be
instantiated.
Some of the facilities provided by System class are standard input, output, error output streams
and access to externally defined properties and environment variables. This class has a utility
method for quickly copying a portion of an array. Also it has methods for loading files and
libraries
Compiler: The Compiler class is provided to support Java-to-native-code compilers and related
services. By design, it serves as a placeholder for a JIT compiler implementation.
SecurityManager: The SecurityManager class allows applications to implement a security policy.
It allows an application to determine, before performing a possibly unsafe or sensitive operation,
what the operation is and whether it is being attempted in a security context that allows the
operation to be performed. The application can allow or disallow the operation.
----------------------------------------------
2) Wrapper classes:- Boolean, Character, Byte, Short, Integer, Long, Float, and Double
----------------------------------------------
Frequently it is necessary to represent a value of primitive type as if it were an object. The
wrapper classes serve this purpose.
An object of type Double, for example, contains a field whose type is double, representing that
value in such a way that a reference to it can be stored in a variable of reference type. These
classes also provide a number of methods for converting among primitive values, as well as
supporting such standard methods as equals and hashCode.
Other classes in support to wrapper classes:
----------------------------------------------
Number: The Number class is the superclass of classes BigDecimal, BigInteger, Byte, Double,
Float, Integer, Long, and Short.The Subclasses of Number must provide methods to convert the
represented num.
The solution is as belowEmployeeDemo.javaimport java.util.Scann.pdfaparnatiwari291
The solution provides code for an employee payroll program. It includes classes for Employee, Company, and EmployeeDemo (the main class). EmployeeDemo gets input for multiple employees and uses the Employee class to calculate payroll values like taxes, wages, deductions. It then passes the data to the Company class which collects overall payroll statistics.
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...PECB
Denis is a dynamic and results-driven Chief Information Officer (CIO) with a distinguished career spanning information systems analysis and technical project management. With a proven track record of spearheading the design and delivery of cutting-edge Information Management solutions, he has consistently elevated business operations, streamlined reporting functions, and maximized process efficiency.
Certified as an ISO/IEC 27001: Information Security Management Systems (ISMS) Lead Implementer, Data Protection Officer, and Cyber Risks Analyst, Denis brings a heightened focus on data security, privacy, and cyber resilience to every endeavor.
His expertise extends across a diverse spectrum of reporting, database, and web development applications, underpinned by an exceptional grasp of data storage and virtualization technologies. His proficiency in application testing, database administration, and data cleansing ensures seamless execution of complex projects.
What sets Denis apart is his comprehensive understanding of Business and Systems Analysis technologies, honed through involvement in all phases of the Software Development Lifecycle (SDLC). From meticulous requirements gathering to precise analysis, innovative design, rigorous development, thorough testing, and successful implementation, he has consistently delivered exceptional results.
Throughout his career, he has taken on multifaceted roles, from leading technical project management teams to owning solutions that drive operational excellence. His conscientious and proactive approach is unwavering, whether he is working independently or collaboratively within a team. His ability to connect with colleagues on a personal level underscores his commitment to fostering a harmonious and productive workplace environment.
Date: May 29, 2024
Tags: Information Security, ISO/IEC 27001, ISO/IEC 42001, Artificial Intelligence, GDPR
-------------------------------------------------------------------------------
Find out more about ISO training and certification services
Training: ISO/IEC 27001 Information Security Management System - EN | PECB
ISO/IEC 42001 Artificial Intelligence Management System - EN | PECB
General Data Protection Regulation (GDPR) - Training Courses - EN | PECB
Webinars: https://pecb.com/webinars
Article: https://pecb.com/article
-------------------------------------------------------------------------------
For more information about PECB:
Website: https://pecb.com/
LinkedIn: https://www.linkedin.com/company/pecb/
Facebook: https://www.facebook.com/PECBInternational/
Slideshare: http://www.slideshare.net/PECBCERTIFICATION
Executive Directors Chat Leveraging AI for Diversity, Equity, and InclusionTechSoup
Let’s explore the intersection of technology and equity in the final session of our DEI series. Discover how AI tools, like ChatGPT, can be used to support and enhance your nonprofit's DEI initiatives. Participants will gain insights into practical AI applications and get tips for leveraging technology to advance their DEI goals.
How to Manage Your Lost Opportunities in Odoo 17 CRMCeline George
Odoo 17 CRM allows us to track why we lose sales opportunities with "Lost Reasons." This helps analyze our sales process and identify areas for improvement. Here's how to configure lost reasons in Odoo 17 CRM
বাংলাদেশের অর্থনৈতিক সমীক্ষা ২০২৪ [Bangladesh Economic Review 2024 Bangla.pdf] কম্পিউটার , ট্যাব ও স্মার্ট ফোন ভার্সন সহ সম্পূর্ণ বাংলা ই-বুক বা pdf বই " সুচিপত্র ...বুকমার্ক মেনু 🔖 ও হাইপার লিংক মেনু 📝👆 যুক্ত ..
আমাদের সবার জন্য খুব খুব গুরুত্বপূর্ণ একটি বই ..বিসিএস, ব্যাংক, ইউনিভার্সিটি ভর্তি ও যে কোন প্রতিযোগিতা মূলক পরীক্ষার জন্য এর খুব ইম্পরট্যান্ট একটি বিষয় ...তাছাড়া বাংলাদেশের সাম্প্রতিক যে কোন ডাটা বা তথ্য এই বইতে পাবেন ...
তাই একজন নাগরিক হিসাবে এই তথ্য গুলো আপনার জানা প্রয়োজন ...।
বিসিএস ও ব্যাংক এর লিখিত পরীক্ষা ...+এছাড়া মাধ্যমিক ও উচ্চমাধ্যমিকের স্টুডেন্টদের জন্য অনেক কাজে আসবে ...
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
A review of the growth of the Israel Genealogy Research Association Database Collection for the last 12 months. Our collection is now passed the 3 million mark and still growing. See which archives have contributed the most. See the different types of records we have, and which years have had records added. You can also see what we have for the future.
Strategies for Effective Upskilling is a presentation by Chinwendu Peace in a Your Skill Boost Masterclass organisation by the Excellence Foundation for South Sudan on 08th and 09th June 2024 from 1 PM to 3 PM on each day.
2. Code:
function main
load X.mat
[D PD]=allfitdist(X1,'NLogL');
[D2 PD2]=allfitdist(X2,'NLogL');
%best fit using maximum likelihood
best_fit_for_X1=D(1)
best_fit_for_X2=D2(1)
correlation_between_X1_X2=correlation(X1,X2)
Y=X1+X2;
Z=2*X1+X2;
meanY=mean(Y)
varY=var(Y)
meanZ=mean(Z)
varZ=var(Z)
correlation_between_Y_Z=correlation(Y,Z)
end
function[r]=correlation(x,y)
avx = mean(x); ex2 = sum((x - avx).^2); %Wasteful multiple passes are a pain,
avy = mean(y); ey2 = sum((y - avy).^2); %But explicit loops
exy = sum((x - avx).*(y - avy)); %Are interpreted slowly.
r = exy/sqrt(ex2*ey2); %Division by N cancels; ignoring the N - 1 ritual.
end
function [D PD] = allfitdist(data,sortby,varargin)
%ALLFITDIST Fit all valid parametric probability distributions to data.
% [D PD] = ALLFITDIST(DATA) fits all valid parametric probability
% distributions to the data in vector DATA, and returns a struct D of
% fitted distributions and parameters and a struct of objects PD
% representing the fitted distributions. PD is an object in a class
% derived from the ProbDist class.
%
3. % [...] = ALLFITDIST(DATA,SORTBY) returns the struct of valid distributions
% sorted by the parameter SORTBY
% NLogL - Negative of the log likelihood
% BIC - Bayesian information criterion (default)
% AIC - Akaike information criterion
% AICc - AIC with a correction for finite sample sizes
%
% [...] = ALLFITDIST(...,'DISCRETE') specifies it is a discrete
% distribution and does not attempt to fit a continuous distribution
% to the data
%
% [...] = ALLFITDIST(...,'PDF') or (...,'CDF') plots either the PDF or CDF
% of a subset of the fitted distribution. The distributions are plotted in
% order of fit, according to SORTBY.
%
% List of distributions it will try to fit
% Continuous (default)
% Beta
% Birnbaum-Saunders
% Exponential
% Extreme value
% Gamma
% Generalized extreme value
% Generalized Pareto
% Inverse Gaussian
% Logistic
% Log-logistic
% Lognormal
% Nakagami
% Normal
% Rayleigh
% Rician
% t location-scale
% Weibull
%
% Discrete ('DISCRETE')
4. % Binomial
% Negative binomial
% Poisson
%
% Optional inputs:
% [...] = ALLFITDIST(...,'n',N,...)
% For the 'binomial' distribution only:
% 'n' A positive integer specifying the N parameter (number
% of trials). Not allowed for other distributions. If
% 'n' is not given it is estimate by Method of Moments.
% If the estimated 'n' is negative then the maximum
% value of data will be used as the estimated value.
% [...] = ALLFITDIST(...,'theta',THETA,...)
% For the 'generalized pareto' distribution only:
% 'theta' The value of the THETA (threshold) parameter for
% the generalized Pareto distribution. Not allowed for
% other distributions. If 'theta' is not given it is
% estimated by the minimum value of the data.
%
% Note: ALLFITDIST does not handle nonparametric kernel-smoothing,
% use FITDIST directly instead.
%
%
% EXAMPLE 1
% Given random data from an unknown continuous distribution, find the
% best distribution which fits that data, and plot the PDFs to compare
% graphically.
% data = normrnd(5,3,1e4,1); %Assumed from unknown distribution
% [D PD] = allfitdist(data,'PDF'); %Compute and plot results
% D(1) %Show output from best fit
%
% EXAMPLE 2
% Given random data from a discrete unknown distribution, with frequency
% data, find the best discrete distribution which would fit that data,
% sorted by 'NLogL', and plot the PDFs to compare graphically.
% data = nbinrnd(20,.3,1e4,1);
5. % values=unique(data); freq=histc(data,values);
% [D PD] = allfitdist(values,'NLogL','frequency',freq,'PDF','DISCRETE');
% PD{1}
%
% EXAMPLE 3
% Although the Geometric Distribution is not listed, it is a special
% case of fitting the more general Negative Binomial Distribution. The
% parameter 'r' should be close to 1. Show by example.
% data=geornd(.7,1e4,1); %Random from Geometric
% [D PD]= allfitdist(data,'PDF','DISCRETE');
% PD{1}
%
% EXAMPLE 4
% Compare the resulting distributions under two different assumptions
% of discrete data. The first, that it is known to be derived from a
% Binomial Distribution with known 'n'. The second, that it may be
% Binomial but 'n' is unknown and should be estimated. Note the second
% scenario may not yield a Binomial Distribution as the best fit, if
% 'n' is estimated incorrectly. (Best to run example a couple times
% to see effect)
% data = binornd(10,.3,1e2,1);
% [D1 PD1] = allfitdist(data,'n',10,'DISCRETE','PDF'); %Force binomial
% [D2 PD2] = allfitdist(data,'DISCRETE','PDF'); %May be binomial
% PD1{1}, PD2{1} %Compare distributions
%
% Mike Sheppard
% Last Modified: 17-Feb-2012
6. %% Check Inputs
if nargin == 0
data = 10.^((normrnd(2,10,1e4,1))/10);
sortby='BIC';
varargin={'CDF'};
end
if nargin==1
sortby='BIC';
end
sortbyname={'NLogL','BIC','AIC','AICc'};
if ~any(ismember(lower(sortby),lower(sortbyname)))
oldvar=sortby; %May be 'PDF' or 'CDF' or other commands
if isempty(varargin)
varargin={oldvar};
else
varargin=[oldvar varargin];
end
sortby='BIC';
end
if nargin < 2, sortby='BIC'; end
distname={'beta', 'birnbaumsaunders', 'exponential', ...
'extreme value', 'gamma', 'generalized extreme value', ...
'generalized pareto', 'inversegaussian', 'logistic', 'loglogistic', ...
'lognormal', 'nakagami', 'normal', ...
'rayleigh', 'rician', 'tlocationscale', 'weibull'};
if ~any(strcmpi(sortby,sortbyname))
error('allfitdist:SortBy','Sorting must be either NLogL, BIC, AIC, or AICc');
end
%Input may be mixed of numeric and strings, find only strings
vin=varargin;
strs=find(cellfun(@(vs)ischar(vs),vin));
vin(strs)=lower(vin(strs));
%Next check to see if 'PDF' or 'CDF' is listed
numplots=sum(ismember(vin(strs),{'pdf' 'cdf'}));
if numplots>=2
7. error('ALLFITDIST:PlotType','Either PDF or CDF must be given');
end
if numplots==1
plotind=true; %plot indicator
indxpdf=ismember(vin(strs),'pdf');
plotpdf=any(indxpdf);
indxcdf=ismember(vin(strs),'cdf');
vin(strs(indxpdf|indxcdf))=[]; %Delete 'PDF' and 'CDF' in vin
else
plotind=false;
end
%Check to see if discrete
strs=find(cellfun(@(vs)ischar(vs),vin));
indxdis=ismember(vin(strs),'discrete');
discind=false;
if any(indxdis)
discind=true;
distname={'binomial', 'negative binomial', 'poisson'};
vin(strs(indxdis))=[]; %Delete 'DISCRETE' in vin
end
strs=find(cellfun(@(vs)ischar(vs),vin));
n=numel(data); %Number of data points
data = data(:);
D=[];
%Check for NaN's to delete
deldatanan=isnan(data);
%Check to see if frequency is given
indxf=ismember(vin(strs),'frequency');
if any(indxf)
freq=vin{1+strs((indxf))}; freq=freq(:);
if numel(freq)~=numel(data)
error('ALLFITDIST:PlotType','Matrix dimensions must agree');
end
delfnan=isnan(freq);
data(deldatanan|delfnan)=[]; freq(deldatanan|delfnan)=[];
%Save back into vin
8. vin{1+strs((indxf))}=freq;
else
data(deldatanan)=[];
end
%% Run through all distributions in FITDIST function
warning('off','all'); %Turn off all future warnings
for indx=1:length(distname)
try
dname=distname{indx};
switch dname
case 'binomial'
PD=fitbinocase(data,vin,strs); %Special case
case 'generalized pareto'
PD=fitgpcase(data,vin,strs); %Special case
otherwise
%Built-in distribution using FITDIST
PD = fitdist(data,dname,vin{:});
end
NLL=PD.NLogL; % -Log(L)
%If NLL is non-finite number, produce error to ignore distribution
if ~isfinite(NLL)
error('non-finite NLL');
end
num=length(D)+1;
PDs(num) = {PD}; %#ok<*AGROW>
9. k=numel(PD.Params); %Number of parameters
D(num).DistName=PD.DistName;
D(num).NLogL=NLL;
D(num).BIC=-2*(-NLL)+k*log(n);
D(num).AIC=-2*(-NLL)+2*k;
D(num).AICc=(D(num).AIC)+((2*k*(k+1))/(n-k-1));
D(num).ParamNames=PD.ParamNames;
D(num).ParamDescription=PD.ParamDescription;
D(num).Params=PD.Params;
D(num).Paramci=PD.paramci;
D(num).ParamCov=PD.ParamCov;
D(num).Support=PD.Support;
catch err %#ok
%Ignore distribution
end
end
warning('on','all'); %Turn back on warnings
if numel(D)==0
error('ALLFITDIST:NoDist','No distributions were found');
end
%% Sort distributions
indx1=1:length(D); %Identity Map
sortbyindx=find(strcmpi(sortby,sortbyname));
switch sortbyindx
case 1
[~,indx1]=sort([D.NLogL]);
11. function PD=fitbinocase(data,vin,strs)
%% Special Case for Binomial
% 'n' is estimated if not given
vinbino=vin;
%Check to see if 'n' is given
indxn=any(ismember(vin(strs),'n'));
%Check to see if 'frequency' is given
indxfreq=ismember(vin(strs),'frequency');
if ~indxn
%Use Method of Moment estimator
%E[x]=np, V[x]=np(1-p) -> nhat=E/(1-(V/E));
if isempty(indxfreq)||~any(indxfreq)
%Raw data
mnx=mean(data);
nhat=round(mnx/(1-(var(data)/mnx)));
else
%Frequency data
freq=vin{1+strs(indxfreq)};
m1=dot(data,freq)/sum(freq);
m2=dot(data.^2,freq)/sum(freq);
mnx=m1; vx=m2-(m1^2);
nhat=round(mnx/(1-(vx/mnx)));
end
%If nhat is negative, use maximum value of data
if nhat<=0, nhat=max(data(:)); end
vinbino{end+1}='n'; vinbino{end+1}=nhat;
end
PD = fitdist(data,'binomial',vinbino{:});
end
12. function PD=fitgpcase(data,vin,strs)
%% Special Case for Generalized Pareto
% 'theta' is estimated if not given
vingp=vin;
%Check to see if 'theta' is given
indxtheta=any(ismember(vin(strs),'theta'));
if ~indxtheta
%Use minimum value for theta, minus small part
thetahat=min(data(:))-10*eps;
vingp{end+1}='theta'; vingp{end+1}=thetahat;
end
PD = fitdist(data,'generalized pareto',vingp{:});
end
function plotfigs(data,D,PD,vin,strs,plotpdf,discind)
%Plot functionality for continuous case due to Jonathan Sullivan
%Modified by author for discrete case
%Maximum number of distributions to include
%max_num_dist=Inf; %All valid distributions
max_num_dist=4;
13. %Check to see if frequency is given
indxf=ismember(vin(strs),'frequency');
if any(indxf)
freq=vin{1+strs((indxf))};
end
figure
%% Probability Density / Mass Plot
if plotpdf
if ~discind
%Continuous Data
nbins = max(min(length(data)./10,100),50);
xi = linspace(min(data),max(data),nbins);
dx = mean(diff(xi));
xi2 = linspace(min(data),max(data),nbins*10)';
fi = histc(data,xi-dx);
fi = fi./sum(fi)./dx;
inds = 1:min([max_num_dist,numel(PD)]);
ys = cellfun(@(PD) pdf(PD,xi2),PD(inds),'UniformOutput',0);
ys = cat(2,ys{:});
bar(xi,fi,'FaceColor',[160 188 254]/255,'EdgeColor','k');
hold on;
plot(xi2,ys,'LineWidth',1.5)
legend(['empirical',{D(inds).DistName}],'Location','NE')
xlabel('Value');
ylabel('Probability Density');
title('Probability Density Function');
grid on
else
%Discrete Data
xi2=min(data):max(data);
14. %xi2=unique(x)'; %If only want observed x-values to be shown
indxf=ismember(vin(strs),'frequency');
if any(indxf)
fi=zeros(size(xi2));
fi((ismember(xi2,data)))=freq; fi=fi'./sum(fi);
else
fi=histc(data,xi2); fi=fi./sum(fi);
end
inds = 1:min([max_num_dist,numel(PD)]);
ys = cellfun(@(PD) pdf(PD,xi2),PD(inds),'UniformOutput',0);
ys=cat(1,ys{:})';
bar(xi2,[fi ys]);
legend(['empirical',{D(inds).DistName}],'Location','NE')
xlabel('Value');
ylabel('Probability Mass');
title('Probability Mass Function');
grid on
end
else
%Cumulative Distribution
if ~discind
%Continuous Data
[fi xi] = ecdf(data);
inds = 1:min([max_num_dist,numel(PD)]);
ys = cellfun(@(PD) cdf(PD,xi),PD(inds),'UniformOutput',0);
ys = cat(2,ys{:});
if max(xi)/min(xi) > 1e4; lgx = true; else lgx = false; end
subplot(2,1,1)
if lgx
semilogx(xi,fi,'k',xi,ys)
else
plot(xi,fi,'k',xi,ys)
end
legend(['empirical',{D(inds).DistName}],'Location','NE')
xlabel('Value');
ylabel('Cumulative Probability');
15. title('Cumulative Distribution Function');
grid on
subplot(2,1,2)
y = 1.1*bsxfun(@minus,ys,fi);
if lgx
semilogx(xi,bsxfun(@minus,ys,fi))
else
plot(xi,bsxfun(@minus,ys,fi))
end
ybnds = max(abs(y(:)));
ax = axis;
axis([ax(1:2) -ybnds ybnds]);
legend({D(inds).DistName},'Location','NE')
xlabel('Value');
ylabel('Error');
title('CDF Error');
grid on
else
%Discrete Data
indxf=ismember(vin(strs),'frequency');
if any(indxf)
[fi xi] = ecdf(data,'frequency',freq);
else
[fi xi] = ecdf(data);
end
%Check unique xi, combine fi
[xi,ign,indx]=unique(xi); %#ok
fi=accumarray(indx,fi);
inds = 1:min([max_num_dist,numel(PD)]);
ys = cellfun(@(PD) cdf(PD,xi),PD(inds),'UniformOutput',0);
ys=cat(2,ys{:});
subplot(2,1,1)
stairs(xi,[fi ys]);
legend(['empirical',{D(inds).DistName}],'Location','NE')
xlabel('Value');
ylabel('Cumulative Probability');
16. title('Cumulative Distribution Function');
grid on
subplot(2,1,2)
y = 1.1*bsxfun(@minus,ys,fi);
stairs(xi,bsxfun(@minus,ys,fi))
ybnds = max(abs(y(:)));
ax = axis;
axis([ax(1:2) -ybnds ybnds]);
legend({D(inds).DistName},'Location','NE')
xlabel('Value');
ylabel('Error');
title('CDF Error');
grid on
end
end
end
Solution
Result:
best_fit_for_X1 =
DistName: 'tlocationscale'
NLogL: 2.1206e+03
BIC: 4.2620e+03
AIC: 4.2472e+03
AICc: 4.2473e+03
ParamNames: {'mu' 'sigma' 'nu'}
ParamDescription: {'location' 'scale' 'degrees of freedom'}
Params: [1.0071 1.9637 37.4643]
Paramci: [2x3 double]
17. ParamCov: [3x3 double]
Support: [1x1 struct]
best_fit_for_X2 =
DistName: 'generalized extreme value'
NLogL: 2.4968e+03
BIC: 5.0142e+03
AIC: 4.9995e+03
AICc: 4.9995e+03
ParamNames: {'k' 'sigma' 'mu'}
ParamDescription: {'shape' 'scale' 'location'}
Params: [-0.2802 2.9571 1.0858]
Paramci: [2x3 double]
ParamCov: [3x3 double]
Support: [1x1 struct]
correlation_between_X1_X2 = 0.0084 (hence X1 and X2 are independent)
meanY = 3.1394
varY = 12.8269
meanZ = 4.1492
varZ = 25.1576
correlation_between_Y_Z = 0.9438 (Hence Y and Z are dependent)
Code:
function main
load X.mat
[D PD]=allfitdist(X1,'NLogL');
[D2 PD2]=allfitdist(X2,'NLogL');
%best fit using maximum likelihood
best_fit_for_X1=D(1)
best_fit_for_X2=D2(1)
correlation_between_X1_X2=correlation(X1,X2)
Y=X1+X2;
Z=2*X1+X2;
meanY=mean(Y)
18. varY=var(Y)
meanZ=mean(Z)
varZ=var(Z)
correlation_between_Y_Z=correlation(Y,Z)
end
function[r]=correlation(x,y)
avx = mean(x); ex2 = sum((x - avx).^2); %Wasteful multiple passes are a pain,
avy = mean(y); ey2 = sum((y - avy).^2); %But explicit loops
exy = sum((x - avx).*(y - avy)); %Are interpreted slowly.
r = exy/sqrt(ex2*ey2); %Division by N cancels; ignoring the N - 1 ritual.
end
function [D PD] = allfitdist(data,sortby,varargin)
%ALLFITDIST Fit all valid parametric probability distributions to data.
% [D PD] = ALLFITDIST(DATA) fits all valid parametric probability
% distributions to the data in vector DATA, and returns a struct D of
% fitted distributions and parameters and a struct of objects PD
% representing the fitted distributions. PD is an object in a class
% derived from the ProbDist class.
%
% [...] = ALLFITDIST(DATA,SORTBY) returns the struct of valid distributions
% sorted by the parameter SORTBY
% NLogL - Negative of the log likelihood
% BIC - Bayesian information criterion (default)
% AIC - Akaike information criterion
% AICc - AIC with a correction for finite sample sizes
%
% [...] = ALLFITDIST(...,'DISCRETE') specifies it is a discrete
% distribution and does not attempt to fit a continuous distribution
% to the data
%
% [...] = ALLFITDIST(...,'PDF') or (...,'CDF') plots either the PDF or CDF
19. % of a subset of the fitted distribution. The distributions are plotted in
% order of fit, according to SORTBY.
%
% List of distributions it will try to fit
% Continuous (default)
% Beta
% Birnbaum-Saunders
% Exponential
% Extreme value
% Gamma
% Generalized extreme value
% Generalized Pareto
% Inverse Gaussian
% Logistic
% Log-logistic
% Lognormal
% Nakagami
% Normal
% Rayleigh
% Rician
% t location-scale
% Weibull
%
% Discrete ('DISCRETE')
% Binomial
% Negative binomial
% Poisson
%
% Optional inputs:
% [...] = ALLFITDIST(...,'n',N,...)
% For the 'binomial' distribution only:
% 'n' A positive integer specifying the N parameter (number
% of trials). Not allowed for other distributions. If
% 'n' is not given it is estimate by Method of Moments.
% If the estimated 'n' is negative then the maximum
% value of data will be used as the estimated value.
20. % [...] = ALLFITDIST(...,'theta',THETA,...)
% For the 'generalized pareto' distribution only:
% 'theta' The value of the THETA (threshold) parameter for
% the generalized Pareto distribution. Not allowed for
% other distributions. If 'theta' is not given it is
% estimated by the minimum value of the data.
%
% Note: ALLFITDIST does not handle nonparametric kernel-smoothing,
% use FITDIST directly instead.
%
%
% EXAMPLE 1
% Given random data from an unknown continuous distribution, find the
% best distribution which fits that data, and plot the PDFs to compare
% graphically.
% data = normrnd(5,3,1e4,1); %Assumed from unknown distribution
% [D PD] = allfitdist(data,'PDF'); %Compute and plot results
% D(1) %Show output from best fit
%
% EXAMPLE 2
% Given random data from a discrete unknown distribution, with frequency
% data, find the best discrete distribution which would fit that data,
% sorted by 'NLogL', and plot the PDFs to compare graphically.
% data = nbinrnd(20,.3,1e4,1);
% values=unique(data); freq=histc(data,values);
% [D PD] = allfitdist(values,'NLogL','frequency',freq,'PDF','DISCRETE');
% PD{1}
%
% EXAMPLE 3
% Although the Geometric Distribution is not listed, it is a special
% case of fitting the more general Negative Binomial Distribution. The
% parameter 'r' should be close to 1. Show by example.
% data=geornd(.7,1e4,1); %Random from Geometric
% [D PD]= allfitdist(data,'PDF','DISCRETE');
% PD{1}
%
21. % EXAMPLE 4
% Compare the resulting distributions under two different assumptions
% of discrete data. The first, that it is known to be derived from a
% Binomial Distribution with known 'n'. The second, that it may be
% Binomial but 'n' is unknown and should be estimated. Note the second
% scenario may not yield a Binomial Distribution as the best fit, if
% 'n' is estimated incorrectly. (Best to run example a couple times
% to see effect)
% data = binornd(10,.3,1e2,1);
% [D1 PD1] = allfitdist(data,'n',10,'DISCRETE','PDF'); %Force binomial
% [D2 PD2] = allfitdist(data,'DISCRETE','PDF'); %May be binomial
% PD1{1}, PD2{1} %Compare distributions
%
% Mike Sheppard
% Last Modified: 17-Feb-2012
%% Check Inputs
if nargin == 0
data = 10.^((normrnd(2,10,1e4,1))/10);
sortby='BIC';
varargin={'CDF'};
end
if nargin==1
sortby='BIC';
end
sortbyname={'NLogL','BIC','AIC','AICc'};
if ~any(ismember(lower(sortby),lower(sortbyname)))
22. oldvar=sortby; %May be 'PDF' or 'CDF' or other commands
if isempty(varargin)
varargin={oldvar};
else
varargin=[oldvar varargin];
end
sortby='BIC';
end
if nargin < 2, sortby='BIC'; end
distname={'beta', 'birnbaumsaunders', 'exponential', ...
'extreme value', 'gamma', 'generalized extreme value', ...
'generalized pareto', 'inversegaussian', 'logistic', 'loglogistic', ...
'lognormal', 'nakagami', 'normal', ...
'rayleigh', 'rician', 'tlocationscale', 'weibull'};
if ~any(strcmpi(sortby,sortbyname))
error('allfitdist:SortBy','Sorting must be either NLogL, BIC, AIC, or AICc');
end
%Input may be mixed of numeric and strings, find only strings
vin=varargin;
strs=find(cellfun(@(vs)ischar(vs),vin));
vin(strs)=lower(vin(strs));
%Next check to see if 'PDF' or 'CDF' is listed
numplots=sum(ismember(vin(strs),{'pdf' 'cdf'}));
if numplots>=2
error('ALLFITDIST:PlotType','Either PDF or CDF must be given');
end
if numplots==1
plotind=true; %plot indicator
indxpdf=ismember(vin(strs),'pdf');
plotpdf=any(indxpdf);
indxcdf=ismember(vin(strs),'cdf');
vin(strs(indxpdf|indxcdf))=[]; %Delete 'PDF' and 'CDF' in vin
else
plotind=false;
end
%Check to see if discrete
23. strs=find(cellfun(@(vs)ischar(vs),vin));
indxdis=ismember(vin(strs),'discrete');
discind=false;
if any(indxdis)
discind=true;
distname={'binomial', 'negative binomial', 'poisson'};
vin(strs(indxdis))=[]; %Delete 'DISCRETE' in vin
end
strs=find(cellfun(@(vs)ischar(vs),vin));
n=numel(data); %Number of data points
data = data(:);
D=[];
%Check for NaN's to delete
deldatanan=isnan(data);
%Check to see if frequency is given
indxf=ismember(vin(strs),'frequency');
if any(indxf)
freq=vin{1+strs((indxf))}; freq=freq(:);
if numel(freq)~=numel(data)
error('ALLFITDIST:PlotType','Matrix dimensions must agree');
end
delfnan=isnan(freq);
data(deldatanan|delfnan)=[]; freq(deldatanan|delfnan)=[];
%Save back into vin
vin{1+strs((indxf))}=freq;
else
data(deldatanan)=[];
end
24. %% Run through all distributions in FITDIST function
warning('off','all'); %Turn off all future warnings
for indx=1:length(distname)
try
dname=distname{indx};
switch dname
case 'binomial'
PD=fitbinocase(data,vin,strs); %Special case
case 'generalized pareto'
PD=fitgpcase(data,vin,strs); %Special case
otherwise
%Built-in distribution using FITDIST
PD = fitdist(data,dname,vin{:});
end
NLL=PD.NLogL; % -Log(L)
%If NLL is non-finite number, produce error to ignore distribution
if ~isfinite(NLL)
error('non-finite NLL');
end
num=length(D)+1;
PDs(num) = {PD}; %#ok<*AGROW>
k=numel(PD.Params); %Number of parameters
D(num).DistName=PD.DistName;
D(num).NLogL=NLL;
D(num).BIC=-2*(-NLL)+k*log(n);
D(num).AIC=-2*(-NLL)+2*k;
D(num).AICc=(D(num).AIC)+((2*k*(k+1))/(n-k-1));
D(num).ParamNames=PD.ParamNames;
D(num).ParamDescription=PD.ParamDescription;
D(num).Params=PD.Params;
D(num).Paramci=PD.paramci;
D(num).ParamCov=PD.ParamCov;
D(num).Support=PD.Support;
25. catch err %#ok
%Ignore distribution
end
end
warning('on','all'); %Turn back on warnings
if numel(D)==0
error('ALLFITDIST:NoDist','No distributions were found');
end
%% Sort distributions
indx1=1:length(D); %Identity Map
sortbyindx=find(strcmpi(sortby,sortbyname));
switch sortbyindx
case 1
[~,indx1]=sort([D.NLogL]);
case 2
[~,indx1]=sort([D.BIC]);
case 3
[~,indx1]=sort([D.AIC]);
case 4
[~,indx1]=sort([D.AICc]);
end
%Sort
D=D(indx1); PD = PDs(indx1);
26. %% Plot if requested
if plotind;
plotfigs(data,D,PD,vin,strs,plotpdf,discind)
end
end
function PD=fitbinocase(data,vin,strs)
%% Special Case for Binomial
% 'n' is estimated if not given
vinbino=vin;
%Check to see if 'n' is given
indxn=any(ismember(vin(strs),'n'));
%Check to see if 'frequency' is given
indxfreq=ismember(vin(strs),'frequency');
if ~indxn
%Use Method of Moment estimator
27. %E[x]=np, V[x]=np(1-p) -> nhat=E/(1-(V/E));
if isempty(indxfreq)||~any(indxfreq)
%Raw data
mnx=mean(data);
nhat=round(mnx/(1-(var(data)/mnx)));
else
%Frequency data
freq=vin{1+strs(indxfreq)};
m1=dot(data,freq)/sum(freq);
m2=dot(data.^2,freq)/sum(freq);
mnx=m1; vx=m2-(m1^2);
nhat=round(mnx/(1-(vx/mnx)));
end
%If nhat is negative, use maximum value of data
if nhat<=0, nhat=max(data(:)); end
vinbino{end+1}='n'; vinbino{end+1}=nhat;
end
PD = fitdist(data,'binomial',vinbino{:});
end
function PD=fitgpcase(data,vin,strs)
%% Special Case for Generalized Pareto
% 'theta' is estimated if not given
vingp=vin;
%Check to see if 'theta' is given
indxtheta=any(ismember(vin(strs),'theta'));
if ~indxtheta
28. %Use minimum value for theta, minus small part
thetahat=min(data(:))-10*eps;
vingp{end+1}='theta'; vingp{end+1}=thetahat;
end
PD = fitdist(data,'generalized pareto',vingp{:});
end
function plotfigs(data,D,PD,vin,strs,plotpdf,discind)
%Plot functionality for continuous case due to Jonathan Sullivan
%Modified by author for discrete case
%Maximum number of distributions to include
%max_num_dist=Inf; %All valid distributions
max_num_dist=4;
%Check to see if frequency is given
indxf=ismember(vin(strs),'frequency');
if any(indxf)
freq=vin{1+strs((indxf))};
end
figure
29. %% Probability Density / Mass Plot
if plotpdf
if ~discind
%Continuous Data
nbins = max(min(length(data)./10,100),50);
xi = linspace(min(data),max(data),nbins);
dx = mean(diff(xi));
xi2 = linspace(min(data),max(data),nbins*10)';
fi = histc(data,xi-dx);
fi = fi./sum(fi)./dx;
inds = 1:min([max_num_dist,numel(PD)]);
ys = cellfun(@(PD) pdf(PD,xi2),PD(inds),'UniformOutput',0);
ys = cat(2,ys{:});
bar(xi,fi,'FaceColor',[160 188 254]/255,'EdgeColor','k');
hold on;
plot(xi2,ys,'LineWidth',1.5)
legend(['empirical',{D(inds).DistName}],'Location','NE')
xlabel('Value');
ylabel('Probability Density');
title('Probability Density Function');
grid on
else
%Discrete Data
xi2=min(data):max(data);
%xi2=unique(x)'; %If only want observed x-values to be shown
indxf=ismember(vin(strs),'frequency');
if any(indxf)
fi=zeros(size(xi2));
fi((ismember(xi2,data)))=freq; fi=fi'./sum(fi);
else
fi=histc(data,xi2); fi=fi./sum(fi);
end
inds = 1:min([max_num_dist,numel(PD)]);
ys = cellfun(@(PD) pdf(PD,xi2),PD(inds),'UniformOutput',0);
ys=cat(1,ys{:})';
bar(xi2,[fi ys]);
30. legend(['empirical',{D(inds).DistName}],'Location','NE')
xlabel('Value');
ylabel('Probability Mass');
title('Probability Mass Function');
grid on
end
else
%Cumulative Distribution
if ~discind
%Continuous Data
[fi xi] = ecdf(data);
inds = 1:min([max_num_dist,numel(PD)]);
ys = cellfun(@(PD) cdf(PD,xi),PD(inds),'UniformOutput',0);
ys = cat(2,ys{:});
if max(xi)/min(xi) > 1e4; lgx = true; else lgx = false; end
subplot(2,1,1)
if lgx
semilogx(xi,fi,'k',xi,ys)
else
plot(xi,fi,'k',xi,ys)
end
legend(['empirical',{D(inds).DistName}],'Location','NE')
xlabel('Value');
ylabel('Cumulative Probability');
title('Cumulative Distribution Function');
grid on
subplot(2,1,2)
y = 1.1*bsxfun(@minus,ys,fi);
if lgx
semilogx(xi,bsxfun(@minus,ys,fi))
else
plot(xi,bsxfun(@minus,ys,fi))
end
ybnds = max(abs(y(:)));
ax = axis;
axis([ax(1:2) -ybnds ybnds]);
31. legend({D(inds).DistName},'Location','NE')
xlabel('Value');
ylabel('Error');
title('CDF Error');
grid on
else
%Discrete Data
indxf=ismember(vin(strs),'frequency');
if any(indxf)
[fi xi] = ecdf(data,'frequency',freq);
else
[fi xi] = ecdf(data);
end
%Check unique xi, combine fi
[xi,ign,indx]=unique(xi); %#ok
fi=accumarray(indx,fi);
inds = 1:min([max_num_dist,numel(PD)]);
ys = cellfun(@(PD) cdf(PD,xi),PD(inds),'UniformOutput',0);
ys=cat(2,ys{:});
subplot(2,1,1)
stairs(xi,[fi ys]);
legend(['empirical',{D(inds).DistName}],'Location','NE')
xlabel('Value');
ylabel('Cumulative Probability');
title('Cumulative Distribution Function');
grid on
subplot(2,1,2)
y = 1.1*bsxfun(@minus,ys,fi);
stairs(xi,bsxfun(@minus,ys,fi))
ybnds = max(abs(y(:)));
ax = axis;
axis([ax(1:2) -ybnds ybnds]);
legend({D(inds).DistName},'Location','NE')
xlabel('Value');
ylabel('Error');
title('CDF Error');