MATLAB Manual Final
MATLAB Manual Final
(MATLAB)
Submitted to:
Mam Aymon Zahra
Submitted by:
Umar Pitafi
Class of 24’
Lab Group: B
Roll # 2K20-CHE-110
Table of Contents
1. Introduction & Installation
2. MATLAB as Calculator & Hierarchy
3. Plotting of graphs
4. Multiple Functional Graphs with axis, legends etc.
5. Vector generation and colon operators
6. Matrix generation and Linear Problem Solving
7. Arrays
8. M-Scripts
9. M-Functions
10. Control Flows ( if……end) loops
11. For…..while loops
12 Polynomials and MATLAB
13 Curve Fitting
14 Interpolation
15 Three Dimensional Plots
1 INTRODUCTION AND INSTALLATION
Introduction:
The name MATLAB stands for Matrix laboratory. MATLAB was written originally to provide
easy access to matrix software developed by the LINPACK (linear system package) and
EISPACK (Eigen system package) projects. MATLAB is a high-performance language for
technical computing. It integrates computation, visualization, and programming environment.
Furthermore, MATLAB is a modern programming language environment: it has sophisticated
data structures, contains built-in editing and debugging tools, and supports object-oriented
programming. These factors make MATLAB an excellent tool for teaching and research.
MATLAB has many advantages compared to conventional computer languages (e.g., C,
FORTRAN) for solving technical problems. MATLAB is an interactive system whose basic data
element is an array that does not require dimensioning.
Installation:
The Installation process is remarkably simple for MATLAB as described in the following steps
1. Go to http://www.mathworks.com/downloads/web_downloads/
2. Sign into your MATLAB account
3. After signing in a page will appear with the download link click on the download button
and download the software
Page | 1
4. After downloading , Open the installer and let it unpack
5. After unpacking the Installer will open, Accept the terms and conditions to continue
installation process and click on next
Page | 2
7. Select your Installation destination
8. Under Products section select MATLAB and move to Confirmation on Confirmation Tab
click on Begin Installation
9. The necessary files for MATLAB will now be downloaded and installed
Page | 3
10. After installation, the following screen will appear
Page | 4
2 MATLAB AS A CALCULATOR AND HIERARCHY OF ARITHMETIC
OPERATIONS
Now in the workspace we can see the answer generated by the expression 5+17 x10 is stored
as Ans 175 this is because we have not specified any variable to the expression and
MATLAB uses default variable (Ans) , to avoid this we can assign a variable to our
expression as
Now this variable can be manipulated in form of function or arguments to generate various
answers
For Instance
Lets suppose we want to calculate Y=42x-194 then by using MATLAB we find this value of
Y by simply writing the argument
Page | 5
The answer generated for the expression will be Stored as variable Y because we have
assigned the expression a variable
Page | 6
If the parenthesis is missing, then the answer varies
So here what we get: two different results. Therefore, we want to emphasize the
importance of precedence rule to avoid ambiguity.
Page | 7
3 PLOTTING OF GRAPHS
MATLAB has an excellent set of graphic tools. Plotting a given data set or the result of
computation is possible with very few commands. You are highly encouraged to plot
mathematical functions and results of analysis as often as possible. Trying to understand
mathematical equations with graphics is an enjoyable and very efficient way of learning math.
Being able to plot mathematical functions and data freely is the most key step, and this section is
written to assist you to do just that.
The MATLAB command to plot a graph is plot(x,y).
The vectors x = [5 10 15 20 ] and y = [2 10 11 19 ]
The MATLAB Command for Plotting 2d graphs is as follows
The plot functions has different forms depending on the input arguments. If y is a vector plot(y)
produces a piecewise linear graph of the elements of y versus the index of the elements of y. If
we specify two vectors, as mentioned above, plot(x,y) produces a graph of y versus x.
Page | 8
For example, to plot the function sin (x) on the interval [0,5pi], we must create a vector of x
values ranging from 0 to 5pi then compute the cos of these values, and finally plot the graph
It can be seen in the screenshot attached below that first we created an interval of 0-5pi and
named it X and after that we assigned a function to that interval and finally gave the plot
command to plot the graph between interval and its functional values
Page | 9
4 MULTIPLE FUNCTIONAL GRAPHS WITH AXIS, LEGENDS
Multiple (x; y) pairs arguments create multiple graphs with a single call to plot. For example,
these statements plot three related functions of x as described in the previous section say we want
to plot multiple functions on a single interval which is defined already, this can be done in
MATLAB by writing following commands
It can seen in the command window that we created various functions for plotting multiple
graphs and in the plot command we added another command ‘—’ for dashed lined for a plain
curve we assigned ‘-‘ to our function and for dotted curve we assigned ‘:’ to our function
Axis , Legends , Titles , annotations and assigning colors can also be done in MATLAB simply
as shown in commands given in the screenshot on the next page
Page | 10
Page | 11
5 VECTOR GENERATION AND COLON OPERATORS
Matrices are the basic elements of the MATLAB environment. A matrix is two-dimensional
array consisting of m rows and n columns. Unusual cases are column vectors (n = 1) and row
vectors (m = 1).
Matrices are fundamental to MATLAB. Therefore, we need to become familiar with matrix
generation and manipulation. Matrices can be generated in several ways.
A vector is a special case of a matrix. The purpose of this section is to show how to create
vectors and matrices in MATLAB. The elements of vectors in MATLAB are enclosed by square
brackets and are separated by spaces or by commas for example this command can be used to
generate a vector I
Page | 12
Column vectors are created in an equivalent way, however, semicolon (;) must separate the
components of a column vector as seen in the screenshot below
On the other hand, a row vector is converted to a column vector using the transpose operator.
The transpose operation is denoted by an apostrophe or a single quote ‘ a screenshot is attached
below showing the working of this command
Furthermore, to access blocks of elements, we use MATLAB's colon notation (:). For example, to access
the first three elements of I, we write,
Page | 13
Or, all elements from the third through the last elements
Page | 14
6 MATRIX GENERATION AND LINEAR PROBLEM SOLVING
1 2 4
[1 1 2 ]
6 2 31
Type
Note that the use of semicolons (;) here is different from their use mentioned earlier to
suppress output or to write multiple commands in a single line. Once we have entered the matrix,
it is automatically stored and remembered in the Workspace. We can refer to it simply as matrix
A. We can then view a particular element in a matrix by specifying its location. We write,
>>A(2,1)
Shown in the screenshot attached below
Page | 15
Linear Spacing
On the other hand, there is a command to generate linearly spaced vectors: linspace. It
is similar to the colon operator (:) but gives direct control over the number of points.
For example,
y = linspace(a,b)
generates a row vector y of one hundred points linearly spaced between and including a and b.
y = linspace(a,b,n)
generates a row vector y of n points linearly spaced between and including a and b. This is
useful when we want to divide an interval into a number of subintervals of the same length.
For example,
Another example
>>A(2,:)
Ans = 1 1 2
Page | 16
The colon operator can also be used to extract a sub-matrix from a matrix A.
>>A(:,2:3)
To interchange rows 1 and 2 of A, use the vector of row indices together with the colon operator.
It is important to note that the colon operator (:) stands for all columns or all rows. To
create a vector version of matrix A, do the following
Page | 17
6.2.3 Deleting row or column
Page | 18
7 ARRAYS
MATLAB has two distinct types of arithmetic operations: matrix arithmetic operations
and array arithmetic operations. We have seen matrix arithmetic operations in the previously
If we have
Then >> C = A.*B produces another matrix C of the same size with elements cij = aijbij . For
example, using the same 3 by 3 matrices, shown on next page
Page | 19
To raise a scalar to a power, we use for example the command 10^2. If we want the operation to be
applied to each element of a matrix, we use .^2. For example, if we want to produce a new matrix whose
elements are the square of the elements of the matrix A, we enter
>> A.^2
The relations below summarize the above operations. To simplify, let's consider two vectors U
and V with elements U = [ui] and V = [vj ].
Page | 20
8 M- FILE SCRIPTS
8.1 Introduction
So far in these labs discussed in this manual , all the commands were executed in the Command
Window. The problem is that the commands entered in the Command Window cannot be saved
and executed again for several times. Therefore, a different way of executing repeatedly
commands with MATLAB is:
1. to create a file with a list of commands,
2. save the, and
3. run the file
If needed, corrections or changes can be made to the commands in the file. The files that
are used for this purpose are called script
Consider the example for Bisection method in MATLAB with the help of M-file scripts
To performs iterations to achieve some tolerance following script can be written in MATLAB
f = @ (x) x^4-16*x^3+72*x^2-96*x+24;
a= -.05;
b= 7;
n=100;
T=10^-5;
if f(a)*f(b)<0
for i=1:n
C = (a+b)/2;
RE=abs((C-b)/C);
fprintf('C%d=%.4f\n',i,C)
if abs(C-b)/C<T || abs(C-a)/C<T
break
end
if f(a)*f(C)<0
b = C;
else if f(b)*f(C)<0
a = C;
end
end
end
else disp('Bad roots')
end
Page | 21
The results generated from this mfile-script are as follows
The MATLAB editor is both a text editor specialized for creating M-files and a graphical
MATLAB debugger. The MATLAB editor has numerous menus for tasks such as saving,
viewing, and debugging. Because it performs some simple checks and also uses color to
differentiate between various elements of codes, this text editor is recommended as the tool of
choice for writing and editing M-files.
As a result, because scripts have some undesirable side-effects, it is better to code any
complicated applications using function M-file.
Page | 22
9 M-FILE FUNCTIONS
As mentioned earlier, functions are programs (or routines) that accept input arguments and return
output arguments. Each M-file function (or function or M-fille for short) has its own area of
workspace, separated from the MATLAB base workspace.
function f = factorial(n)
n=input ('enter desired number')
f=prod(1:n);
Page | 23
In addition, it is important to note that function name must begin with a letter and must be no
longer than the maximum of 63 characters. Furthermore, the name of the text file that you save
will consist of the function name with the extension .m. Thus, the above example file would be
factorial.m.
We have already seen the two first cases. Here, we will focus our attention on the third one.
In this case, the variable is defined in the script file. When the file is executed, the user is
prompted to assign a value to the variable in the command prompt. This is done by using
the input commands. Same bisection method as discussed previously is mentioned as an example
on the next page but with changes for the input
Page | 24
f = input(' desired function =');
a= input('Enter domain point a =');
b= input ('domain point b=');
n=input ('desired iterations to be performed=');
T= input ('enter desired tolerance to be achieved=');
if f(a)*f(b)<0
for i=1:n
c = (a+b)/2;
RE=abs((c-b)/c);
fprintf('c%d=%.4f\n',i,c)
if abs(c-b)/c<T || abs(c-a)/c<T
break
end
if f(a)*f(c)<0
b = c;
else if f(b)*f(c)<0
a = c;
end
end
end
else disp('Bad roots')
end
As discussed before, MATLAB automatically generates a display when commands are executed.
In addition to this automatic display, MATLAB has several commands that can be used to
generate displays or outputs.
Two commands that are frequently used to generate output are: disp and fprintf. The main
differences between these two commands can be summarized as follows
Page | 25
10 CONTROL FLOWS ( IF……END) LOOPS
10.1. Introduction
MATLAB is also a programming language. Like other computer programming languages,
MATLAB has some decision making structures for control of command execution. This decision
making or control flow structures include for loops, while loops, and if-else-end constructions.
Control flow structures are often used in script M-¯les and function M-files. By creating a file
with the extension .m, we can easily write and run programs. We do not need to compile the
program since MATLAB is an interpretative (not compiled) language. MATLAB has thousands
of functions, and you can add your own using m-files. MATLAB provides several tools that can
be used to control the flow of a program (script or function). In a simple program as shown in the
previous Chapter, the commands are executed one after the other. Here we introduce the flow
control structure that make possible to skip commands or to execute specific group of
commands.
MATLAB has four control flow structures: the if statement, the for loop, the while loop,
and the switch statement.
if expression
statements
end
Here is an example
Input
Page | 26
Output
Page | 27
11 FOR…..WHILE LOOPS
Usually, expression is a vector of the form i:s:j. A simple example of for loop is
It is a promising idea to indent the loops for readability, especially when they are nested. Note
that MATLAB editor does it automatically.
Multiple for loops can be nested, in which case indentation helps to improve the
readability.
while expression
statements
end
Page | 28
x=1
while x <= 10
x = 3*x
end
It is important to note that if the condition inside the looping is not well defined, the looping
will continue indefinitely. If this happens, we can stop the execution by pressing Ctrl-C.
The for while and for end examples were previously discussed for the bisection method in this
section I have attached a m script with the control flows for Newton Raphson method
f = @(x) x^3 - 4*x -5;
df = @(x) 3*(x^2) -4;
x0 = 2;
e = 0.000001;
n = 10;
if df(x0)~=0
for i=1:n
x1 = x0 - f(x0)/df(x0);
fprintf('x%d = %.16f\n',i,x1)
if abs(x1-x0)/x1<e
break
end
x0 = x1;
end
else
disp('newton method cannot run because derivative of given function is
zero');
end
Page | 29
12 POLYNOMIALS AND MATLAB
12.1 Introduction
Polynomials are mathematical expressions that are frequently used for problem solving and
modeling in science and engineering. In many cases an equation that is written in the process of
solving a problem is a polynomial, and the solution of the problem is the zero of the
polynomials. MATLAB has a wide selection of functions that are specifically designed for
handling polynomials.
Where P is a vector with coefficients of Polynomial and X is a number or a variable that has an
assigned value or a computable expression
X can also be a vector or a matrix . In such cases the polynomial is calculated for each element
and the answer is a vector or a matrix
For instance
A polynomial x^5 - 12.1*x^4 + 40.59*x^3 - 17.015*x^2 – 71.95*x + 35.88
This problem can be solved in command window with the commands shown on the next page
Page | 30
For x = 9
r= roots(p)
where r is a column vector with the roots of a polynomial and p is the row vector with the
coefficients of the polynomial
Page | 31
When roots of the polynomial are known the poly command can be used for determining the
coefficients of the polynomial, the command poly is
P=poly( r )
12.4.1. Addition
Two polynomials can be added (or subtracted) by adding the vectors of the coefficients. If the
polynomials are not of the same order (which means that the vectors of the coefficients are not of
the same length), the shorter vector has to be modified to be of the same length as the longer
vector by adding zeros (called padding)
As shown in MATLAB let p1 be the first polynomial and p2 be the second of same dimensions
Page | 32
Then
12.4.2. Multiplication
Two polynomials can be multiplied with the MATLAB built in function conv which has the
form
C = conv (a,b)
Where c is a vector of the coefficients of the polynomial that is the product of multiplication and
a,b are the vectors if the polynomials that are being multiplied
The two polynomials do not have the same order
Page | 33
Multiplication of three or more polynomials us done by using the conv function repeatedly
For example
12.4.3. Division
A polynomial can be divided by another polynomial with the Matlab builtin function deconv
which has the following form
[q,r] = deconv(u,v)
Where q is a vector with the coefficients of the quotient polynomial, r is a vector with the
coefficients of the remainder polynomial and u is the vector with the numerator polynomial and
v is a vector with the coefficients of the denominator polynomial
For example
Page | 34
13 CURVE FITTING
13.1. Introduction
Curve fitting, also called regression analysis, is a process of fitting a function to a set of data
points. The function can then be used as a mathematical model of the data. Since there are many
types of functions (linear, polynomial, power, expo- nential, etc.) curve fitting can be a
complicated process. Many times there is some idea of the type of function that might fit the
given data and the need is only to determine the coefficients of the function. In other situations,
where nothing is known about the data, it is possible to make different types of plots which
provide information about possible forms of functions that might give a good fit to the data. This
section describes some of the basic techniques for curve fitting, and the tools that MATLAB has
for this purpose.
Page | 35
Curve fitting with polynomials is done in MATLAB with the polyfit function, which uses the
least squares method. The basic form of the polyfit function is
p = polyfit (x,y,n)
where p is the vector of the coefficient of the polynomial that fits the data and x is a vector with
horizontal coordinate of the data points and y is a vector with vertical coordinate of the data
points and n is the degree of polynomial
Page | 36
14 INTERPOLATION
14.1. Introduction
Interpolation is estimation of values between data points. MATLAB has interpolation functions
that are based on polynomials, which are described in this section, and on Fourier
transformation, which are outside the scope of this book. In one- dimensional interpolation each
point has one independent variable (x) and one dependent variable (y). In two-dimensional
interpolation each point has two independent variables (x and y) and one dependent variable (z).
Page | 37
Which generates
Page | 38
15 THREE DIMENSIONAL PLOTS
15.1 Introduction
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 oth- ers. The plots can also be formatted to
have a specific appearance and special effects. Many of the three-dimensional plotting features
are described in this chap- ter. Additional information can be found in the Help Window under
Plotting and Data Visualization.
1. The three vectors with the coordinates of the data points must have the same number
of elements.
2. The line specifiers, properties, and property values are the same as in 2-D plots
For example
if the coordinates x, y, and z are given as a function of the parameter r by
x = sqrt(tsint(st))
y= sqrt(tcos(2t))
z= 0.5t
Page | 39
A plot of the points for 0≤t≤6pi can be produced by the following script file:
Page | 40
Page | 41
CONTENTS
1 Introduction and Installation ................................................................................................................ 1
2 MATLAB as a Calculator and Hierarchy of arithmetic operations ........................................................ 5
3 Plotting of graphs .................................................................................................................................. 8
4 Multiple Functional Graphs with axis, legends................................................................................... 10
5 Vector Generation and Colon operators............................................................................................. 12
6 Matrix generation and Linear Problem Solving .................................................................................. 15
7 Arrays.................................................................................................................................................. 19
8 M- File Scripts .................................................................................................................................... 21
9 M-File Functions ................................................................................................................................. 23
10 Control Flows ( if……end) loops ................................................................................................... 26
11 For…..while loops .......................................................................................................................... 28
12 Polynomials and MATLAB ............................................................................................................... 30
13 Curve Fitting .................................................................................................................................... 35
14 Interpolation ................................................................................................................................... 37
15 Three Dimensional Plots ................................................................................................................. 39