0% found this document useful (0 votes)
76 views43 pages

Introduction To Mat Lab: First Year Chemical Engineering Department

This document introduces the basics of MATLAB. It discusses that MATLAB is a programming language for technical computing. It can be used to perform matrix operations, data analysis, and visualization. The document then provides an overview of basic MATLAB commands and functions for arithmetic, plotting, solving equations, and other common tasks in engineering. It also describes how to start and quit a MATLAB session.

Uploaded by

Douda Samih
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
76 views43 pages

Introduction To Mat Lab: First Year Chemical Engineering Department

This document introduces the basics of MATLAB. It discusses that MATLAB is a programming language for technical computing. It can be used to perform matrix operations, data analysis, and visualization. The document then provides an overview of basic MATLAB commands and functions for arithmetic, plotting, solving equations, and other common tasks in engineering. It also describes how to start and quit a MATLAB session.

Uploaded by

Douda Samih
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 43

Introduction to Mat Lab

First Year
Chemical Engineering Department

Fall 2016
PRINCIPLES AND BASIC FEATURES OF MATLAB
In this part we will introduce the basic MATLAB commands and their use. The approach is to
illustrate the use of the commands by examples. Because in this section we will deal with
fundamentals, additional examples of the use of many of these commands will take place as
we proceed throughout the course. Although many examples are provided here, no attempt is
made to cover every possible use or variant of the commands. For additional information on
the individual MATLAB commands, you can refer to the HELP of the MATLAB command
window.
1 Getting Started
1.1 What is MATLAB?
MATLAB is high-performance language for technical computing. It began as a "MATrix
LABoratory" program, intended to provide interactive access to the libraries Linpack and
Eispack. These are carefully tested, high-quality programming packages for solving linear
equations and eigenvalue problems. The basic data element of MATLAB is an array that does
not require dimensioning. This allows the solution of many technical computing problems,
especially those with matrix and vector formulations, in a fraction of the time it would take to
write a program in a scalar non interactive language such as C, FORTRAN or Pascal. More
capabilities have been added as time has passed, many more commands, and very fine
graphics capabilities.
MATLAB integrates computation, visualization, and programming in an easy-to-use
environment where problems and solutions are expressed in a familiar mathematical notation.
Typical uses include:
• Mathematics and computation
• Algorithm development
• Modeling, simulation, and prototyping
• Data analysis, exploration, and visualization
• Scientific and engineering graphics
• Application development, including Graphical User Interface building
In university environments, it is the standard instructional tool for introductory and
advanced courses in mathematics, engineering and science. In industry, MATLAB is the tool
of choice for high productivity research, development and analysis.

1.2 Information on the Internet


There are pointers to information on the Internet that you may find helpful. Be aware,
though, that because these resources are maintained at remote sites, the information may not
always apply to you, and may not always be available.
The Mathworks Incorporation, the company that produced MATLAB, has its own web site
at www.mathworks.com. This site presents much of the MATLAB demo, MATLAB
conference proceedings and contact information for The Mathworks, and lots more. The
Mathworks Incorporation continually updates this site, so the information may change from
day to day.

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
1
A searchable online copy of the full MATLAB Reference Guide including all MATLAB
commands and function calls with illustrations and examples may be found in the following
site: http://spicerack.sr.unh.edu/~mathadm/tutorial/software/matlab/
Many of the resources on MATLAB including tutorials, notes and applications may be
found in http://www.indiana.edu/~statmath/math/matlab/
An excellent documentation with step-by-step instructions and examples is available
through the MATLAB Primer on http://www.cis.yale.edu/secf/software/matlab/matlab-
primer.html
Many of the texts on the applications of MATLAB in engineering disciplines that appeared
during the past two years are listed in: http://www.prenhall.com/list_ac/searches/EG0131.html
1.3 Scope and Objective
In this course we will learn how to use MATLAB to solve most of the mathematical
problems encountered in the various Chemical Engineering sciences. This will proceed
through the coverage of the following:
➢ Mathematical operations
➢ Polynomial operations
➢ Solving Algebraic equations
➢ Differentiation and Integration
➢ 2- and 3-D plotting
These notes are based on the assumption that you do not know (or did not receive a formal
exposure to) MATLAB. For those of you who are comfortable with MATLAB please
challenge yourself by pushing the extent of your knowledge.

1.4 Starting and Quitting a Session


MATLAB is started by clicking the START of the Win95, then clicking on the MATLAB
icon from the PROGRAMS group. You can double-click the short-cut icon of MATLAB if it
exists on your desktop. Once invoked, MATLAB will clear the screen, provide some
introductory remarks, such as:
Using Toolbox Path Cache. Type "help toolbox_path_cache" for more info.

To get started, select "MATLAB Help" from the Help menu.


>> and produces the MATLAB prompt: " >>"
If you've never seen MATLAB in action before, type demo at the MATLAB >> prompt:
>> demo
This puts you into the MATLAB Expo, which demonstrates, with color and animation,
MATLAB, SIMULINK, and the MATLAB Application Toolboxes. From the MATLAB Expo
Main Map, you can get introductory information about, or "visit" the various demo modules.
To skip the Welcome to the MATLAB Expo window, and open directly in the MATLAB
Expo Main Map, type expomap at the MATLAB >> prompt:
>> expomap
From the MATLAB screen, select demos that introduce how the program handles matrices,
numerics, visualization, and language.

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
2
To exit from MATLAB type: quit or exit at the MATLAB prompt, followed by either the
“enter”, “return” or “carriage return” key. However, you can alternatively pull down the
file menu and click on ExitMATLAB.
From here on, we will not repeat the instruction to depress the “enter”, “return” or
“carriage return” key after a MATLAB command is typed. It is understood that you must do
this to execute a command; i.e., MATLAB does not respond to a line of commands until one
of those keys is depressed.

2 Simple Mathematics and Fundamental Expressions


Working in the MATLAB environment is straightforward because most commands are
entered as you would write them mathematically. MATLAB is an expression language; the
expressions you type are interpreted and evaluated. MATLAB statements are usually of the
form
variable = expression, or simply
expression
Expressions are usually composed from operators, functions, and variable names. Evaluation
of the expression produces a matrix, which is then displayed on the screen and assigned to the
variable for future use. If the variable name and = sign are omitted, a variable ans (for answer)
is automatically created to which the result is assigned.

For example, entering the following simple expression

>> a = 4/3

yields the MATLAB response

a=
1.3333
and assigns to variable a the value of 4 divided by 3. In general, it is a good idea to use
appropriate and memorable names for variables. MATLAB recognizes the first 19 characters
of a variable name and requires only that the first character in a variable name be a letter.
MATLAB is case sensitive, so, for example, a and A are two different variables. All
MATLAB commands are written in lowercase letters.
If you do not care to create a new variable but want to know the value of an expression,
you can type the expression by itself, e.g.,
>> 4/3
which yields
ans =
1.3333

where ans is a MATLAB-generated dummy variable that stands for “answer”.

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
3
If the last character of a statement is a semicolon, the printing is suppressed, but the
assignment is carried out. This is essential in suppressing unwanted printing of intermediate
results. In other words, if you prefer to create a new variable but do not want to see the
MATLAB response, type a semicolon at the end of the expression. For example,
>> b = 4+7;
will create a new variable b whose value is 11, but MATLAB will not display the value of b.
Moreover, you can check the value of a variable at any time by entering the variable name at
the prompt as follows:
>> b
b=
11
This is an extremely useful feature, especially when you are debugging a sequence of
expressions.
Expressions, as opposed to variables, can be made up of sequences of numbers, operators,
functions and variables that have been previously defined. For example, since a and b have
already been defined, we can do the following:
>> c = a*(b-1)
c =
13.3333
Note that blank spaces can be used to improve readability. If you are typing in an expression
that does not fit on one line, use ellipsis dots (three or more periods) at the end of the line and
continue typing on the next line, e.g.,
>> p = 1 + 2 + …
3 + 4 + 6;
Arithmetic operators are the same as those commonly used, except that * represents
multiplication, \ performs left division and ^ is the power operator. For example typing
>> p^2

causes MATLAB to return

ans =
256

Left division is defined like right division except that the order of dividend and divisor is
swapped, i.e., a\b = (a) -1 b. For a and b scalars, a\b = b/a; in other words, the division is
carried from left to right; for example
>> y = 6\3
returns
y=
0.5000

and not 2.000, as if we were dividing 6 by 3 !

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
4
MATLAB performs operations in the following order:

^ power operator
* multiplication
/ and \ division
+ addition
- subtraction
Precedence of like operators proceeds from left to right, but parentheses can be used to affect
the order of operation. The following three examples illustrate these precedence rules:
>> 1+2^3/4*2
ans =
5
>> 1+2^3/(4*2)
ans =
2
>> (1+2)^3/(4*2)
ans =
3.3750
MATLAB has several predefined variables. These include i and j , both of which denote −1
. Using i or j to generate complex numbers can be very convenient. However, predefined
variables can be overwritten, so be careful using the variable names i and j to mean other than
−1 . For example, many people use i and j as indices for vectors and matrices. As a result,
they often use i or j this way in MATLAB, e.g., by entering i=1 to reassign i to be equal to 1
instead of −1 . It is recommended that you avoid changing the values of the predefined
variables. However, if you choose to do so, it is good practice to reset them after use with the
clear command. For example, to retrieve the predefined value of −1 for i type clear i.
Other predefined variables are
pi, which stands for 
Inf, which stands for 
NaN, which stands for not a number (e.g. 0/0)
MATLAB will return  or NaN when you divide by zero. When this happens, execution of
your calculation will not be terminated; however, MATLAB will warn you of the problem:
>> d = 4/0
warning : Divide by zero
d=

Similarly, MATLAB returns NaN when you attempt to perform certain undefined calculations
e.g.,
>> dd = Inf/Inf
dd =
NaN
Note that in this case no warning is given. In general, you should try to avoid generating Inf
and NaN because they can lead meaningless results in your calculations.
Alexandria University- Faculty of Engineering
Chemical Engineering Department
First Year -Summer 2021
5
3 The MATLAB Workspace and Saving Sessions
When you first start running MATLAB, it is case-sensitive. This means that MATLAB
distinguishes between uppercase and lowercase variable and function names. So, you can
safely have two separate variables named g and G.
MATLAB allows you to clear the command (text) window. The clc command clears the
command window, and give you a fresh >> prompt. The clf command clears the graphics
window and leaves it blank. (we will talk about that later on).If the clear command is followed
by some variables, these variables are erased. If you type
>> clear a b c
only the variables a, b and c will be cleared.
The who command displays the names of all your variables available in the MATLAB
workspace. The whos command gives you the names of all the variables, along with
information about each variable's size, number of elements, number of bytes, density, and
whether the variable is complex..
4 Number Display Format
While all computations in MATLAB are performed in double precision, the format of the
displayed output can be controlled by the following commands:
>> format short fixed point with 4 decimal places (the default)
>> format long fixed point with 14 decimal place
>> format short e scientific notation with 4 decimal places
>> format long e scientific notation with 15 decimal places
>> format bank Fixed format for currency (money).
>> format compact Suppress extra line-feeds.
>> format loose Puts the extra line-feeds back in.
>> format Default. (Same as short).
>> format rat Fraction

Once invoked, the chosen format remains in effect until changed.


The command format compact will suppress most blank lines allowing more information to
be placed on the screen or page. It is independent of the other format commands.
For example, to see a five-digit floating point display (scientific notation) enter
>> format short e
The new display will look as follows:
>> c
c =
1.3333e+01
Typing format returns the display to the default.
It is also important to know, however, that the permanent variable eps (epsilon) gives
the machine precision about 10-16 on most machines. It is useful in determining tolerances for
convergence of iterative processes.

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
6
5 Mathematical Functions
To make life easier, MATLAB includes many standard functions that are easily
incorporated into expressions. Each function is a block of code that accomplishes a specific
task. MATLAB contains all of the standard functions such as sin, cos, log, exp, sqrt, as well as
many others. A pair of parentheses follows each function, which includes the so-called
argument(s) of the function. For example:
>> sin(pi/4)
ans =
0.7071
In this example pi/4 is the argument of the sin function.
One of the simplest functions have one input argument and one output argument, such as
the sqrt function, which returns the square root of the input argument. The input argument
goes inside a pair of parentheses. For example,
>> y = sqrt(1+4*i)
returns
y=
1.6005+ 1.2496i
Notice the way in which the complex number 1 + 4i was displayed.
Examples for the most commonly used elementary and trigonometric functions include:

Elementary Functions Trigonometric Functions


abs absolute value sin sine
sqrt square root cos cosine
real real part tan tangent
imag imaginary part asin arcsine
conj complex conjugate acos arccosine
round round to nearest integer atan arctangent
fix round toward zero sinh hyperbolic sine
exp exponential base e cosh hyperbolic cosine
log natural logarithm tanh hyperbolic tangent
log10 log base 10 asinh hyperbolic arcsine
acosh hyperbolic arccosine
atanh hyperbolic arctangent
6 On-Line Help
We cannot learn MATLAB from a list of its variables, operators and functions. So rather
than listing the remaining simple MATLAB functions, we discuss how you can explore them
further using the help command. MATLAB has an online help facility. This is the easiest
way to find out more about the MATLAB commands. To determine the usage of any function,
type help [function name] at the MATLAB command window.
A dictionary becomes very helpful once you know some of the basics of a language.
Entering help by itself at the MATLAB prompt displays a list of MATLAB help topics. These

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
7
include for example, “ops - operators and special characters”, “elfun - Elementary math
functions” and “plotxy - Two-dimensional graphics”. To get more information and lists of
MATLAB functions for a particular topic, type help followed by the name of the topic. For
instance, typing help elfun will give a list of elementary math functions categorized as
trigonometric, exponential, complex and numeric. This list will give a brief description of each
function. To get more information about an individual command, type help followed by the
command name.
These lists are easy to use even if you want to perform an operation using MATLAB but
do not know which command to use. Most of the MATLAB commands have fairly mnemonic
names, so skimming the topics and lists until you find some likely candidates usually works.
You can also use the command lookfor to search through the lists using a keyword.
Suppose you want to compute e-1+3i. Scanning the list of MATLAB topics for the
appropriate exponential command leads you to “elfun” for elementary functions. Scanning the
list of elementary functions clearly leads you to the command exp. To find out more about
exp, type
>>help exp
MATLAB returns a detailed description of exp, which indicates that exp is the command you
needed.

When using the help facility, you will find that MATLAB may return more information
than can fit on your command window. To control MATLAB output so that you can view it
page by page, use the more command. Typing more on enables output control. In this case,
MATLAB will display only one page of output.. To see the next line of output hit the return
key. To advance to next page of output hit the space bar. Hitting the “q” key will stop the
outputting and return you to the MATLAB prompt. Type more off to disable paged output.
This controlled output feature is also very useful when you want to view large vectors or
matrices page by page.
The demo command launches an online preview or demo of MATLAB's capabilities.
However, parts of the demo depend on optional additions or toolboxes, not all of these will
have been installed on the system you are using. The demos use both the Figure and
Command windows, you will have to move the Command and Figure windows around
periodically to be able to view the information that is in each of them. In addition, some of the
demos will pause and await a key press in the Command window. If no other method is
available, you can use a CTRL-C to terminate a MATLAB demo or other script. It will
generate a few error messages, but it will get you back to the MATLAB command prompt.
While the demo shows off some of the more powerful features of MATLAB, intro gives
several detailed examples of the basic features and techniques of MATLAB. Intro also makes
greater use of the Command window to display explanations of what it is doing.
Info gives a brief overview of MATLAB and The Mathworks Inc., as well as
information on subscribing to the MATLAB newsletter.

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
8
7 M-Files
MATLAB statements can be prepared with any text editor, and stored in a file for later
use. MATLAB can then execute this sequence of statements. The file is referred to as an "M-
file". Each M-file should have a name that ends in .m . Much of your work with MATLAB
will be in creating and refining M-files. It is much easier to use M-files than to enter
commands line by line at the MATLAB prompt. Writing m-files will make you much more
productive. We will use the NOTEPAD of Windows'95 to create M-files. There are two types
of M-files: script files and function files.
7.1 Script Files
A script file is a regular text file that contains a series of MATLAB commands written
just as you would enter them in the MATLAB environment. Statements that begin with a %
are considered to be comments and are ignored by MATLAB. Pulling down the file menu
from the MATLAB command window creates a script file. You can either create a new file or
open an existing one. The commands in the script file are executed in the MATLAB
environment simply by entering the name of the script file without the .m . For example,
suppose the text file areacir.m contains the following statements:
% areacir.m: example m-file to
% compute the area and circumference of a circle
r = 2.5;
area = pi*r^2
circum=2*pi*r

Then typing areacir at the MATLAB prompt will yield the following MATLAB response:
area =
19.6349
circum =
15.7079
which are the area and circumference of a circle of a radius 2.5. Entering help areacir gives
you back the text in the comment lines at the beginning of the file:
% areacir.m: example m-file to
% compute the area and circumference of a circle
It should be obvious that it is very desirable to include at least some brief comment as a header
to each m-file you create.
In a Windows environment you can view the text editor window simultaneously with the
MATLAB command window. This means you can use the two windows to edit a script file
repeatedly and run it in MATLAB without ever quitting MATLAB.
Because MATLAB treats script files exactly as if they are command sequences, all
variables currently in the MATLAB workspace can be used by the script file commands, and
similarly all variables created by the script file are available for use after the script file has
been run. For example after running areacir.m we can examine area as follows:
>> area
area =
19.6349

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
9
When any script file name is entered at the MATLAB prompt, MATLAB searches in
several places to find the corresponding file. Suppose you have entered sample in the hope of
running a script file you have written and named sample.m . If the file is not there, MATLAB
looks in the current directory for the file sample.m. If the file is not there, MATLAB then
looks in the directories specified by the environment variable MATLABPATH. Consequently,
to avoid confusion, make sure your M-files do not have the same name as previously defined
variables, M-files or MATLAB functions. Also be aware that MATLAB will not find your file
at all if it is neither in the current directory nor in a directory specified in MATLABPATH.
On some versions of MATLAB, the script file startup.m is run automatically when
MATLAB is invoked. Therefore, you might want to create or edit the file startup.m, if it
exists, to include commands that you would like running every time you invoke MATLAB.
For example, you might include the command format short e to set the numerical display
automatically.
7.2 Function Files
Function files provide extensibility to MATLAB. You can create new functions specific
to your problem, which will then have the same status as other MATLAB functions. Function
definitions are stored in files with the name function-name.m. For example for a function
returning one variable, the first line of a function definition must start with the word function
and can be of the form:
function variable = f(argument1, argument2,...)
This specifies the name of the function and its input arguments.
For example, suppose we would like to create a function called "circlarea", which calculates
the area of a circle having any given radius. The M-file will appear as follows:
% This function calculates the area of a circle
% The arguments x, and y represent the radius and
% the area of the circle, respectively
function y = f(x)
y=pi*x^2;
We can now invoke the function called circlarea in the same way as we do for commonly
used MATLAB functions. Therefore, in order to find the area of a circle with a radius 6.5, we
can type the following:
>> A = circlarea (6.5)
and this is what we get:
A=
132.7323
Note that whereas a script file name can only be entered by itself at the MATLAB prompt
(or as a line in another script file), a function can be called when needed. For example, if p is a
variable that has been specified, you could use circlarea in an expression such as differ = 100
- circlarea(p). Also try help circlarea to confirm implementation of the help command. A
function does not contain any variable equivalence, and it is all symbolic in nature; not like a

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
10
script file. This is expected, however, since a function will be of a more general nature and use
when compared to a script file.
The second major difference between function files and script files is that the variables
generated in function files are local to the function, whereas variables in script files are global.
This means that the variables y and x in our example are not available after the function has
been used. Therefore, if you enter z = circlarea (p), only p and z are available after running.

If you want the function to return more than one value, let's say two values, the first line
of the function definition must start with the word function and can be of the form:
function [variable1 variable2] = f(argument1, argument2,...)
For example suppose we want to create the function called "circle", which returns the area and
the perimeter of a circle with any given radius. The M-file for this function will be:
% This function calculates the area of a circle and its perimeter
% The arguments x, y and p represent the radius, the area and the
% perimeter of the circle, respectively
function [y,p] = f(x)
y = pi*x^2;
p = 2*pi*x;
We can now invoke the function called circle in the same way as we do for commonly used
MATLAB functions. Therefore, in order to find the area of a circle with a radius 6.5, and its
perimeter we can type the following:
[Area Perim]=circle (6.5)
In this case we get
Area =
132.7323

Perim =
40.8407

7.3 Text Strings and Input


Text strings are entered into MATLAB surrounded by single quotes. For example,
s = 'This is a test'
assigns the given text string to the variable s.

Text strings can be displayed with the function disp. For example:
disp('this message is hereby displayed')
The blanks command enters a string of blanks, and is used with the disp command;
blanks(n) is a string of n blanks. For example:
disp(['xxx' blanks(20) 'yyy'])
will give
xxx yyy (Notice the 20 blank spaces between xxx and yyy)

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
11
and typing:
disp(blanks(n)')
moves the cursor down n lines.

In an M-file the user can be prompted to interactively enter input data with the function
input. When, for example, the statement
number = input('Enter the number of students: ')
is encountered, the prompt message is displayed and execution pauses while the user keys in
the input data. Upon pressing the return key, the data is assigned to the variable number and
execution resumes.
8 Vectors and Vector Operations
A vector is a one dimensional array. Let's start off by creating something simple. Enter each
element of the vector (separated by a space) between square brackets, and set it equal to a
variable. For example, to create the vector a, enter into the MATLAB command window:
>> a = [1 2 3 4 5 6 9 8 7]
MATLAB should return:
a=
1 2 3 4 5 6 9 8 7
Let's say you want to create a vector with elements between 0 and 20 evenly spaced in
increments of 2 (this method is frequently used to create a time vector): you can type
>> t = 0:2:20
MATLAB should return:
t=
0 2 4 6 8 10 12 14 16 18 20
Alternatively, the MATLAB function linspace(x1, x2) generates a row vector of 100 linearly
equally spaced points between x1 and x2, while the function linspace(x1, x2, n) generates n
points between x1 and x2. Suppose we want to generate a vector with 10 elements between 18
and 180:
>> linspace(18,180,10)
ans =
18 36 54 72 90 108 126 144 162 180
(Use the MATLAB Help to see what the function LOGSPACE will do !)
Manipulating vectors is almost as easy as creating them. First, suppose you would like to add
2 to each of the elements in vector a. The equation for that looks like:
>> b = a + 2
MATLAB should return:
b=
3 4 5 6 7 8 11 10 9

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
12
Now suppose, you would like to add two vectors together. If the two vectors are the same
length, it is easy. Simply add the two as shown below:
>> c = a + b
MATLAB should return:
c=
4 6 8 10 12 14 20 18 16

Subtraction of vectors of the same length works exactly the same way.

Vectors are not necessarily created form integer-spaced elements.


>> knew = 1:0.25:2
knew =
1.000 1.2500 1.5000 1.7500 2.0000

You can also generate a vector, by entering its elements as expressions:


>> v = [sin(pi/3) -7^3 k+1]
v =
0.8660 -343.000 2.3333

MATLAB has a series of functions operating on vectors. Some of these functions are:
max, min, sum, prod, mean, sort.

For example if we type max(v), MATLAB will return 2.3330; typing mean(v), will return -
113.2670, which is the average values of all three elements of the vector v.

MATLAB can also convert a row vector to a column vector. Upon typing:
>> v'
MATLAB will give:
ans =
0.8660
-343.0000
2.3330

One important aspect of MATLAB is that it can perform element-to-element operations.


Multiplying two vectors element by element is a little different. Since we are always dealing
with matrices, even if we have one single number (it will be a 1x1 matrix), the * symbol is
defined as matrix multiplication when used on any two variables, whether or not they are
matrices. Use " .* " to specify element-wise multiplication. So, suppose you want to get the
product of the corresponding elements of the two vectors a and b, if you simply type a*b
MATLAB will respond with an error message:
?? Error using ==> *
Inner matrix dimensions must agree.
Alexandria University- Faculty of Engineering
Chemical Engineering Department
First Year -Summer 2021
13
In this case we will have to type:
>> a.*b
and MATLAB will return:
ans =
3 8 15 24 35 48 99 80 63
We can perform the exponentiation of a by typing a.^2, and this will return:
ans =
1 4 9 16 25 36 81 64 49
Dividing a by b, can be accomplished using a./b
In other words, when dealing with arrays of numbers, other than matrices, we always perform
element-to-element operation. This can be accomplished by preceding the mathematical
operator with a dot.
It is important to realize that elementary functions when operating on a vector, will also yield
a vector. For example, if we look for log(a), we will find that it is also a one-dimensional
array, with the same number of elements as the vector a:
ans =
0 0.6931 1.0986 1.3863 1.6094 1.7918 2.1972 2.0794 1.9459

9 Polynomials
Polynomials are described in MATLAB by row vectors with elements that are equal to
the polynomial coefficients in order of decreasing powers . For example, to enter the second
degree polynomial p = s2 + 5s + 6 type p = [1 5 6]. The vector p has three elements. Therefore,
MATLAB can interpret a vector of length n+1 as an nth order polynomial. Zero coefficients
must be included to avoid confusion; i.e., q = s3 + 5s + 6 is entered as p = [1 0 5 6]. A
polynomial can be evaluated using the polyval command. For example:
>> polyval (p,1)
ans =
12

gives the value of the polynomial p at s = 1. The roots command is a convenient way to find
the roots of a polynomial, e.g.:
>> r = roots(p)
r =
-3
-2

Similarly, you can construct polynomials from roots,


>> t = poly([-4 -5])
t =
1 9 20

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
14
The command conv multiplies two polynomials and deconv divides two polynomials.
The script file polyroly.m shown below illustrates these commands in use.
% polyroly
% Example of multiplying and dividing polynomials.
f1 = [1 3 2]; % f1 = s^2 + 3s + 2
f2 = [1 3]; % f2 = s + 3
f3 = [1 2]; % f3 = s + 2
g = conv(f1,f2); % g = (s^2 + 3s + 2)(s + 3)
h = deconv(g,f3) % h = (s^2 + 3s + 2)(s + 3)/(s + 2)
Note the use of % to begin a comment. Everything following % on a line is ignored by
MATLAB. Typing polyroly at the MATLAB prompt yields the following response:
h=
1 4 3
In this example f3 divides g with no remainder. In general, when used with one output
argument, the command deconv will return only the quotient even if the remainder is nonzero.
However, if two output arguments are specified as shown below, MATLAB will return both
the quotient q and the remainder r:
>> [q,r] = deconv(f1,f2)
q=
1 0
r=
0 0 2
The MATLAB function polyder(p) returns the derivative of the polynomial whose
coefficients are the elements of vector p:
>> p = [1 5 6];
>> polyder(p)
ans =
2 5
10 Symbolic Mathematics
In what followed we learned how MATLAB can be used like a very powerful,
programmable calculator. It takes numbers (123.6/6.9) or variables (y = [10 20 30]) and acts
upon them using the commands and functions we specify (Z = sin(pi/4) or q = log10(45/8)) to
produce numerical results. What basic MATLAB lacks is the ability to manipulate
mathematical expressions without actually using numbers. Basic MATLAB must have
numbers to work with. For example, asking for the sine of a variable that has not been
assigned a numerical value, results in:
>> y = sin(x) % Take the sine of x
??? Undefined function or variable x.

The commands and functions introduced in this section can change all that. Now we can tell
MATLAB to manipulate expressions that let you compute with mathematical symbols rather
than numbers. This process is often called symbolic math. Here are some examples of
symbolic expressions:
Alexandria University- Faculty of Engineering
Chemical Engineering Department
First Year -Summer 2021
15
d x2
cos(x2) 3x2 + 5x - 1 v= 2x
2
f=  dx
dx 1− x
The Symbolic Math Toolbox is a collection of tools (functions) for MATLAB that are used for
manipulating and solving symbolic expressions. There are tools to combine, simplify,
differentiate, integrate and solve algebraic and differential equations. Other tools are used in
liner algebra to derive exact results for inverses, determinants and other properties and
characteristics of symbolic matrices without the error introduced by numerical computations.

10.1 Symbolic Expressions


These are character strings, or arrays of character strings, that represent numbers,
functions, operators and variables. The variables are not required to have predetermined
values. Symbolic equations are symbolic expressions containing an equal sign. Symbolic
arithmetic is the practice of solving these symbolic equations by applying known rules and
identities to the given symbols, exactly the way we learned to solve them in algebra and
calculus. Symbolic matrices are arrays whose elements are symbolic expressions
Here are some examples of symbolic expressions along with their MATALB
equivalents:

Symbolic Expression MATLAB Representation

1
'1/(2*x^n)'
2x n
1
y= y = '1/sqrt(2*x)'
2x

cos (x2) - sin(2x) 'cos(x^2) - sin(2*x)'

M = a b  M = sym('[a,b;c,d]')
c d 

d  x2 
G=  
dx  log x 
G = diff('x^2/log(x)')

b
x3
f= 
a 1− x
dx f = int('x^3/sqrt(1-x)','a','b')

Symbolic expressions without variables are called symbolic constants.


you will have to type the following line before attempting to execute any of the symbolic
operations:
>> syms x u

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
16
In other words, you will have to explicitly declare all symbolic variables used in symbolic
expressions.
If you have defined, for example, two symbolic expressions, f and g according to:
>> f='1/x'; g='sin(u)':
Alternatively, you can use the sym command, to create each symbolic expression:
>> f=sym('1/x'); g=sym('sin(u)');
In this case you will not have to declare the symbols x and u, and you can perform any
symbolic operation directly on any expressions including these symbolic variables.
All symbolic functions (with a few exceptions discussed later) act on symbolic expressions
and symbolic arrays, and return symbolic expressions or arrays. The result may sometimes
look like a number, but it is a symbolic expression internally represented by a character string.
We discussed earlier how to use the isstr function to find out whether or not it is a string.
A number of standard algebraic operations can be performed on symbolic expressions.
The functions symadd, symsub, symmul and symdiv, add, subtract, multiply and divide two
expressions, and sympow raises one expression to the power of another. For example, given
the two functions:
f = 2x2 + 3x - 5 g = x2 - x + 7
>> f = '2*x^2+3*x-5' %define the symbolic expression
f=
2*x^2+3*x-5
>> g = 'x^2-x+7'
g=
x^2-x+7
>> symadd(f,g) % find an expression for f + g
ans =
3*x^2+2*x+2
>> symsub(f,g) % find an expression for f - g
ans =
x^2+4*x-12
>> symmul(f,g) % find an expression for f * g
ans =
(2*x^2+3*x-5) * (x^2-x+7)
>> symdiv(f,g) % find an expression for f / g
ans =
(2*x^2+3*x-5) / (x^2-x+7)
>> sympow(f,3) %find an expression for f 3
ans =
(2*x^2+3*x-5)^3
MATLAB has the capability to perform more advanced operations on symbolic expressions.
The compose function combines f(x) and g(x) into f(g(x)). The finverse function finds the

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
17
functional invers of an expression, and the symsum finds the symbolic summation of an
expression.
Given the expressions:
1 1
f= g =sin(x) h= k = sin(v)
1 + x2 1 + u2

>> f = '1/(1+x^2)';g = 'sin(x)'; h = '1/(1+u^2)'; k = 'sin(v)';


>> compose(f,g) % find an expression for f(g(x))
ans =
1/(1+sin(x)^2)
>> compose (g,f) % find an expression for g(f(x))
ans =
sin(1/(x^2+1))

compose can also be used on functions that have different independent variables:
>> compose(h,k,'u','v') % given h(u), k(v), find h(k(v))
ans =
1/(1+sin(v)^2)

The functional inverse of an expression, say f(x), is the expression g(x) that satisfies the
condition g(f(x)) = x. For example, the functional inverse of ex is ln(x), since ln(ex) = x. The
functional inverse of sin(x) is arcsine(x). The finverse function returns the functional inverse
of an expression, and warns you if the result is not unique.
>> finverse('1/x') % inverse of 1/x is 1/x, since '1/(1/x) = x'
ans =
1/x
>> finverse('x^2') %g(x^2) = x has more than one solution
Warning: finverse (x^2) is not unique
ans =
x^(1/2)
>> finverse ('a*x+b') % find the solution to 'g(f(x)) = x'
ans =
-(b-x)/a
>> finverse('a*b+c*d-a*z','a') % find the solution to 'g(f(a)) = a'
ans =
-(c*d-a)/(b-z)
Symbolic expressions can be converted to numeric values and back again. MATLAB has
some very few symbolic functions that can return numeric values. Notice, however, that some
symbolic functions automatically convert a number into its symbolic representation if it is one
of a number of arguments to the function. (Refer to the symop discussed earlier).

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
18
The sym function can take a numeric argument and convert it into a symbolic representation.
The numeric function does the opposite. It converts a symbolic constant (a symbolic
expression with no variables) to a numeric value.
>> phi = '(1+sqrt(5))/2';
>> numeric (phi) % convert to a numeric value

ans =
1.6180
The eval function passes a character string to MATLAB to evaluate. Therefore, eval is another
function that can be used to convert a symbolic constant into a number, or to evaluate an
expression:
>> eval(phi) % execute the string '(1+sqrt(5))/2'
ans =
1.6180
We have already worked with polynomials in MATLAB, using vectors whose elements are
the coefficients of the polynomials. The symbolic function sym2poly converts a symbolic
polynomial to its MATLAB equivalent coefficient vector. The function poly2sym does the
reverse, and permits the specification of the variable to use in the resulting expression.
>> f = '2*x^2+x^3-3*x+5' % f is the symbolic polynomial
f=
2*x^2+x^3-3*x+5
>> n=sym2poly(f) %extract the coefficient vector
n=
1 2 -3 5
>> poly2sym(n) %recreate the polynomial in x
ans =
2*x^2+x^3-3*x+5
>> poly2sym(n,'s') %recreate the polynomial in s
ans =
s^3+2*s^2-3*s+5
10.2 SOLVE Symbolic solution of algebraic equations.
SOLVE('eqn1','eqn2',...,'eqnN')
SOLVE('eqn1','eqn2',...,'eqnN','var1,var2,...,varN')
SOLVE('eqn1','eqn2',...,'eqnN','var1','var2',...'varN')

The eqns are symbolic expressions or strings specifying equations. The vars are symbolic
variables or strings specifying the unknown variables. SOLVE seeks zeros of the expressions
or solutions of the equations.

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
19
If not specified, the unknowns in the system are determined by FINDSYM. If no analytical
solution is found and the number of equations equals the number of dependent variables, a
numeric solution is attempted.

Three different types of output are possible. For one equation and one output, the resulting
solution is returned, with multiple solutions to a nonlinear equation in a symbolic vector. For
several equations and an equal number of outputs, the results are sorted in lexicographic order
and assigned to the outputs. For several equations and a single output, a structure containing
the solutions is returned.

Examples:

solve('p*sin(x) = r') chooses 'x' as the unknown and returns

ans =
asin(r/p)

[x,y] = solve('x^2 + x*y + y = 3','x^2 - 4*x + 3 = 0') returns

x=
[ 1]
[ 3]

y=
[ 1]
[ -3/2]

S = solve('x^2*y^2 - 2*x - 1 = 0','x^2 - y^2 - 1 = 0') returns


the solutions in a structure.

S=
x: [8x1 sym]
y: [8x1 sym]

[u,v] = solve('a*u^2 + v^2 = 0','u - v = 1') regards 'a' as a parameter and solves the two
equations for u and v.
S = solve('a*u^2 + v^2','u - v = 1','a,u') regards 'v' as a parameter, solves the two
equations, and returns S.a and S.u.

[a,u,v] = solve('a*u^2 + v^2','u - v = 1','a^2 - 5*a + 6') solves


the three equations for a, u and v.

[x,y] = solve('sin(x+y)-exp(x)*y = 0','x^2-y = 2') cannot find


an analytic solution, so returns a numeric solution.

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
20
10.3 FZERO Scalar nonlinear zero finding.
X = FZERO(FUN,X0) tries to find a zero of the function FUN near X0.
FUN accepts real scalar input X and returns a real scalar function value F
evaluated at X. The value X returned by FZERO is near a point where FUN
changes sign (if FUN is continuous), or NaN if the search fails.

X = FZERO(FUN,X0), where X is a vector of length 2, assumes X0 is an


interval where the sign of FUN(X0(1)) differs from the sign of FUN(X0(2)).
An error occurs if this is not true. Calling FZERO with an interval
guarantees FZERO will return a value near a point where FUN changes
sign.

X = FZERO(FUN,X0), where X0 is a scalar value, uses X0 as a starting guess.


FZERO looks for an interval containing a sign change for FUN and
containing X0. If no such interval is found, NaN is returned.
In this case, the search terminates when the search interval
is expanded until an Inf, NaN, or complex value is found.

X = FZERO(FUN,X0,OPTIONS) minimizes with the default optimization


parameters replaced by values in the structure OPTIONS, an argument
created with the OPTIMSET function. See OPTIMSET for details. Used
options are Display and TolX. Use OPTIONS = [] as a place holder if
no options are set.

X = FZERO(FUN,X0,OPTIONS,P1,P2,...) allows for additional arguments


which are passed to the function, F=feval(FUN,X,P1,P2,...). Pass an empty
matrix for OPTIONS to use the default values.

[X,FVAL]= FZERO(FUN,...) returns the value of the objective function,


described in FUN, at X.

[X,FVAL,EXITFLAG] = FZERO(...) returns a string EXITFLAG that


describes the exit condition of FZERO.
If EXITFLAG is:
> 0 then FZERO found a zero X
< 0 then no interval was found with a sign change, or
NaN or Inf function value was encountered during search
for an interval containing a sign change, or
a complex function value was encountered during search
for an interval containing a sign change.

[X,FVAL,EXITFLAG,OUTPUT] = FZERO(...) returns a structure


OUTPUT with the number of iterations taken in OUTPUT.iterations.

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
21
Examples
FUN can be specified using @:
X = fzero(@sin,3)
returns pi.
X = fzero(@sin, 3, optimset('disp','iter'))
returns pi, uses the default tolerance and displays iteration information.

FUN can also be an inline object:


X = fzero(inline('sin(3*x)'),2);

Limitations
X = fzero(inline('abs(x)+1'), 1)
returns NaN since this function does not change sign anywhere on the
real axis (and does not have a zero as well).
X = fzero(@tan,2)
returns X near 1.5708 because the discontinuity of this function near the
point X gives the appearance (numerically) that the function changes sign at X.

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
22
11 Matrices and Matrix Operations
11.1 Entering and Manipulating Matrices
Matrices are entered into MATLAB by listing the elements of the matrix and enclosing
them within a pair of square brackets. Commas or blanks separate elements of a single row,
and semicolons or carriage return separates rows. For example
>> A = [1 2; 3 4]
yields the MATLAB response
A=
1 2
3 4
and
>> A = [1,2
3,4]
produces the same result.
Matrix elements can be any MATLAB expression; however, MATLAB recognizes only
rectangular matrices; i.e. the matrix must have the same number of columns in each row. To
find the dimensions of a matrix use the size command, e.g.
>> size(A)
ans =
2 2
Individual matrix elements can be referenced using indices enclosed within parentheses. The
first index identifies the row number, and the second index identifies the column number. For
instance, to change the second element in the second row of matrix A to 5, type
>> A(2,2) = 5
ans =
1 2
3 5
If you add an element to a matrix beyond the existing size of the matrix, then MATLAB
automatically inserts zeros as needed to maintain a rectangular matrix:
>> A(3,3) = 6
A=
1 2 0
3 5 0
0 0 6
Using the simple commands described thus far, you can easily manipulate both the
matrices and vectors. For example, to add a row onto a matrix A, we type

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
23
>> A = [A; [7 8 9]]
A=
1 2 0
3 5 0
0 0 6
7 8 9

To extract the submatrix of A that consists of the second through third rows and of the first
though third columns, use vectors as indices as follows:
>> B = A(2:3,1:3)
B=
3 5 0
0 0 6

The : command as an index by itself indicates that all elements should be selected; i.e.,
A(1,: ) will return the entire first row of matrix A. Typing A( : ) will return all the elements of
A strung out in a column vector.
Matrices can also be manipulated using vectors that contain elements equal to 0 and 1
only. These 0-1 vectors are most frequently generated using relational operators, such as > or
<. If you use a 0-1 vector as a matrix index, rows or columns corresponding to the 1’s are
selected while those corresponding to 0’s are not selected, such as,
>> B = B (:,[0 1 1])
B =
5 0
0 6
MATLAB has commands for generating special matrices. For example, you can create a
diagonal matrix with the diag command using a vector containing the diagonal elements as the
input argument, such as,
>> D = diag([1 2])
D =
1 0
0 2

The MATLAB function ones(n) generates an n-by-n matrix of ones. The function ones(m,n)
or ones([m,n]) generate an m-by-n matrix of ones.

>>ones(3)
ans =
1 1 1
1 1 1
1 1 1

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
24
>>ones(3,5)
ans =
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

On the other hand, the MATLAB function eye(n), generates an n-by-n identity matrix.
eye(m,n) or eye([m,n]) is an m-by-n matrix with 1's on the diagonal and zeros elsewhere.

>>eye(2)
ans =
1 0
0 1

>> eye(4,3)
ans =
1 0 0
0 1 0
0 0 1
0 0 0

The fliplr command flips the matrix in the left/right direction: fliplr(x) returns x with row
preserved and columns flipped in the left/right direction. For example:

x= 123 becomes 321


456 654

On the other hand the command flipud, flips the matrix in the up/down direction: flipud(x)
returns x with columns preserved and rows flipped in the up/down direction. For example,
x = 1 4 3 6
2 5 becomes 2 5
3 6 1 4

We can also separate any matrix into an upper part and a lower part using triu and tril, which
keep the upper part and the lower part, respectively. For example if:
>>a=
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
if we use the command, triu(a), MATLAB will display:

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
25
>> ans =
1 2 3 4
0 6 7 8
0 0 11 12
0 0 0 16
if we use tril(a), the lower part will be displayed, with zeros in the upper part.

Closing Notes:
The elements of a matrix being entered are enclosed by brackets
A matrix is entered in "row-major order" [i.e. all of the first row, then all of the second
row, etc];
Rows are separated by a semicolon [or a new line], and the elements of the row may be
separated by either a comma or a space. [Caution: Watch out for extra spaces!]
The element in the ith row and jth column of a is referred to in the usual way:
>> A(2,3) = 10

11.2 Matrix Operations


MATLAB performs matrix arithmetic as easily as it does scalar arithmetic. To add two
matrices, simply type:

>> B + D
ans =
6 0
0 8

Similarly, to multiply two matrices, do as you do for scalars:

>> B*D
ans =
5 0
0 12

Dividing by matrices is also straightforward once you understand how MATLAB


interprets the divide symbols / and \ . Suppose you want to solve for x in the equation Px
= Q. To express the solution x = P-1 Q in MATLAB, use left division as x = P\Q. Now
suppose you want to solve yP = Q for y. The solution to this problem is y = QP-1, which
you can write in MATLAB using right division as y = Q/P.
Although MATLAB needs no special instructions to multiply or divide matrices, it
does require that the inner dimensions of the two matrices being multiplied or divided be
the same. The exception is multiplying or dividing a matrix by a scalar, which is a valid
calculation. MATLAB will tell you when you try to multiply matrices having
incompatible dimensions. For instance, running mistake.m:

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
26
mistake.m
% mistake: Shows what happens when you try to multiply
% matrices having incompatible dimensions.
X = [1 2 3] ; Y = [4 7 0;2 2 8];
Z = X*Y;
yields the MATLAB error response
??? Error using == > *
Inner matrix dimensions must agree.
Error in == > mistake.m
One line 4 == > Z = X*Y;
To debug mistake.m enter size(X) and then size(Y) at the MATLAB
prompt to check the dimensions of the matrices X and Y. Of course, you will find that X
is a 1 x 3 matrix and Y is a 2 x 3 matrix. Therefore the last statement in mistake.m is in
error because the inner dimensions of X and Y are not the same. Multiplication can be
performed, however, if we use the transpose of Y because the transpose is a 3 x 2 matrix.
The ' command computes the transpose of a matrix. Therefore, replacing the last line of
mistake.m with Z = X*Y' and running mistake.m will give a valid result.
The power operator ^ also operates on the matrix as a whole as long as the matrix is
square. For example, D^2 is equivalent to D*D. However, Y^2 is not valid because Y
is not a square matrix.
MATLAB includes many functions that perform some operation on the matrix, such
as det(X) and inv(X), which produce the determinant and the inverse of X, respectively.
rank(X) determines the rank of matrix X, and expm(X) computes eX . Note that many of
these functions require that the input argument be a square matrix. To explore other
functions and to learn more about using these functions use help as described earlier, and
particularly help elmat
Important Note:
Sometimes you may want to consider a matrix as simply an array of numbers and
operate on the array element by element. Specifically, you will create arrays to represent
tables of data that you want to manipulate. Suppose you have a table of data that you have
entered as an array called Data. Suppose you want to perform a root mean square
calculation and need to find the square of each element in Data. Using a . you can
convert arithmetic matrix operations into element-by-element operations. Specifically,
preceding the operator with the . indicated array operation . To square each element in
the array, type Data.^2. Similarly, to multiply two arrays R and S (of the same
dimension) element by element, type R.*S as follows:
>> R = [4 5
0 1];
>> S = [2 3
4 6];

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
27
>> R.*S
ans =
8 15
0 6
Some MATLAB functions automatically operate element by element on an array. For
example, exp(X) will return an array with each element equal to the exponential of the
corresponding element of X. The trigonometric functions and other elementary
mathematical functions such as abs, sqrt and log also operate element by element.

12 Plotting
12.1 Creating Two-Dimensional Plots
Ordinary two-dimensional plots can be generated in MATLAB using the plot command.
The most basic use of plot is with a single vector as the input argument. Specifically, if you
enter the command plot(v) for any real vector v, MATLAB will create a plot of the elements
of v versus their indices. That is, the first element of v will be plotted versus 1, the second
element of v versus 2, etc.

For v = [1 .35 .15 .05 .01 .005 0 0 0 0]The result is shown if the following figure:

0.9

0.8

0.7

0.6

0.5

0.4

0.3

0.2

0.1

0
0 2 4 6 8 10

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
28
Notice that the axes are automatically drawn and scaled to include all of the data in v. When
you enter a plotting command, such as plot(v), in the MATLAB command window, the
graphics window will automatically be called to show your plot. You can size both windows
to appear simultaneously beside each other, and you can switch between them using the
mouse, for example.

The command plot(v) produces a different result if v is a vector of complex numbers. In


this case plot(v) will yield a plot of the real part of v versus the imaginary part of v. If the
argument of the plot command is a matrix, then MATLAB treats each column as a distinct
vector to be potted and places all of the plots on the same graph. The script file examplot.m
creates a 5x5 matrix and plots it. The first command, clf, in the script file clears the graphics
window. It is useful to put this command in the beginning of all your plotting routines to avoid
unintentionally plotting on top of a previously displayed graph.

examplot.m
% Matrix plotting
% We will create a 5x5 matrix and plot its columns
clf % Clear graphics window
A=[1 2 3 4 5;0.5 0.35 0.29 0.25 0.21;0.35 0.29 0.25 0.21 0.2;…
0.25 0.21 0.2 0.18 0.16]
plot(A) % Plot the matrix

4.5

5.0000
0.2100
0.2000
0.1600
4
Last Column
3.5

4.0000
0.2500
0.2100
0.1800
3 3.0000
0.2900
0.2500
0.2000
2.5 First Column
2
2.0000
0.3500
0.2900
0.2100

1.5

1
0.5000
0.3500
0.2500
1.0000

0.5

0
1 1.5 2 2.5 3 3.5 4

As you can see, the result is hard to understand, primarily because the four individual plots are
not labeled. We will show how to label the line on a plot shortly.

If you enter plot(x,y) where x and y are vectors of the same dimension, MATLAB will
plot y versus x. Running the script file genplot.m will generate such a plot:

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
29
genplot.m
% Generate a plot using an Arrhenius-type equation.
clf
T= [100:50:300]; %Generate values for temperature
K0=2e03 ; % Set the value for the constant
E=2.3567e3; % Set the value for activation energy
K=K0.*exp(-E./(1.987.*T)); % Calculate corresponding K's
y=K;x=1./T; % Set values for x's and y's
plot(x,y) % Plot the result

40

35

30

25

20

15

10

0
3 4 5 6 7 8 9 10
-3
x 10

The first line generates values of temperatures from 100 to 300°C in increments of 50°C. After
assigning values for the constants of the equation the corresponding rate constant values are
computed. Notice here the use of the . between the operators: e.g. K0.exp(-E./(1.987.*T)). If
we had used K0*exp(-E/(1.987*T)), we would have gotten an error message for trying to
multiply two matrices of incompatible dimensions. In general, the collection of array operation
commands (.* , .^ , ./ , etc.) is very useful in plotting. We generate the vectors x and y by
letting x be the reciprocal of the temperature and y be the rate constant. The generated plot
shows the relationship between the rate constant and the reciprocal of the temperature. Note
that the first argument of the plot command is interpreted as the horizontal axis and the second
argument as the vertical axis.

Once you have generated a plot, you can read data off the plot by using the command
ginput. For example, you can use ginput to find the coordinates of the data points of the
generated figure. Entering [xpoint,ypoint] = ginput will put a crosshair on the graph. You can
move the crosshair with the mouse. When you have moved the crosshair to a point of interest,
depress the mouse button, and MATLAB will compute the coordinates at the crosshair. You
can extract coordinates for many different points at a time by successively repeating this
procedure. When you are done, hit the enter or return key. You may need to be sure that the

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
30
crosshair is in the graphics window when you do this. MATLAB will respond in the command
window by displaying the coordinates of all the data points you selected. The variable xpoint
will contain the x coordinates and the variable ypoint will contain the y coordinates of the data
points.

In addition to the plot command, MATLAB provides several other two-dimensional


plotting commands that operate the same way as plot but yielding different graph scales.
Specifically, loglog, semilogx and semilogy produce plots with one or two logarithmically
scaled axes. Use the help facility for more background on these plotting command and related
topics.

Helpful Hints

We will now see some ways of customizing plots such as adding new information like
titles and labels to a graph for better display of data.

The title, xlabel and ylabel commands title and label the axes of your plot. For example
add the following lines to the end of the file genplot.m
title('Plot of an Arrhenius-type relation')
xlabel('Reciprocal of temperature, 1/T')
ylabel('Value of K')
grid
returns the following plot:

Plot of an Arrhenius-type relation


40

35

30

25

20

15

10

0
3 4 5 6 7 8 9 10
Reciprocal of temperature, 1/T -3
x 10

Labeling of arbitrary points on a graph can be done with the text or the gtext commands. The
text command performs manual labeling: i.e. you must specify the coordinates on the graph
for the position of the first letter of label. The gtext command provides interactive labeling:
i.e. after generating your plot enter gtext('label'). MATLAB will provide a crosshair in the
graphics window which you can move to the desired label position using the mouse. When

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
31
you are finished moving the crosshair, depress the mouse button and MATLAB will respond
by writing label on the plot to the right of the crosshair. Try help for additional information.

Next, try replacing the command plot(x,y) in genplot.m with plot(x,y,'..') and rerun it.
Instead of the default solid-line plot, you should see a dotted-line plot. MATLAB provides a
variety of line and point types and colors that you can use to make your plots look exactly as
you wish. They are particularly useful when you need to distinguish between different lines on
a multiple-line plot and you do not like the default line appearance. You can specify your own
colors, line styles and markers. This is particularly useful if you have more that a data set to be
presented on the same graph. The following table shows the symbols used for these options:

Symbol Color Symbol Marker Symbol Linestyle


b blue . point - solid line
g green o circle : dotted line
r red x cross -. dash-dot line
c cyan + plus sign -- dashed line
m magenta * asterisk
y yellow s square
k black d diamond
w white v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)

Suppose, for example you have the following two sets of data, which represent the variation of
the corrosion rate of zinc with Reynolds number, in solutions of different concentrations:

1 wt% 3.5 wt%


Re Rate Re Rate
392.312 524.35 396.709 660.22
977.412 525.60 991.773 689.27
1948.1 566.42 1983.55 889.57
2952.46 702.84 2895.45 905.68
4018.06 775.75 3847.39 1024.98

First we create two sets of vectors: one for the 1% salt, and one for the 3.5% salt:
>> Re1=[392.312 977.412 1948.1 2952.46 4018.06]; Rate1=[524.35 525.6 566.42
702.84 775.75]
>> Re2=[396.709 991.773 1983.55 2895.45 3847.39]; Rate2=[660.22 689.27 889.57 905.68
1024.98]

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
32
Then we use the given data to plot two lines with different colors and symbols. If at the
MATLAB prompt, the following line is entered:
>> plot(Re1,Rate1,'r*',Re1,Rate1,'y--',Re2,Rate2,'go',Re2,Rate2,'m-')
The following plot appears in the graphics window:

The first relation drawn is Re1 vs. Rate1, with red asterisk and yellow solid line (bottom line); the
second relation is Re2 vs. Rates with green circles and magenta solid line (top line)

The plot can, of course be customized to have a title and labeled axes as explained earlier.

Furthermore, one graphics window can hold more than one set of axes. The current figure can be
subdivided into many plotting areas: the command subplot(m,n,p) subdivides the current figure
window into an m-by-n matrix of plotting areas and chooses the pth area to be active. The subplots
are numbered left to right along the top row, then the second row, etc…

For example:
>> subplot (1,2,1) %pick the upper left of a 1 by 2 grid of subplots
>> plot (Re1, Rate1), title('Corrosion rate for a 1% salt concentration')
>> subplot (1,2,2) %pick the upper right of a 1 by 2 grid of subplots
>> plot (Re2, Rate2), title('Corrosion rate for a 3.5% salt concentration')

The following will therefore, appear in the graphics window:

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
33
Important Note
Sometimes we want to use a logarithmic scale on either axis, or both. In this case instead of using
the plot command we can use the loglog command for plotting on a logarithmic scale for both the
X- and Y- axes. To plot on a semi-logarithmic scale we can use the semilogx or semilogy
commands if a logarithmic (base 10) scale is used for the X-axis or the Y-axis, respectively. Each
of these commands is used exactly as we do with the plot command.
For further assistance and hints on plotting you can use the lookfor plot command to see what
MATLAB is presenting for plotting purposes.

12.2 Creating Three-Dimensional Plots


The plot function for 2-D plotting can be extended into three dimensions with plot3. The
format is the same as the 2-D plot, except the data are in triples, rather than pairs. The generalized
format of plot3 is plot3(x1,y1,z1,S1,x2,z2,S2, ….) where xn, yn and zn are vectors or matrices,
and Sn are optional character strings specifying color, marker, symbol and/or linestyle. The
command plot3 is commonly used to plot a three-dimensional function of a single variable. For
example:
>> t=linspace(0,10*pi);
>> plot3(sin(t),cos(t),t);
>>xlabel('sin(t)'), ylabel('cos(t)'),zlabel('t');
>> text (0,0,0,'Origin')
>> grid on
>> title('Figure for a helix')

The following figure appears in the graphics window:

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
34
From this simple example it is apparent that all the basic features of a 2-D graphics exists in 3-D
also. There is a zlabel command for labeling the Z-axis. The grid command toggles a 3-D grid
underneath the plot. The command text(x,y,z,'string') places a character string at the position
identified by the triplet x,y,z. In addition, subplot applies directly to 3-D graphics functions.

MATLAB defines a mesh surface by the Z-coordinates of points above a rectangular grid in the
x-y plane. It forms the mesh plot by joining adjacent points with straight lines. The results looks
like a fishing net with knots at the data points. For example, consider the peaks function:

>> [x,y,z]=peaks(30);
>> mesh(x,y,z)

gives a mesh plot with contours and the command


Instead of mesh, try the meshc command, which
>> xlabel('X-Axis'), ylabel('Y-Axis'), zlabel('Z-Axis')
>> title('Mesh Plot of PEAKS')

meshz, which gives a mesh plot with zero plane.

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
35
A surface plot looks like a mesh plot, except that the spaces between the linesn called patches
are filled. Plots of this type are generated using the surf function:

>> [x,y,z]=peaks(30);
>> surf(x,y,z)
>> xlabel('X-Axis'), ylabel('Y-Axis'), zlabel('Z-Axis')

a surf plot with contours and the command surfl,


Instead of surf, try the surfc command, which gives
>> title('Surface Plot of PEAKS')

which gives a surf plot with lighting.


12.3 Plotting Symbolic Expressions
The function ezplot can be used to plot
symbolic expressions:
>> y='-16*t^2+64*t+96';
>> ezplot(y)

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
36
It can be seen that ezplot graphs the
given symbolic function over the domain
-2  t  2 and scales the y-axis
accordingly. It also adds grids and
labels. In this case we are only interested
in times between 0 and 6. Lets try again
and specify the range:
>> ezplot(y,[0 6])%plot y for 0 < t < 6

Now the region of interest shows up a little better, but there is still part of plot below the
ground. The plot could be fixed by changing the time range and reissuing the ezplot
command, e.g. ezplot(y,[0 5.1623]). Once the plot is in he figure window, it can be modified
like any other plot. Let's scale both axes of the current plot and add a title a labels:

>> axis([0 5.5 0 165]) %scale to show the region of interest


>> title ('Plot of Height versus Time')
>> ylabel('Height in meters'), xlabel('Time in seconds')

All other MATLAB plotting commands


are also available to customize the plot.
For example the command zoom will let
you use the mouse to zoom in on any
desired area of the two-dimensional plot.

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
37
12.5. For
FOR Repeat statements a specific number of times. The general form of a FOR statement is:

FOR variable = expr, statement, ..., statement END

The columns of the expression are stored one at a time in the variable and then the
following statements, up to the END, are executed. The expression is often of the form X:Y,
in which case its columns are simply scalars. Some examples (assume N has already been
assigned a value).

FOR I = 1:N,
FOR J = 1:N,
A(I,J) = 1/(I+J-1);
END
END

FOR S = 1.0: -0.1: 0.0, END steps S with increments of -0.1


FOR E = EYE(N), ... END sets E to the unit N-vectors.

Long loops are more memory efficient when the colon expression appears in the FOR
statement since the index vector is never created.

12.6 Break
The BREAK statement can be used to terminate the loop prematurely. BREAK Terminate
execution of WHILE or FOR loop. BREAK terminates the execution of FOR and WHILE
loops. In nested loops, BREAK exits from the innermost loop only.

BREAK is not defined outside of a FOR or WHILE loop. Use RETURN in this context
instead.

12.7. Continue
CONTINUE Pass control to the next iteration of FOR or WHILE loop.
CONTINUE passes control to the next iteration of FOR or WHILE loop
in which it appears, skipping any remaining statements in the body
of the FOR or WHILE loop.

In nested loops, CONTINUE passes control to the next iteration of FOR or WHILE loop
enclosing it.

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
38
12. Logical statements
12.1. IF IF statement condition.
The general form of the IF statement is

IF expression
statements
ELSEIF expression
statements
ELSE
statements
END

The statements are executed if the real part of the expression has all non-zero elements. The
ELSE and ELSEIF parts are optional. Zero or more ELSEIF parts can be used as well as
nested IF's. The expression is usually of the form expr rop expr where rop is ==, <, >, <=, >=,
or ~=.
Example
if I == J
A(I,J) = 2;
elseif abs(I-J) == 1
A(I,J) = -1;
else
A(I,J) = 0;
end
12.2. Else
ELSE Used with IF.
ELSE is used with IF. The statements after the ELSE are executed
if all the preceding IF and ELSEIF expressions are false.

The general form of the IF statement is


IF expression
statements
ELSEIF expression
statements
ELSE
statements
END
12.3. Else if
ELSEIF IF statement condition.
ELSEIF is used with IF. The statements after the ELSEIF are executed if the expression is
true and all the preceding IF and ELSEIF expressions are false. An expression is considered
true if the real part has all non-zero elements.

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
39
ELSEIF does not need a matching END, while ELSE IF does.

The general form of the IF statement is


IF expression
statements
ELSEIF expression
statements
ELSE
statements
END

12.4. While
WHILE Repeat statements an indefinite number of times.
The general form of a WHILE statement is:

WHILE expression
statements
END

The statements are executed while the real part of the expression has all non-zero elements.
The expression is usually the result of expr rop expr where rop is ==, <, >, <=, >=, or ~=.

The BREAK statement can be used to terminate the loop prematurely.

For example (assuming A already defined):

E = 0*A; F = E + eye(size(E)); N = 1;
while norm(E+F-E,1) > 0,
E = E + F;
F = A*F/N;
N = N + 1;
end
13. Interpolation
13.1 One Dimensional Interpolation
INTERP1 1-D interpolation (table lookup).
YI = INTERP1(X,Y,XI) interpolates to find YI, the values of the underlying function Y at
the points in the vector XI. The vector X specifies the points at which the data Y is given. If Y
is a matrix, then the interpolation is performed for each column of Y and YI will be
length(XI)-by-size(Y,2).

YI = INTERP1(Y,XI) assumes X = 1:N, where N is the length(Y) for vector Y or


SIZE(Y,1) for matrix Y.

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
40
Interpolation is the same operation as "table lookup". Described in "table lookup" terms,
the "table" is [X,Y] and INTERP1 "looks-up" the elements of XI in X, and, based upon their
location, returns values YI interpolated within the elements of Y.

YI = INTERP1(X,Y,XI,'method') specifies alternate methods. The default is linear


interpolation. Available methods are:
'nearest' - nearest neighbor interpolation
'linear' - linear interpolation
'spline' - piecewise cubic spline interpolation (SPLINE)
'pchip' - piecewise cubic Hermite interpolation (PCHIP)
'cubic' - same as 'pchip'
'v5cubic' - the cubic interpolation from MATLAB 5, which does not
extrapolate and uses 'spline' if X is not equally spaced.

YI = INTERP1(X,Y,XI,'method','extrap') uses the specified method for extrapolation for


any elements of XI outside the interval spanned by X. Alternatively, YI =
INTERP1(X,Y,XI,'method',EXTRAPVAL) replaces these values with EXTRAPVAL. NaN
and 0 are often used for EXTRAPVAL. The default extrapolation behavior with four input
arguments is 'extrap' for 'spline' and 'pchip' and EXTRAPVAL = NaN for the other methods.

For example, generate a coarse sine curve and interpolate over a


finer abscissa:
x = 0:10; y = sin(x); xi = 0:.25:10;
yi = interp1(x,y,xi); plot(x,y,'o',xi,yi)

13.2 Two Dimensional Interpolation


INTERP2 2-D interpolation (table lookup).
ZI = INTERP2(X,Y,Z,XI,YI) interpolates to find ZI, the values of the underlying 2-D
function Z at the points in matrices XI and YI. Matrices X and Y specify the points at which
the data Z is given. Out of range values are returned as NaN.

XI can be a row vector, in which case it specifies a matrix with constant columns. Similarly,
YI can be a column vector and it specifies a matrix with constant rows.

ZI = INTERP2(Z,XI,YI) assumes X=1:N and Y=1:M where [M,N]=SIZE(Z).


ZI = INTERP2(Z,NTIMES) expands Z by interleaving interpolates between
every element, working recursively for NTIMES. INTERP2(Z) is the
same as INTERP2(Z,1).

ZI = INTERP2(...,'method') specifies alternate methods. The default is linear interpolation.


Available methods are:
'nearest' - nearest neighbor interpolation

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
41
'linear' - bilinear interpolation
'cubic' - bicubic interpolation
'spline' - spline interpolation

All the interpolation methods require that X and Y be monotonic and plaid (as if they were
created using MESHGRID). If you provide two monotonic vectors, interp2 changes them to a
plaid internally.
X and Y can be non-uniformly spaced.

For example, to generate a coarse approximation of PEAKS and interpolate over a finer
mesh:
[x,y,z] = peaks(10); [xi,yi] = meshgrid(-3:.1:3,-3:.1:3);
zi = interp2(x,y,z,xi,yi); mesh(xi,yi,zi)

Alexandria University- Faculty of Engineering


Chemical Engineering Department
First Year -Summer 2021
42

You might also like