Professional Documents
Culture Documents
Lab 1
Introduction to MATLAB
Objective:
To get familiar with data entering, data utilizing and plotting in MATLAB.
Introduction:
MATLAB:
MATLAB is widely used in all areas of applied mathematics, in education and research at
universities, and in the industry. MATLAB stands for MATrix LABoratory and the software
is built up around vectors and matrices. This makes the software particularly useful for linear
algebra but MATLAB is also a great tool for solving algebraic and differential equations and
for numerical integration. MATLAB has powerful graphic tools and can produce nice pictures
in both 2D and 3D. It is also a programming language, and is one of the easiest programming
languages for writing mathematical programs. The MATLAB environment (on most computer
systems) consists of menus, buttons and a writing area similar to an ordinary word
processor. MATLAB is case sensitive. This means that MATLAB knows a difference between
letters written as lower and upper-case letters. For example, MATLAB will understand sin
(2) but will not understand Sin(2).
Command window:
The writing area that you will see when you start MATLAB, is called the command window.
In this window you give the commands to MATLAB. Debugging is usually done in command
window. Command window is called MATLAB interface.
Workspace:
The Workspace browser enables you to view and interactively manage the contents of the
workspace in MATLAB. For each variable or object in the workspace. You can edit the
contents of scalar (1-by-1) variables directly in the Workspace browser. Right-click the
variable and select Edit Value. To edit other variables, double-click the variable name in the
Workspace browser to open it in the Variables editor.
Variables Editor:
The MATLAB Variables editor provides a convenient interface for viewing, modifying, and
plotting dataset arrays.
You can reorder variables in a dataset array using the Variables editor. You can enter new data
values directly into the Variables editor.
Command History window:
The commands you type in the command window are stored by MATLAB and can be viewed
in the Command History window. To repeat a command, you have already used, you can
University of Engineering & Technology, Lahore
Faisalabad Campus Page 1 of 48
Probability & Statistics Session 2018
simply double-click on the command in the history window, or use the <up arrow> at the
command prompt to iterate through the commands you have used until you reach the command
you desire to repeat.
Input command:
Request user input displays the text in prompt and waits for the user to input a value and press
the Return key. It is used for data entering.
Syntax:
x = input(prompt)
Zeros: It creates an array of all zeros.
Syntax:
X = zeros(sz1,...,szN)
Plot:
Plot creates a 2-D line plot of the data in Y versus the corresponding values in X.
Syntax:
plot(X,Y)
Procedure:
I opened MATLAB in my PC and opened a new script.
I created a zero matrix of 10 by 3 equal to a variable “A”. then I used input command in
for loop so that every time I run the program it ask the user to input the values of the matrix.
To call any entry we write the matric name and specified position of any entry i.e,
variable(row,coloum).
To index a row after comma a colon is used and to index column colon is used before
comma.
Task 1: Task 1: To store the data in the form of 10x3 table by entering it manually without
using built-in functions.
MATLAB code:
Fig no 1.1
Task 2: Plot the given four functions for 0≤ x ≤ 64 and step size of 0.5.
1. y = x 1
2. y = x(log𝟐𝒙 ) 2
𝒙 𝟐
3. y = 𝐱(𝐥𝐨𝐠𝟐 ) 3
4. y = 𝒙𝟐 4
Matlab code :
Fig no 1.2
Task 2: Find the out of given functions for x = [1,2,3,4,5] and y = [6,7,8,9,10].
1. ∑𝟓𝒊=𝟏 𝒙𝒊 ∑𝟓𝒊=𝟏 𝒚𝒊 5
2. ∑𝟓𝒊=𝟏 𝒙𝒊 𝒚𝒊 6
3. ∑𝟓𝒊=𝟏 𝒍𝒐𝒈𝟏𝟎 𝒙𝒊 7
4. √∑𝟓𝒊=𝟏 𝟓𝒙𝑖 + 𝒚𝑖 8
5. ∑𝟓𝒊=𝟏|𝟐𝒙𝑖 + 𝟓𝒚𝑖| 9
𝟓
6. 𝒆∑𝒊=𝟏 𝒙𝑖 10
Matlab code:
Fig no 1.4
Fig no 1.5
Fig no 1.6
Conclusion:
MATLAB is helpful in making a matrix of huge no. of numbers.
We can perform any kind of mathematical operation on MATLAB and can see the
output of a function.
MATLAB can used to analyze code and developing algorithms.
We can develop a model on MATLAB and can make its application.
Lab 2
Introduction to Bar graph and pie charts
Objective:
To get familiar with bar graph, and pie charts in MATLAB.
Introduction:
Bar graph:
A bar graph is a graph that represents categorical data with rectangular bars with heights and
lengths proportional to the value that they represent. The bar can be plotted vertically on
horizontally.
Syntax:
bar(y)
bar(x,y)
bar(y) creates a bar graph with one bar for each element in y. If y is a matrix,
then bar groups the bars according to the rows in y.
bar(x,y) draws the bars at the locations specified by x.
Syntax:
barh(y) , barh(x,y)
barh(y) draws one horizontal bar for each element in y. If y is a matrix, barh groups the
bars produced by the elements in each row. The y-axis scale ranges from 1 up
tolength(y) when y is a vector, and 1 to size(y,1), which is the number of rows, when y is
a matrix. The values in y can be numeric or duration values.
barh(x,y) draws a bar for each element in y at locations specified in x, where x is a vector
defining locations along the y-axis. The location values can be nonmonotonic, but cannot
contain duplicate values. If y is a matrix, barh groups the elements of each row in y at
corresponding locations in x. The values in x can be numeric, datetime, duration, or
categorical values.
Pie chart:
A pie chart is a circular statistical graphic which is circular statistical graphic which is divided
into slices to illustrate numerical proportion. In a ppie chart the arc length of each slice is
proportional to the quality is represents.
Syntax:
pie(X) , pie(X,labels)
pie(X,explode,labels)
pie(X) draws a pie chart using the data in X. Each slice of the pie chart represents an
element in X.
pie(X,labels) specifies text labels for the slices. The number of labels must equal the
number of slices. X must be numeric.
pie(X,explode,labels) specifies text labels for the slices. The number of labels must equal
the number of slices.
Syntax:
text (x, y, txt)
text(x,y,txt) adds a text description to one or more data points in the current axes using
the text specified by txt. To add text to one point, specify x and y as scalars in data units.
To add text to multiple points, specify x and y as vectors with equal length.
Procedure:
I opened MATLAB in my PC and opened a new script.
I declared two vectors with variable name “A” and “X”. Then I used bar command to plot
the values in a bar graph.
To display the height of the bars I used text command and passed the label in string form.
Then make it center by horizon and vertical center.
To change the properties of the bar graph can use the dot operator with the same property
syntax appeared in the command window.
To plot the graph in horizontal direction I used barh command.
I plotted the data in the form of group by declaring vector having more than one column.
The I plotted the data in the form of stack by writing stacked in bar command.
We can’t access the data of the bars in stacked form so we can access is by writing the
variable with bar number i.e. y(1).
I used pie command to plot the graph in the form of pie chart.
I used label to display the x axis vales and explode to differentiate it from other data .
Output:
Output:
Output:
4. 3D bar graph:
MATLAB code:
Output:
Output:
1. Pie Chart:
MATLAB code:
Output:
Output:
Conclusion:
MATLAB is helpful in computing data and plotting it.
MATLAB can also be helpful in making pictorial representation of data.
Lab 3
Probability of independent events
Objective:
To find probability of independent events using MATLAB.
Introduction:
Probability:
It is the branch of mathematics that deal with calculating the likelihood of given event
occurrence which is expressed in numbers between zero and one.
Probability model:
Probability model is the mathematical description of an uncertain situation.
2. Probability law:
The probability law, assigns a non-negative number P(A) (called the probability of A) that
encodes or belief about the collective likelihood of elements of A.
Types of events:
There are two types of event.
1. Independent events:
Events that are not affected by previous events/outcomes are called independent events.
2. Dependent events:
Events that are affected by previous events/outcomes are called dependent events.
2. Additivity:
If A and B are two disjoint events, then the probability of their union satisfies:
P (A U B) = P(A) + P(B)
3. Normalization
The probability of entire sample space Ω is equal to 1, that is
P (Ω) = 1
Properties of Probability:
P (φ) = 0
P(𝐴𝐶 ) = 1 - P(A)
P (A U B) = P(A) + P(B) (if A ∩ B = φ)
P (A U B) = P(A) + P(B) – P (A ∩ B ) (if A ∩ B ≠ φ)
Procedure:
I opened MATLAB in my PC and opened a new script.
I declared a matrix of sample space then used sort command for simplicity.
Then I check repetition of numbers in the matrix by using loops.
If the number repeated the value of count increased by one and its probability = count /
number of elements in sample space defined as length(s) in the code.
Then I plotted the probabilities of all numbers in bar graph.
LAB TASKS
Lab task 1:
Prove P (A U B) = P(A) + P(B)- P( AΩ B) and P(A ΩB ) =1
Lab task 2:
To check whether the given event is disjoint or not.
Disjoint events cannot happen at the same time. In other words, they are mutually exclusive.
Put in formal terms, events A and B are disjoint if their intersection is zero: P(A∩B) = 0.
Lab 4
Conditional Probability
Objective:
To implement condition probability using MATLAB.
Introduction:
Conditional Probability:
The conditional probability of an event B is the probability that the event will occur given the
knowledge that an event A has already occurred. This probability is written P(B|A), notation
for the probability of B given A. In the case where events A and B are independent (where
event A has no effect on the probability of event B), the conditional probability of
event B given event A is simply the probability of event B, that is P(B).
If events A and B are not independent, then the probability of the intersection of A and B (the
probability that both events occur) is defined by:
P (A and B) = P (B) * P (A | B).
From this definition, the conditional probability P(B|A) is easily obtained by dividing by P(A):
P (A ∩ B)
P (A / B) =
P (B)
Where we assume that P (B) > 0; the conditional probability is undefined if the conditioning
event has zero probability.
Save command:
Save command saves all variables from the current workspace in a MATLAB formatted binary
file (MAT-file) called filename. If filename exists, save overwrites the file.
Syntax:
save(filename)
Load command:
Load variables from file into workspace
Syntax:
load(filename)
Sum command:
Sum command returns the sum of the elements of A along the first array dimension whose size
does not equal 1.
Syntax:
S = sum(A)
sum(A,1) operates on successive elements in the columns of A and returns a row vector of
the sums of each column.
sum(A,2) operates on successive elements in the rows of A and returns a column vector of
the sums of each row
Male Female
GOT 80 20
West World 100 25
MPTH 50 225
Find the conditional probabilities P(GOT/M), P(GOT/F), P(WestWorld/M), P(WestWorld/F),
P(MPTH/M) and P(MPTH/F)
Matlab code:
Fig no 4.1
Fig no 4.2
Lab task 2:
Find the Conditional probabilities of given weather condition.
Matlab code :
Fig no 4.3
Fig no 4.4
Fig no 4.5
Conclusion:
Become familier with some commands to find conditional probabilities using matlab.
Lab 5
Bayes Theorem
Objective:
To implement Bayes Theorem using MATLAB.
Introduction:
Bayes Theorem:
Bayes' theorem, named after 18th-century British mathematician Thomas Bayes, is a
mathematical formula for determining conditional probability. The theorem provides a way to
revise existing predictions or theories (update probabilities) given new or additional evidence.
In finance, Bayes' theorem can be used to rate the risk of lending money to potential borrowers.
In short Bayes theorem is used to find reverse conditional probability. It is used in data mining
and machine learning.
P(A)∗ P(B|A)
P(A|B) =
P(B)
Prior probability:
It is the probability of an event before new data. Is collected it is the best rational assessment
of probability of an outcome on the current knowledge before an experiment is performed.
Posterior probability:
Posterior probability is the revised probability of an event occurring after taking new
information it can be calculated by updating Prior probability by using Bayes' theorem.
Unique command:
If A is a table or timetable, then unique returns the unique rows in A in sorted order i.e the
command provides Unique values in array.
Syntax:
C = unique(A)
The values (or rows) in C return in the same order as in A. Let B= ([5 5 3 4] C=unique(B,
'stable') returns C = [5 3 4].
Reshape command:
The reshape command given blow reshapes A using the size vector, sz, to define size(B).
Syntax:
B = reshape(A,sz)
For example, reshape(A,[2,3]) reshapes A into a 2-by-3 matrix. sz must contain at least 2
elements, and prod(sz) must be the same as numel(A).
LAB TASKS
Lab Task 1:
Matlab code:
Fig n0 5.1
Fig no 5.2
Fig no 5.3
Lab 06
Objective:
To familiarized with random variables, its types, Probability Mass Function (PMF),
Cumulative Distribution Function (CDF) and its implementation in MATLAB.
Random variables:
The Probability Mass Function (PMF) provides the probability of a particular point in the
sample space of a discrete random variable (R.V). For a countable SX {a0 , a2 , … , an }, the
PMF is the set of probabilities as stated below:
• P1: 0 ≤ 𝑃𝑋 (𝑥) ≤ 1
In probability theory and statistics, the cumulative distribution function (CDF) of a real-valued
random variable X, or just distribution function of X,evaluated at x, is the probability that X
will take a value less than or equal to x. CDF is defined as:
Properties of CDF
1. P1: 0 ≤ 𝐹𝑋 (𝑥) ≤ 1
2. P2: 𝑎 ≤ 𝑏 → 𝐹𝑋 (𝑎) ≤ 𝐹𝑋 (𝑏)
3. P3: lim 𝐹𝑋 (𝑥) = 0
𝑥→−∞
The expected value, expectation or mean of a discrete R.V is the “average” value of the random
variable. Expectation is computed by using the probability of each point in the R.V’s image as
the weight of that point. Mathematically, the expected value of a discrete random variable is:
Variance of a R.V is a measure of “the amount of variation of a R.V around its mean”.
Mathematically, the variance of a discrete RV is defined as:
Lab Tasks
Lab Task 1:
Matlab code :
Fig no 6.1
Fig no 6.2
Lab 7
Binomial and Geometric distribution
Objective:
To familiarized with binomial and geometric distribution and its implementation in MATLAB.
Introduction:
Binomial Distribution:
A binomial distribution can be thought of as simply the probability of a SUCCESS or
FAILURE outcome in an experiment or survey that is repeated multiple times.
A binomial experiment is a statistical experiment that has the following properties:
To find the probability density function of 𝑿 we have to find the probability of 𝒙 successes in
𝒏 independent trails. If we have x successes in 𝒏 trails, then the probability of each n-tuple
with 𝑥 successes and 𝒏 − 𝒙 failures is
Syntax:
Y = binopdf(X,N,P)
Geometric Distribution:
The geometric distribution is the number of trials needed to get first success in repeated
Bernoulli trials.
𝒙𝒕𝒉𝑥
P(X = x) = p* (1 − 𝑝)𝑛−𝑥
Where x= 1, 2, 3….., ∞
Geopdf command:
geopdf returns the probability density function (pdf) of the geometric distribution at each value
in x using the corresponding probabilities in p. x and p can be vectors, matrices, or
multidimensional arrays that all have the same size.
Syntax:
y = geopdf(x,p)
LAB TASKS
Lab Task 1:
Suppose that 80 percent of trees in a forest of 300 trees are infected with a virus, and we take
5 trees at random to test for the virus. What is the probability that exactly 2 of the 5trees have
the virus?
Matlab code:
Fig no 7.1
Lab 8
Poisson and Negative Binomial Distribution
Objective:
To familiarized with Poisson and negative binomial distribution and its implementation in
MATLAB.
Introduction:
Poisson Distribution:
Experiments yielding numerical values of a random variable X, the number of outcomes
occurring during a given time interval or in a specified region, are called Poisson experiments.
The given time interval may be of any length, such as a minute, a day, a week, a month, or
even a year.
A random variable X is said to have a Poisson distribution if its probability density function is
given by:
𝑒 −𝜆 𝜆𝑥
p(x)= 𝑥!
Where 0<𝛌<∞ is a parameter.
Poisspdf command
poisspdf computes the Poisson pdf at each of the values in X using mean parameters
in lambda. X and lambda can be vectors, matrices, or multidimensional arrays that all have the
same size.
Syntax:
Y = poisspdf(X,lambda)
To find the number of trials ‘n’ needed to get fixed number of successes ‘x’
P(X = x) = (𝑛−1
𝑥−1
)𝑝 𝑥 (1 − 𝑝)𝑛−𝑥
nbinpdf command
It returns the negative binomial pdf at each of the values in X using the corresponding number
of successes, R and probability of success in a single trial, P. X, R, and P can be vectors,
matrices, or multidimensional arrays that all have the same size, which is also the size of Y. A
scalar input for X, R, or P is expanded to a constant array with the same dimensions as the other
inputs.
Syntax:
Y = nbinpdf(X,R,P)
LAB TASKS
Lab Task 1:
Matlab code:
Fig no8.1
Conclusion:
In this experiment we learn poission usinhg matlab.
Lab 9
Uniform Distribution
Objective:
To familiarized with Uniform and normal distribution and its implementation in MATLAB.
Introduction:
Uniform Distribution:
This distribution is defined by two parameters, a and b:
a is the minimum.
b is the maximum.
A random variable X is said to be uniform on the interval [a, b] if its probability density
function is of the form
1
f(x) =
𝑏−𝑎
which is calculated from the formula of area of rectangle where a and b are constants.
A continuous random variable X is said to be Normal or Gaussian if it has a PDF of the form
1 (𝑥−µ)2
−
𝑓(𝑥 ) = 𝑒 2𝜎 2
√2𝜋 𝜎
where 𝝁 and 𝝈 are two scalar parameters characterizing the PDF, with 𝝈 assumed nonnegative.
The 𝛍 parameter defines the location of the peak for normal distribution and is calculated by
using formula 𝐸[𝑋] = 𝜇 where 𝜎 defines the width of the normal distribution calculated by
using formula 𝑉𝑎𝑟 [𝑋] = 𝜎 2
Let 𝑿 be a normal random variable with mean µ and variance 𝝈𝟐. We “standardize” 𝑿 by
defining a new random variable 𝑌 given by
𝑋−µ
𝑌=
𝜎
Thus, Y is a standard normal random variable. This fact allows us to calculate the probability
of any event defined in terms of X: we redefine the event in terms of Y, and then use the
standard normal.
makedist command:
Creates a probability distribution object for the distribution distname, using the default
parameter values.
Syntax:
pd = makedist(distname)
For normal distribution we will write pd = makedist('Normal') and to create a normal
distribution object with parameter use pd = makedist('Normal','mu',75,'sigma',10)
Pdf Command:
It returns output as an array containing the probability density function (PDF) for the ProbDist
object PD, evaluated at values in X
Syntax:
Y = pdf(PD, X)
LAB TASKS
Lab Task 1:
Uniform distribution :
Matlab code :
Fig no 9.1
Fig no 9.2
Lab 10
Covariance
Objective:
To familiarized with Covariance and its implementation in MATLAB.
Introduction:
Covariance:
In mathematics and statistics, covariance is a measure of the relationship between two random
variables. The metric evaluates how much – to what extent – the variables change together. In
other words, it is essentially a measure of the variance between two variables. However, the
metric does not assess the dependency between variables.
Covariance measures how much the movement in one variable predicts the movement in a
corresponding variable. he units are computed by multiplying the units of the two variables.
The variance can take any positive or negative values. The values are interpreted as follows:
Positive covariance:
Indicates that two variables tend to move in the same direction i.e. increasing linear relationship
of two variables.
Negative covariance:
Reveals that two variables tend to move in inverse directions i.e. the decreasing linear
relationship of two variables
If covariance is zero the there is no relationship between two variables.
Figure11.1: Covariance
Average product of deviation measures extent to which variables covary, the degree of linkage
between them
1 𝑁
𝑆𝑥𝑦 = ∑ (𝑋𝑖 − 𝑋̅)(𝑌𝑖 − 𝑌̅)
𝑁 − 1 𝑖=0
LAB TASKS
Lab Task 1:
Investigate relationship between cigarette smoking and lung capacity. Data: sample group
response data on smoking habits, and measured lung capacities, respectively
Matlab code :
Fig no 10 .1
Lab Task 2:
Rising Hill manufacturing wishes to study the relationship between the number of workers, ‘x’,
and the number of tables produced, ‘y’. To do so 10 samples are obtained. Details are given as
follows; Find cov(x,y)
Matlab code :
Fig no 10.2
Lab 11
Correlation
Objective:
To familiarized with Correlation and its implementation in MATLAB.
Introduction:
Correlation:
A correlation is a statistical measure of the relationship between two variables. The measure is
best used in variables that demonstrate a linear relationship between each other. The fit of the
data can be visually represented in a scatterplot. Using a scatterplot, we can generally assess
the relationship between the variables and determine whether they are correlated or not.
For example, height and weight are related; taller people tend to be heavier than shorter people.
The relationship isn't perfect. Hook’s Law: 𝐹=𝑘𝑥. The relationship between two variables is
linear and perfect.
The correlation coefficient is a value that indicates the strength of the relationship between
variables. The coefficient can take any values from -1 to 1. The interpretations of the values
are:
No correlation.
When correlation is 0 he variables do not have a relationship with each other.
If correlation is 1 the variables tend to move in the same direction (i.e., when one variable
increases, the other variable also increases).
LAB TASKS
Lab Task 1:
Investigate relationship between cigarette smoking and lung capacity. Data: sample group
response data on smoking habits, and measured lung capacities, respectively
Fig no 11.1
Lab Task 2:
The local ice cream shop keeps track of how much ice cream they sell versus the temperature
on that day, here are their figures for the last 12 days
Temprature 14.2 16.4 11.9 15.2 18.5 22.1 19.4 25.1 23.4 18.1 22.6 17.2
Sale 215 325 185 332 406 522 412 614 544 421 445 408
Matlab code :
Fig no 11.2
Conclusion:
In this lab, I implemented correlation in MATLAB using examples provided.