Matlab Notes Prep. by Shahid Sir Merged
Matlab Notes Prep. by Shahid Sir Merged
Plots are a very useful tool for presenting information, especially in science and
engineering. MATLAB has many commands that can be used for creating different
types of plots. These include Line Plots, Data Distribution Plots, Discrete Data Plots,
Geographic Plots, Polar Plots, Contour Plots, Vector Fields, Surfaces, Volumes, and Polygons
and Animation.
MATLAB plotting functions and tools direct their output to a figure window.
vector vector
plot(X,Y) creates a 2-D line plot of the data in Y versus the corresponding values
in X.
Example 1:
If a vector x has the elements 1 2 3 4 5 6 7 8 and a vector y has the elements 3 1 2 6
5 7 8 3 a simple plot of y versus x can be created by as:
Example: Create x as a vector of linearly spaced values between 0 and 2*pi. Use an
increment of pi/100 between the values. Create y as sine values of x. Create a line
plot of the data.
>> x = linspace(0,2*pi,100);
>> y = sin(x);
>> plot(x,y)
>> %Label the axes and add a title.
>> xlabel('x')
>> ylabel('sin(x)')
>> title('Plot of the Sine Function')
Overlay plots and sub plots
MATLAB provides us the power to combine plots in several ways. This has the
power to combine multiple plots in the same axes called overlay plots, or create
multiple axis in the same figure using subplots.
Overlay Plots
We frequently need to plot more than one curve or data set on a single plot i.e.,
plotting the multiple graphs in the same plot or combine plots in same axes. Such a
plot is called an overlay plot. By default, new plots clear existing plots and reset axes
properties in the MATLAB, such as the title. However, user can use the hold on
command to combine multiple plots in the same axes.
To use overlay plots in MATLAB, the command plot has the form:
plot(X1,Y1,...,Xn,Yn)
plot(X1,Y1,LineSpec1,...,Xn,Yn,LineSpecn)
plots multiple X, Y pairs using the same axes for all lines.
By default, MATLAB clears the figure before each plotting command. You can plot
multiple lines using the hold on command. Until you use hold off or close the window,
all plots appear in the current figure window. When the hold state is on, new plots will
not clear existing plots or reset axes properties, such as axes or title labels.
Example:
Plot of Given Data In this case given data is used to create vectors that are then
used in the plot command. The following table contains sales data and profit of a
company from 1988 to 1994.
Year 1988 1989 1990 1991 1992 1993 1994
Sales (millions) 8 10 12 11 11 12 14
Profit (millions) 1 2 4 4 5 7 8 9
When you run the file, MATLAB generates the following graph:
Three-Dimensional Plots
Three-dimensional (3-D) plots can be a useful way to present data that consists of
more than two variables. MATLAB provides various options for displaying three-
dimensional data. They include line and wire, surface, mesh plots, and many others.
The plots can also be formatted to have a specific appearance and special effects.
Line plots
A three-dimensional line plot is a line that is obtained by connecting points in three-
dimensional space. A basic 3-D plot ‘is created with the plot3 command, which is
very similar to the plot command and has the form:
plot3(x,y,z)
plot3(x,y, linespec)
plot 3 plots graph in space
The three vectors x,y,z with the coordinates of the data points must have the
same number of elements.
The line specifiers, properties are the same as in 2-D plots
Example:
If the coordinates x, y, and z are given as a function of the parameter t by
X=√tsin(2t)
y=√tcos(2t)
z=0.5t
Draw a plot of the points for 0≤ t ≤ 6pi
Script Code:
t=0:0.1:6*pi;
x=sqrt(t).*sin(2*t);
y=sqrt(t).*cos(2*t);
z=0.5*t;
plot3(x,y,z,'k','linewidth',1)
grid on
xlabel('x'); ylabel('y'); zlabel('z')
Example:
Use the command plot3 (x , y, z) to plot the circular helix
x(t) = sin t,
y(t)=cos t,
z( t)=t,
0 <= t <= 20.
Script Code:
t=0:2:20;
x=sin(t);
y=cos(t).*cos(2*t);
z=t;
plot3(x,y,z)
grid
xlabel('x(t)=sin(t)'); ylabel('y(t)=cos(t)'); zlabel('z(t)=t')
Example:
Plot of a parametric space curve: x (t) = t, y (t ) = t2, z(t ) = t3. 0<=t <=l.
Script Code:
t = linspace (0 , 1,100) ;
x = t;
y = t.^2;
z = t.^ 3;
plot3 ( x,y,z)
grid
xlabel ('x(t)=t' )
ylabel ('y(t)=t^2 ')
zlabel ('z(t)=t^3 ')
Example:
Take x(t) , y (t) , and z(t) as input arguments to plot 3-D parametric curve. The
default domain is 0 < t < 2 π. Plot x ( t ) = tcos ( 3πt) , y ( t ) = tsin ( 3πt) , and z(t) =
t over the default domain.
Script Code:
t=0:2:2*pi;
x =t.*cos(3*pi*t);
y =t.*sin(3*pi*t);
z =t;
plot3(x,y,z)
grid
xlabel('x(t)=tcos3pit)'); ylabel('y(t)=tsin3pit'); zlabel('z(t)=t');
Symbolic vs. Numerical Computation in MATLAB
MATLAB Symbolic Mathematics
syms x y
MATLAB has a number of other built-in classes (and a user can create her/his
own, new classes if desirable). The class of a variable describes the structure of
operations and functions that can be applied to the variable. You can access the
class to which a variable belongs by invoking the command class:
>> x=5;
>> class(x)
ans =
double
>> x=[1 2 3]
x=
1 2 3
>> class(x)
ans =
double
>> a=sym('a');
>> class(a)
ans =
sym
Solving Linear Algebraic Equations in MATLAB
A linear equation can be defined as the equation having the maximum degree one.
A nonlinear equation can be defined as the equation having the maximum degree 2
or more than 2. A linear equation forms a straight line on the graph. A nonlinear
equation forms the curve on the graph.
Using a solve command we can solve an equation or system of equations that are in
the form of expressions. A single algebraic equation can be solved for one variable,
and a system of equations can be solved for several variables with the solve
function. An algebraic equation can have one or several symbolic variables.
The format of the solve command for solving a single equation is:
s = solve(eq)
If the equation has several symbolic variables, a solution can be obtained for any of
the variables in terms of the others. The solution is again obtained by using the solve
command, in this case takes the form:
S = solve(eqn,var)
solves an equation eqn for the symbolic variable var. If you do not specify var,
the symvar function determines the variable to solve for. For example, solve(x + 1 ==
2, x) solves the equation x + 1 = 2 for x.
The format of the solve command for solving a system of n equations is:
S = solve(eq1,eq2,....,eqn)
or
S = solve(eq1,eq2,...,eqn,var1,var2,...,varn)
The arguments eq1,eq2,...,eqn are the equations to be solved. for the
variables vars and returns a structure that contains the solutions. If you do not
specify vars, solve uses symvar to find the variables to solve for. In this case, the
number of variables that symvar finds is equal to the number of equations eqns.
[s1,...,sn] = solve(eq1,eq2,....,eqn)
or
[s1,...,sn] = solve(eq1,eq2,...,eqn,var1,var2,...,varn)
solves the system of equations eqns for the variables vars. The solutions are
assigned to the variables s1,...,sn. If you do not specify the
variables, solve uses symvar to find the variables to solve for. In this case, the
number of variables that symvar finds is equal to the number of output arguments N.
Output
ans =
3
ans =
1
ans =
-5
Another Way
syms x y z
eqn1 = '2*x + y + z = 2'
eqn2 = '-x + y - z = 3'
eqn3 = 'x + 2*y + 3*z = -10'
[s1,s2,s3] = solve(eqn1,eqn2,eqn3);
%[s1,s2,s3] = solve(eqn1,eqn2,eqn3,x,y,z);
s1
s2
s3
Output
qn1 =
2*x + y + z = 2
eqn2 =
-x + y - z = 3
eqn3 =
x + 2*y + 3*z = -10
s1 =
3
s2 =
1
s3 =
-5
Solve System of Linear Equations Using linsolve
Matrix Methods for solving system of Linear Equations
Sets of linear algebraic equations can be expressed as a single equation, using
matrix notation. A system of linear equations can be represented as the matrix
form A⋅x=b, where A is the coefficient matrix. If you do not have the system of linear
equations in the form Ax=b, use equationsToMatrix command to convert the
equations into this form.
Inverse Matrix Method
We have a matrix multiplication equation of the form Ax = b, and we want to
solve for the unknowns x. This can be accomplished as follows:
Ax=b
x = A-1 b So, the solution can be found as a product of the inverse of A and the
column vector b.
To put the system of linear equations in the form Ax = B, you can also use
MATLAB’s equationsToMatrix function to convert the equations into this form. The
second input to equationsToMatrix defines the independent variables in the
equations.
Consider the same system of equations.
>> syms x y z
eqn1 = 2*x + y + z == 2;
eqn2 = -x + y - z == 3;
eqn3 = x + 2*y + 3*z == -10;
[A,B] = equationsToMatrix([eqn1, eqn2, eqn3], [x, y, z])
>> A
A=
2 1 1
-1 1 -1
1 2 3
>> B
B=
2
3
-10
>> sol = linsolve(A,B)
sol =
3
1
-5
Gauss-Jordan elimination using MATLAB
Gauss-Jordan Elimination puts a matrix in reduced row echelon form. The
command to do Gauss-Jordan reduction, known in MATLAB as “reduced row-
echelon form”, is
rref(A)
R = rref(A) produces the reduced row echelon form of A using Gauss Jordan
elimination with partial pivoting. In this form, the matrix has leading 1s in the pivot
position of each column.
This technique requires forming an augmented matrix (that contains both the
coefficient matrix A and the known vector b), and then transforms the matrix to its
row reduced echelon form.
3 4
4 -2
To express a system in matrix form, we extract the coefficients of the variables and
the constants, and these become the entries of the matrix. When a system is written
in this form, we call it an augmented matrix.
A=
3 4 7
4 -2 5
A=
8 1 6
3 5 7
4 9 2
>> RA = rref(A)
RA =
1 0 0
0 1 0
0 0 1
A=
2 1 1
-1 1 -1
1 2 3
>> B=[2;3;-10]
B=
2
3
-10
A=
2 1 1 2
-1 1 -1 3
1 2 3 -10
>> rref(A)
ans =
1 0 0 3
0 1 0 1
0 0 1 -5
>> solution=ans(:,end)
solution =
3
1
-5
>> A=[-3,2;1,1]
A=
-3 2
1 1
>> B=[1;4]
B=
1
4
>> A=[A B]
A=
-3 2 1
1 1 4
rref(A)
ans =
1.0000 0 1.4000
0 1.0000 2.6000
The solution is found from the last column so x1 = 1.4000, x2 = 2.6000. To get this in
a column vector in MATLAB:
>> x = ans(:,end)
x=
1.4000
2.6000
And so on. Here A1 is the matrix obtained by replacing the first column
of A by B, A2 is the matrix obtained by replacing the second column of A by B etc.
>> A=[-3,2;1 1]
A=
-3 2
1 1
>> B=[1;4]
B=
1
4
>> A1=A;
A1(:,1)=B
A1 =
1 2
4 1
>> A2=A;
A2(:,2)=B
A2 =
-3 1
1 4
For example,
The most basic form of the dsolve command for finding the solution to a single
equation is:
dsolve('eqn')
where eqn is a text string used to enter the equation.
It returns a symbolic solution with a set of arbitrary constants that MATLAB labels
C1, C2, and so on.
dsolve('eqn', ‘var’)
In the dsolve(‘eq’,‘var’) command the user defines the independent variable by typing
it for var (as a string).
You can also specify initial and boundary conditions for the problem, as comma-
delimited list following the equation as:
dsolve('eqn','cond1', 'cond2',…)
can be used for ODE’s that needs to be solved for the interval with the initial
condition(s).
>> dsolve('Dx=x+t')
ans =
C9*exp(t) - t – 1
To solve an initial value problem, say, the above equation with x(1) = 1, use
>> dsolve('Dx=x+t','x(1)=1','t')
ans =
(3*exp(t))/exp(1) - t – 1
>> dsolve('D2x+2*Dx+x=0')
ans =
C5/exp(t) + (C6*t)/exp(t)
To solve an initial value problem, say, the above equation with x(1) = 2, use
>> dsolve('D2x+2*Dx+x=0','x(1)=2','t')
ans =
C7/exp(t) - (t*exp(1)*(C7/exp(1) - 2))/exp(t)
Ordinary Differential Equation (ODE)
Finding Numerical Solutions
MATLAB has a number of tools for numerically solving ordinary differential
equations. We will focus on the main two, the built-in functions ode23 and ode45.
Example:
Solve the ODE
y′= 6*x - 3*y
Use a time interval of [0,5] and the initial condition y0 = 0.
For single equations, we can define f(x, y) as an anonymous /inline function.
>> f = inline(' 6*x - 3*y')
f=
Inline function:
f(x,y) = 6*x - 3*y
[x,y] = ode45(f,[0 2],0);
plot(x,y)
Now use the solver ode23
f = inline(' 6*x - 3*y')
f=
Inline function:
f(x,y) = 6*x - 3*y
>> [x,y] = ode23(f,[0 2],0);
>> plot(x,y)
Example: Using MATLAB to give a numerical solution to an ODE
The ODE is
We use ode45 to obtain the numeric solution by defining a MATLAB function equal
to the right side of the equation with an anonymous function.
syms t
f = @(t,y) 2.*y -1
f=
@(t,y)2.*y-1
To solve and plot the approximate solution on the interval [0,1], we give the
command
ode45(f, [0,1], 1)
Differentiation
In calculus, differentiation is one of the two important concepts apart from
integration. Differentiation is a method of finding the derivative of a function.
Differentiation is a process, in Maths, where we find the instantaneous rate of change
in function based on one of its variables. The most common example is the rate
change of displacement with respect to time, called velocity. The opposite of finding a
derivative is anti-differentiation.
If x is a variable and y is another variable, then the rate of change of x with respect to
y is given by dy/dx. This is the general expression of derivative of a function and is
represented as f'(x) = dy/dx, where y = f(x) is any function.
Derivatives of polynomials
Polyder function
The MATLAB built-in function polyder finds the derivative of a polynomial. The
functions polyder is used to analytically differentiate any polynomial represented by
a vector of coefficients. The built-in function polyder can be used to calculate the
derivative of a single polynomial, a product of two polynomials, or a quotient of
two polynomials.
k = polyder(p)
[n d] = polyder(p,q)
Example: Consider the functions f1(x) = 3x2 – 2x + 4 and f2(x) = x2 + 5, find the
derivatives of single polynomial, product of polynomials and quotient of two
polynomials.
Derivative of a polynomial p
Method 1
>> d = polyder(p,q)
d=
12 -6 26 -6
The derivative of f1*f2 is: 12x3 – 6x2 + 38x – 10
Method 2
Another approach is to use define is to first use the conv(p,q) function to find the
total polynomial, and then use polyder(cnv) function.
cnv = conv(p,q)
cnv =
3 -2 13 -6 12
>> d=polyder(cnv)
d=
12 -6 26 -6
The derivative of f1*f2 is: 12x3 – 6x2 + 38x – 10
>> [n,d]=polyder(p,q)
n=
2 10 -6
d=
1 0 6 0 9
The derivative of is
Symbolic Differentiation (symbolic derivatives)
Symbolic differentiation finds the derivative of a given function with respect to one of its
variables. The derivative of a function y=f(x) is a measure of how y changes with x
MATLAB provides the diff command for computing symbolic derivatives. diff command
Differentiate symbolic expression or function. In its simplest form, you pass the function you
want to differentiate to diff command as an argument.
Because you did not specify the differentiation variable, diff uses the default variable defined
by symvar.
diff (f, n) will compute nth derivative (as passed in the argument) of the function ‘f’ w.r.t the
variable determined using symvar.
diff(f,var,n) computes the nth derivative of the function f with respect to the variable var
passed in the argument.
Example: find the derivative of univariate expression with respect to default variable.
>> syms x y
>> y=sin(3*x)*exp(5*x)+x^2+1/3
y=
x^2 + sin(3*x)*exp(5*x) + 1/3
>> diff(y)
ans =
2*x + 3*cos(3*x)*exp(5*x) + 5*sin(3*x)*exp(5*x)
% Because you did not specify the differentiation variable, diff uses the default variable
defined by symvar. For this expression, the default variable is x:
Example: find the derivative of univariate expression with respect to particular variable.
Example: find the derivative of univariate expression with respect to particular variable at
value 3
>> subs(ans,{x},{3})
ans =
-2.1994e+006
Example: find the fourth order derivative of univariate expression with respect to particular
variable.
>> diff(y,x,4)
ans =
960*cos(3*x)*exp(5*x) - 644*sin(3*x)*exp(5*x)
Example: find the fourth order derivative of univariate expression with respect to particular
variable at value 3
>> subs(ans,{x},{3})
ans =
-3.7270e+009
Partial Derivatives
Total derivative is a measure of the change of all variables, while Partial derivative is a
measure of the change of a particular variable having others kept constant. The diff command
can also handle partial differentiation.
Example: Consider f(x,y)=x^2+y^2, a function of two variables. The first partial derivative
of f with respect to its variables x and y are found as follows.
>> syms x y
>> f=2*x^2+3*y
f=
2*x^2 + 3*y
The total derivative of f(x,y) can be obtained as
>> dx=diff(f,x,y)
dx =
3
>> dx=diff(f,x)
dx =
4*x
>> dy=diff(f,y)
dy =
3
Example: Consider f(x,y)= x*sin(x*y), a function of two variables. Find its total
derivatives and partial derivatives.
The total derivative of f(x,y) can be obtained as
>> syms x y
diff(x*sin(x*y), x, y)
ans =
x^2*cos(x*y)
>> diff(x*sin(x*y), x)
ans =
sin(x*y) + x*y*cos(x*y)
>> diff(x*sin(x*y),y)
ans =
x^2*cos(x*y)
Numerical approximation to derivatives
We can calculate the derivative numerically by approximating the derivative of a
function at particular value.
Example: find the numerical approximation to the derivative of function f when the
variable x=2
>> f=x^2
f=
x^2
>> diff(f,x)
ans =
2*x
Numerical approximation to the derivative of f at x=2
>> subs(ans,{x},{2})
ans =
4
Method 1
>> f=x^3-4*x^2
f=
x^3 - 4*x^2
>> diff(f,x)
ans =
3*x^2 - 8*x
>> subs(ans,{x},{2})
ans =
-4
Method 2
>> derrivative=inline(diff(x^3 - 4*x^2,x,'x'))
derrivative =
Inline function:
derrivative(x) = x.*-8.0+x.^2.*3.0
derivative at x=2
>> derrivative(2)
ans =
-4
Polynomial Integration
Matlab function polyint is used to compute the integration of a polynomial. The general form
of this function is
q= polyint(p, k)
or
q = polyint(p)
were
p represents the vector of the coefficients of the polynomials whose integration is to be
obtained, and
k is the scalar constant of integration and q contains the result.
q = polyint(p) assumes a constant of integration k = 0.
p = [4 -3 0 1];
q = polyint(p)
q=
1 -1 0 1 0
Example: Integrate the polynomial using the polyint function. Specify the
constant of integration as 2.
P = [4 0 -2 0 1 4];
K=2;
I = polyint(p,k)
I=
0.6667 0 -0.5000 0 0.5000 4.0000 2.0000
Example: Integrate the polynomial
. Take constant of integration as 3
q=
I=
32.6667
Let us take constant of integration k = 3.
>> k=3;
>> q = polyint(conv(p,v),k)
q=
0.1250 0 0 0 -0.2500 0.3333 0 1.0000 3.0000
>> a = 0;
>> b = 2;
>> I = diff(polyval(q,[a b]))
I=
32.6667
Integration in MATLAB
Integration is defined as the process of finding the anti derivative of a function. There are
two types of Integration:
Indefinite Integral
Let f(x) be a function. Then the family of all antiderivatives is called the indefinite integral
of a function f(x) and it is denoted by ∫f(x)dx. The symbol ∫f(x)dx is read as the indefinite
integral of f(x) with respect to x. The indefinite integral of f(x) is a function. i.e. An
indefinite integral returns a function of the independent variable(s). With an indefinite
integral there are no upper and lower limits on the integral here, and what we'll get is an
answer that still has x's in it and will also have a constant (usually denoted by C) in it. Its
general form is:
Where
∫f(x)dx is read “the integral of f w.r.t. x”
the symbol ∫ is called the integral sign
the function f is referred to as the integrand of the integral and
the variable x is called the variable of integration
Definite Integral
Definite integrals are the extension after indefinite integrals, definite integrals have limits
[a, b]. The definite integral of f(x) is a NUMBER which gives the area of a curve bounded
between given limits. It is denoted by ∫f(x)dx under the limit of a and b, it denotes the area
of curve F(x) bounded between a and b, where a is the lower limit and b is the upper limit.
Its general form is:
where a is the lower limit and b is the upper limit.
MATLAB provides the int command for computing symbolic integrals. polyint() is related
only to polynomials. It returns the integral of the polynomial represented by the coefficients.
The int function integrates symbolic expressions and functions. It is more general.
f = int(expr)
f = int(expr) computes the indefinite integral of expr. int uses the default integration variable
determined by symvar(expr,1). If expr is a constant, then the default integration variable is x.
f = int(expr,var)
f = int(expr,var) computes the indefinite integral of expr with respect to symbolic scalar
variable var.
f = int(expr,a,b)
F = int(expr,a,b) computes the definite integral of expr from a to b. it uses the default
integration variable determined by symvar(expr,1). If expr is a constant, then the default
integration variable is x.
int(expr,[a b]) is equivalent to int(expr,a,b).
f = int(expr,var,a,b)
f = int(expr,var,a,b) computes the definite integral of expr with respect to the symbolic
>> int(f,x)
ans =
(2*x^(3/2)*(log(x) - 2/3))/3
p='4*x^5-2*x^3+x+4'
p=
4*x^5-2*x^3+x+4
>> int(p)
ans =
(2*x^6)/3 - x^4/2 + x^2/2 + 4*x
>> pretty(ans)
Example: find the definite integrals of a function under the limits -4 and 10
>> p='sin(x)+cos(x)^2'
p=
sin(x)+cos(x)^2
>> int(p,-4,10)
ans =
cos(4) - cos(10) + sin(8)/4 + sin(20)/4 + 7
double(ans)
ans =
7.6610
Example: Evaluate the definite integral
>> a=-1;
>> b=3;
p='3*x^4-4*x^2+10*x-25'
p=
3*x^4-4*x^2+10*x-25
int(p,a,b)
ans =
736/15
>> 736/15
ans =
49.0667
Numerical Integration using MATLAB inbuild functions
we have several built-in functions quad, quadl, trapz and integral in matlab, we can use for
numerical integration. The quad and quadl commands are used for integration when f(x) is a
function, and trapz is used when f(x)is given by data points.
Example:
>> p='x^2'
p=
x^2
>> int(p,0,1)
ans =
1/3
>> 1/3
ans =
0.3333
The quad command:
The form of the quad command, which uses the adaptive Simpson method of integration, is:
We will follow the following 2 steps to find integral of a function using integral function.
Step 1: Create the function in MATLAB
Step 2: Use the integral function to calculate the integration
Syntax
M = mean(A)
If A is a vector, then mean(A) returns the mean of the elements. If A is a matrix,
then mean(A) returns a row vector containing the mean of each column.
M = mean(A,dim)
returns the mean along dimension dim. For example, if A is a matrix, then mean(A,2) is a
column vector containing the mean of each row and mean(A,1) returns a row vector
containing the mean of each column.
M = mean(A,'all')
computes the mean over all elements of A. This syntax is valid for MATLAB versions
R2018b and later.
A=
1 2 3
2 3 4
3 4 5
>> mean(A)
ans =
2 3 4
>> mean(A,1)
ans =
2 3 4
>> a=[12 3 4]
a=
12 3 4
>> mean(a)
ans =
6.3333
>> a=[1;2;3]
a=
1
2
3
>> mean(a)
ans =
2
>>A=[1 2 3;2 3 4;3 4 5]
A=
1 2 3
2 3 4
3 4 5
>> mean(A,1)
ans =
2 3 4
>> mean(A,2)
ans =
2
3
4
Median
The "median" is the "middle" value in the list of numbers. To find the median, your numbers
have to be listed in numerical order from smallest to largest.
Syntax
M = median(A)
If A is a vector, then median(A) returns the median value of A. If A is a matrix, then median
(A) returns a row vector containing the mean of each column. i.e., If A is a nonempty matrix,
then median(A) treats the columns of A as vectors and returns a row vector of median values.
M = median(A,dim)
returns the median of elements along dimension dim. For example, if A is a matrix,
then median(A,2) is a column vector containing the median value of each row.
M = median(A,'all')
computes the median over all elements of A. This syntax is valid for MATLAB® versions
R2018b and later.
>> A=[1 2 3 4 5]
A=
1 2 3 4 5
>> median(A)
ans =
>> A=[1;2;3;4;5]
A=
1
2
3
4
5
>> median(A)
ans =
a=
1 2 3
3 2 1
4 3 2
>> median(a)
ans =
3 2 2
>> median(a,1)
ans =
3 2 2
For each column, the median value is the middle number in sorted order.
>> median(a,2)
ans =
2
2
3
For each row, the median value is the middle number in sorted order.
Mode
The mode is defined as the most frequently occurring element in the vector. The "mode" is
the value that occurs most often. If no number in the list is repeated, then there is no mode for
the list.
Syntax
M = mode(A)
returns the sample mode of A, which is the most frequently occurring value in A. When there
are multiple values occurring equally frequently, mode returns the smallest number of those
values. If A is a vector, then mode(A) returns the most frequent value of A. If A is a
nonempty matrix, then mode(A) returns a row vector containing the mode of each column
of A.
M = mode(A,dim) returns the mode of elements along dimension dim. For example, if A is a
matrix, then mode(A,2) is a column vector containing the most frequent value of each row
M = mode(A,'all') computes the mode over all elements of A. This syntax is valid for
MATLAB versions R2018b and later.
>> a=[1 2 2 3 5 5]
a=
1 2 2 3 5 5
>> mode(a)
ans =
>> a=[1 5 5 3 2 2]
a=
1 5 5 3 2 2
>> mode(a)
ans =
2
>> a=[1 2 2 3 4;1 4 4 4 5;7 1 3 3 3]
a=
1 2 2 3 4
1 4 4 4 5
7 1 3 3 3
>> mode(a)
ans =
1 1 2 3 3
>> mode(a,1)
ans =
1 1 2 3 3
>> mode(a,2)
ans =
2
4
3
Range
The "range" of a list of numbers is just the difference between the largest and smallest values.
Syntax
y = range(X)
returns the difference between the maximum and minimum values of sample data in X.
If X is a vector, then range(X) is the range of the values in X. If X is a matrix,
then range(X) is a row vector containing the range of each column in X.
y = range(X,dim)
returns the range along the operating dimension dim of X. For example, if X is a matrix,
then range(X,2) is a column vector containing the range value of each row.
>> a=[1 2 4 7 3]
a=
1 2 4 7 3
>> range(a)
ans =
>> a=[1;2;4;7;3]
a=
1
2
4
7
3
>> range(a)
ans =
a=
1 2 2 3 4
1 4 4 4 5
7 1 3 3 3
>> range(a)
ans =
6 3 2 1 2
>> range(a,1)
ans =
6 3 2 1 2
>> range(a,2)
ans =
3
4
6
Variability in Statistics
Variability in statistics refers to the difference being exhibited by data points within a data set
or how spread out a group of data is. In other words, variability measures how much your
scores differ from each other. Variability is also referred to as dispersion or spread. Data sets
with similar values are said to have little variability, while data sets that have values that are
spread out have high variability.
Measures of Variability
This can be expressed through the range, variance or standard deviation of a data set.
Variance
The variance is a measure of variability that determines the squared variation of a set of
variables from the average or mean in that set.
The variance symbolically represented by σ2, s2, or Var(X), is defined as the sum of the
squared distances of each term in the distribution from the mean (μ), divided by the number
of terms in the distribution (N). It is calculated by taking the mean of the data points,
subtracting the mean from each data point individually, squaring each of these results, and
then taking another mean of these squares.
Population variance
When you have collected data from every member of the population that you’re interested in,
you can get an exact value for population variance.
The population variance formula looks like this:
Sample variance
When you collect data from a sample, the sample variance is used to make estimates
or inferences about the population variance.
The sample variance formula looks like this:
With samples, we use n – 1 in the formula because using n would give us a biased estimate
that consistently underestimates variability. The sample variance would tend to be lower than
the real variance of the population.
Reducing the sample n to n – 1 makes the variance artificially large, giving you an unbiased
estimate of variability: it is better to overestimate rather than underestimate variability in
samples.
Find the mean of the given data set. Calculate the average of a given set of values
Now subtract the mean from each value and square them
Find the average of these squared values, that will result in variance
Say if x1, x2, x3, x4, …,xn are the given values.
Therefore, the mean of all these values is:
x̄ = (x1+x2+x3+…+xn)/n
Now subtract the mean value from each value of the given data set and square them.
(x1-x̄)2, (x2-x̄)2, (x3-x̄)2,…….,(xn-x̄)2
Find the average of the above values to get the variance.
Var (X) = [(x1-x̄)2+ (x2-x̄)2+ (x3-x̄)2+…….+(xn-x̄)2]/n
Hence, the variance is calculated.
Variance in MATLAB
Syntax:
V = var(A) returns the variance of the elements of A along the first array dimension whose
size does not equal 1. If A is a matrix, V is a row vector containing the variances
corresponding to each column.
V = var(A,w,dim) returns the variance along the dimension dim. To maintain the default
normalization while specifying the dimension of operation, set w = 0 in the second argument.
var(A,0) is the same as var(A).
V = var(A,w,'all') computes the variation over all elements of A when w is either 0 or 1. This
syntax is valid for MATLAB versions R2018b and later.
>> a=[1 5 2 4 3]
a=
1 5 2 4 3
>> var(a)
ans =
2.5000
>> a=[1 5 2 3 4;8 5 2 5 7]
a=
1 5 2 3 4
8 5 2 5 7
>> var(a)
ans =
>> var(a,0)
ans =
24.5000 0 0 2.0000 4.5000
>> var(a,1)
ans =
12.2500 0 0 1.0000 2.2500
Standard Deviation
The standard deviation is derived from variance and tells you, on average, how far each value
lies from the mean. Standard Deviation is just the square root of Variance.
σ = population standard deviation
s = std(X,flag) for flag = 0, is the same as std(X). For flag = 1, std(X,1) returns the standard
deviation using population variance above
>> a=[1 5 2 4 3]
a=
1 5 2 4 3
>> std(a)
ans =
1.5811
>> std(a,0)
ans =
1.5811
>> std(a,1)
ans =
1.4142
For matrix a
>> s = std(a,0,1)
s=
0.7071 0.7071 0
>> s = std(a,0,2)
s=
1
1
Hans-Petter Halvorsen
Interpolation
Interpolation is used to estimate data points between two known points. The most common
interpolation technique is Linear Interpolation.
The most common interpolation technique is Linear Interpolation. • In MATLAB we can use
the interp1() function. • The default is linear interpolation, but there are other types available,
such as: – linear – nearest – next– previous– spline – cubic etc. The default method is 'linear'.
Problem: Assume we want to find the interpolated value for, e.g., = 3.5
We can use one of the built-in Interpolation functions in MATLAB:
x=0:5;
y=[15, 10, 9, 6, 2, 0];
plot(x,y ,'-o')
grid on
new_x=3.5;
new_y = interp1(x,y,new_x)
Example: consider the example of temperature variation in a day
Time Temperatur
e
00 mid night 30.1
01 am and so 29.7
on
02 28.2
03 27.4
04 29.7
05 29.9
06 30.1
07 28.3
08 31.5
09 27.6
10 28.8
11 28.9
12 28.1
13 26.6
14 29.2
15 28.4
16 27.5
17 27.9
18 28.6
19 28.2
20 29.4
21 29.3
22 30.9
23 27.3
24 29.5
We are interested in finding temperature at various times in a day in addition to the ones
where data is available.
We interpolate or fill the missing data
Now h=0:24
t= [30.1, 29.7, 28.2, 27.4, 29.7, 29.9, 30.1, 28.3, 31.5, 27.6, 28.8, 28.9, 28.1, 26.6, 29.2, 28.4,
27.5, 27.9, 28.6,28.2,29.4,29.3,30.9,27.3,29.5]
h=0:24;
h1=[2.5,6.5,10.25,17.0]
t= [30.1, 29.7, 28.2, 27.4, 29.7, 29.9, 30.1, 28.3, 31.5, 27.6, 28.8, 28.9, 28.1, 26.6, 29.2, 28.4,
27.5, 27.9, 28.6,28.2,29.4,29.3,30.9,27.3,29.5];
t1=interp1(h,t,h1)
plot(h1,t1,'go--')
Example2:
>> x=0:10;
>> y=sin(x);
>> plot(x,y,'go--')
>> xi=0:.25:10;
>> yi=interp1(x,y,xi,'linear');
>> plot(xi,yi,'go--')
title('(Default) Linear Interpolation');
Assume we want to find the interpolated value for xi given below
x=0:10;
y=sin(x);
xi=0:.25:10;
yi=interp1(x,y,xi,'spline');
plot(xi,yi,'go--')
title('Spline Interpolation');
Histogram in MATLAB
A Histogram is a diagrammatic representation of a group of data over user-specified ranges.
Basically, the histogram contains several bins. Bins are non-overlapping intervals in which
the data is spread. In MATLAB we have a function named hist() which allows us to plot a
bar graph.
Syntax:
hist(X)
where X represents the data. The X is a vector.
The histogram function creates a histogram plot of X. The histogram function uses an
automatic binning algorithm that returns bins with a uniform width, chosen to cover the range
of elements in X and reveal the underlying shape of the distribution. histogram displays the
bins as rectangles such that the height of each rectangle indicates the number of elements in
the bin.
hist(Y,x) where x is a vector, returns the distribution of Y among length(x) bins with centers
specified by x. For example, if x is a 5-element vector, hist distributes the elements of Y into
five bins centered on the x-axis at the elements in x. Note: use histc if it is more natural to
specify bin edges instead of centers.
Output:
Example 2: Histogram with a given number of bins:
% generate 1000 random numbers
y=randn(1000,1)
% assign 50 to variable nbins for number of bins
nbins=50;
% hist() function to plot the histogram
% hist() funcion use the nbins variable and spread the data in 50 bins
hist(y,nbins)
Output:
Example 3: Histogram of multiple columns:
% generate 1000 random numbers in 4 groups
y=randn(1000,4)
% hist() function to plot the histogram
hist(y)
Output
Example 3: Histogram and given bins with centre specified
y=randn(1000,4);
x=[1 2 3 4 5];
hist(y,x)
Output
What Is a statistical Distribution?
An arrangement of values of a variable showing their observed or theoretical frequency of
occurrence. A distribution in statistics is a function that shows the possible values for a
variable and how often they occur. From a practical perspective, we can think of a
distribution as a function that describes the relationship between observations in a sample
space.
For example, we may be interested in the age of humans, with individual ages representing
observations in the domain, and ages 0 to 125 the extent of the sample space. The distribution
is a mathematical function that describes the relationship of observations of different heights.
A distribution is simply a collection of data, or scores, on a variable. Usually, these scores are
arranged in order from smallest to largest and then they can be presented graphically.
Density Functions
Distributions are often described in terms of their density or density functions. Density
functions are functions that describe how the proportion of data or likelihood of the
proportion of observations change over the range of the distribution.
Two types of density functions are probability density functions and cumulative density
functions.
Probability Density function: calculates the probability of observing a given value.
Cumulative Density function: calculates the probability of an observation equal or less than
a value.
A probability density function, or PDF, can be used to calculate the likelihood of a given
observation in a distribution. It can also be used to summarize the likelihood of observations
across the distribution’s sample space. Plots of the PDF show the familiar shape of a
distribution, such as the bell-curve for the Gaussian distribution.
Distributions are often defined in terms of their probability density functions with their
associated parameters.
A cumulative density function, or CDF, is a different way of thinking about the likelihood of
observed values. Rather than calculating the likelihood of a given observation as with the
PDF, the CDF calculates the cumulative likelihood for the observation and all prior
observations in the sample space. It allows you to quickly understand and comment on how
much of the distribution lies before and after a given value. A CDF is often plotted as a curve
from 0 to 1 for the distribution.
Both PDFs and CDFs are continuous functions. The equivalent of a PDF for a discrete
distribution is called a probability mass function, or PMF.
Gaussian Distribution
The Gaussian distribution, named for Carl Friedrich Gauss, is the focus of much of the field
of statistics.
Data from many fields of study surprisingly can be described using a Gaussian distribution,
so much so that the distribution is often called the “normal” distribution because it is so
common.
A Gaussian distribution can be described using two parameters:
mean: Denoted with the Greek lowercase letter mu, is the expected value of the distribution.
variance: Denoted with the Greek lowercase letter sigma raised to the second power
(because the units of the variable are squared), describes the spread of observation from the
mean.
It is common to use a normalized calculation of the variance called the standard deviation
standard deviation: Denoted with the Greek lowercase letter sigma, describes the
normalized spread of observations from the mean.
A Gaussian with these values for the mean and standard deviation is called the Standard
Gaussian.
Example: Compute the pdf values for the standard normal distribution at the values in x.
x = [-2,-1,0,1,2];
y = normpdf(x)
y = 1×5
0.0540 0.2420 0.3989 0.2420 0.0540
Example: Compute the pdf values evaluated at the values in x for the normal distribution
with mean mu and standard deviation sigma.
x = [-2,-1,0,1,2];
mu = 2;
sigma = 1;
y = normpdf(x,mu,sigma)
y = 1×5
0.0001 0.0044 0.0540 0.2420 0.3989
Example: Compute the pdf values evaluated at zero for various normal distributions with
different mean parameters.
mu = [-2,-1,0,1,2];
sigma = 1;
y = normpdf(0,mu,sigma)
y = 1×5
0.0540 0.2420 0.3989 0.2420 0.0540