Lec of MATLAB - 2nd Stage - Compressed
Lec of MATLAB - 2nd Stage - Compressed
Lecture One:
Introduction to MATLAB
Starting MATLAB
Getting started
Mathematical functions
1
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
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. The software package has been commercially available since 1984 and is
now considered as a standard tool at most universities and industries worldwide.
Starting MATLAB
After logging into your account, you can enter MATLAB by double-clicking on the MATLAB shortcut icon
(MATLAB) on your Windows desktop. When you start MATLAB, a special window called the MATLAB
desktop appears. The desktop is a window that contains other windows. The major tools within or accessible
from the desktop are:
The Command Window
The Command History
The Workspace
The Current Directory
The Help Browser
The Start button
When MATLAB is started for the first time, the screen looks like the one that shown in the Figure below.
This illustration also shows the default configuration of the MATLAB desktop. You can customize the
arrangement of tools and documents to suit your needs.
2
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
- Overwriting variable
Once a variable has been created, it can be reassigned. In addition, if you do not wish to see the intermediate
results, you can suppress the numerical output by putting a semicolon (;) at the end of the line. Then the
sequence of commands looks like this:
>> t = 5;
>> t = t+1
t=6
3
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
- Error messages
If we enter an expression incorrectly, MATLAB will return an error message. For example, in the following,
we left out the multiplication sign, *, in the following expression
>> x = 10;
>> 5x
??? 5x
Error: Unexpected MATLAB expression.
- Making corrections
To make corrections, we can, of course retype the expressions. But if the expression is lengthy, we make
more mistakes by typing a second time. A previously typed command can be recalled with the up-arrow key
↑. When the command is displayed at the command prompt, it can be modified if needed and executed.
In MATLAB, it becomes
>> 1/(2+3^2)+4/5*6/7
ans = 0.7766
or, if parentheses are missing,
>> 1/2+3^2+4/5*6/7
ans = 10.1857
4
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Mathematical functions
MATLAB offers many predefined mathematical functions for technical computing which contains a large
set of mathematical functions.
There is a long list of mathematical functions that are built into MATLAB. These functions are called built-
ins. Many standard mathematical functions, such as sin(x), cos(x), tan(x), ex, ln(x), are evaluated by the
functions sin, cos, tan, exp, and log respectively in MATLAB.
Table below lists some commonly used functions, where variables x and y can be numbers, vectors, or
matrices.
In addition to the elementary functions, MATLAB includes a number of predefined constant values. A list of
the most common values is given in Table below.
5
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Examples:
6
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Lecture Two:
Matrix generation
- Entering a vector
- Entering a matrix
- Matrix indexing
- Colon operator
- Linear spacing
- Colon operator in a matrix
- Creating a sub-matrix
- Matrix generators
1
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Introduction
Matrices are the basic elements of the MATLAB environment. A matrix is a two-dimensional array
consisting of m rows and n columns. Special cases are column vectors (n = 1) and row vectors (m = 1).
In this section we will illustrate how to apply different operations on matrices. MATLAB supports two types
of operations, known as matrix operations and array operations.
Matrix generation
Matrices are fundamental to MATLAB. Therefore, we need to become familiar with matrix generation and
manipulation. Matrices can be generated in several ways.
- Entering a vector
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. As discussed earlier, an array of dimension 1 x n is called a row vector, whereas an
array of dimension m x 1 is called a column vector. The elements of vectors in MATLAB are enclosed by
square brackets and are separated by spaces or by commas. For example, to enter a row vector, v, type
>> v = [1 4 7 10 13]
v = 1 4 7 10 13
Column vectors are created in a similar way, however, semicolon (;) must separate the components of a
column vector,
>> w = [1;4;7;10;13]
w=
1
4
7
10
13
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 (').
>> w = v'
w=
1
4
7
10
13
Thus, v(1) is the first element of vector v, v(2) its second element, and so forth. Furthermore, to access
blocks of elements, we use MATLAB's colon notation (:). For example, to access the first three elements of
v, we write,
>> v(1:3)
ans = 1 4 7
2
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Or, all elements from the third through the last elements,
>> v(3,end)
ans = 7 10 13
where end signifies the last element in the vector. If v is a vector, writing
>> v(:)
produces a column vector, whereas writing
>> v(1:end)
produces a row vector.
- Entering a matrix
A matrix is an array of numbers. To type a matrix into MATLAB you must
begin with a square bracket, [
separate elements in a row with spaces or commas (,)
use a semicolon (;) to separate rows
end the matrix with another square bracket, ].
type,
>> A = [1 2 3; 4 5 6; 7 8 9]
MATLAB then displays the 3 x 3 matrix as follows,
A=
1 2 3
4 5 6
7 8 9
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)
ans = 4
- Matrix indexing
We select elements in a matrix just as we did for vectors, but now we need two indices. The element of row i
and column j of the matrix A is denoted by A(i,j). Thus, A(i,j) in MATLAB refers to the element Aij of
matrix A. The first index is the row number and the second index is the column number. For example,
A(1,3) is an element of first row and third column. Here, A(1,3)=3.
Correcting any entry is easy through indexing. Here we can substitute A(3,3) = 9 by A(3,3) = 0.
3
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
- Colon operator
The colon operator will prove very useful and understanding how it works is the key to efficient and
convenient usage of MATLAB. It occurs in several different forms. Often we must deal with matrices or
vectors that are too large to enter one element at a time. For example, suppose we want to enter a vector x
consisting of points
(0; 0:1; 0:2; 0:3; . . . ; 5). We can use the command
>> x = 0:0.1:5;
The row vector has 51 elements.
- 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 100 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 to b with steps, where :
>>linspace(1,5,9)
ans=
1 1.5 2 2.5 3 3.5 4 4.5 5
divides the interval [1; 9] into 10 equal subintervals (0.5), then creating a vector of 10 elements.
This is useful when we want to divide an interval into a number of subintervals of the same length.
The colon operator can also be used to extract a sub-matrix from a matrix A.
4
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
- Creating a sub-matrix
To extract a submatrix B consisting of rows 2 and 3 and columns 1 and 2 of the matrix A, do the following
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
>> A(:)
ans =
1
2
3
4
5
6
7
8
0
The submatrix comprising the intersection of rows p to q and columns r to s is denoted by A(p:q,r:s).
As a special case, a colon (:) as the row or column speci¯er covers all entries in that row or column; thus
5
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
- Dimension
To determine the dimensions of a matrix or vector, use the command size. For example,
>> size(A)
ans =
3 3
means 3 rows and 3 columns, or more explicitly with,
>> [m,n]=size(A)
- Transposing a matrix
The transpose operation is denoted by an apostrophe or a single quote ('). It flips a matrix about its main
diagonal and it turns a row vector into a column vector. Thus,
>> A'
ans =
1 4 7
2 5 8
3 6 0
By using linear algebra notation, the transpose of m x n real matrix A is the n x m matrix that results from
interchanging the rows and columns of A. The transpose matrix is denoted AT .
6
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
- Matrix generators
MATLAB provides functions that generates elementary matrices. The matrix of zeros, the matrix of ones,
and the identity matrix are returned by the functions zeros, ones, and eye, respectively.
>> b=ones(3,1)
b=
1
1
1
Equivalently, we can define b as >> b = [1;1;1]
>> eye(3)
ans =
1 0 0
0 1 0
0 0 1
>> c = zeros(2,3)
c=
0 0 0
0 0 0
In addition, matrices can be constructed in a block form. With C defined by C = [1 2; 3 4], we may create a
matrix D as follows
>> D = [C zeros(2); ones(2) eye(2)]
D=
1 2 0 0
3 4 0 0
1 1 1 0
1 1 0 1
Examples
7
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
8
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Lecture Three
Array operations
1
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Array operations
MATLAB has two different types of arithmetic operations: matrix arithmetic operations and array arithmetic
operations.
- Matrix arithmetic operations
As we mentioned earlier, MATLAB allows arithmetic operations: +, -, *, and ^ to be carried out on matrices.
Thus,
A+B or B+A is valid if A and B are of the same size
A*B is valid if A's number of column equals B's number of rows
A^2 is valid if A is square and equals A*A
α*A or A*α multiplies each element of A by α
If A and B are two matrices of the same size with elements A = [aij ] and B = [bij ], then the command
>> C = A.*B
produces another matrix C of the same size with elements cij = aijbij . For example, using the same 3 x 3
matrices,
we have,
>> C = A.*B
C=
10 40 90
160 250 360
490 640 810
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
2
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
>> A.^2
ans =
1 4 9
16 25 36
49 64 81
The relations below summarize the above operations. To simplify, let's consider two vectors U and V with
3
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Examples:
X=[1,2,3;4,5,6]
Y=[12,11,10;9,8,7]
>>X+Y
ans =
13 13 13
13 13 13
>>X-Y
ans =
-11 -9 -7
-5 -3 -1
>>X+3
ans =
4 5 6
7 8 9
>>X*3
ans =
3 6 9
12 15 18
>>X.*Y
ans =
12 22 30
36 40 42
>>X*Y’
ans =
64 46
163 118
>>X’*Y
ans =
48 43 38
69 62 55
90 81 72
4
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Lecture Four
1
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
x + 2y + 3z = 1
4x + 5y + 6z = 1
7x + 8y = 1
1 2 3
𝐴 = [4 5 6 ]
7 8 0
1
𝑏 = [1]
1
2
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
2. The second one is to use the backslash ( \ ) operator. The numerical algorithm behind this operator is
computationally efficient. This is a numerically reliable way of solving system of linear equations by
using a well-known process of Gaussian elimination.
>> A = [1 2 3; 4 5 6; 7 8 0];
>> b = [1; 1; 1];
>> x = A\b
x=
-1.0000
1.0000
-0.0000
3
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Lecture Five
Programming in MATLAB
1
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Introduction
So far in these lab sessions, 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 file, 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 files or scripts for short.
This section covers the following topics:
- M-File Scripts
- M-File Functions
M-File Scripts
A script file is an external file that contains a sequence of MATLAB statements. Script files have a filename
extension .m and are often called M-files. M-files can be scripts that simply execute a series of MATLAB
statements, or they can be functions that can accept arguments and can produce one or more outputs.
Example 1
Consider the system of equations:
x + 2y + 3z = 1
3x + 3y + 4z = 1
2x + 3y + 3z = 2
Find the solution x to the system of equations.
Solution:
1. Use the MATLAB editor to create a file: File → New → M-file.
2. Enter the following statements in the file:
A = [1 2 3; 3 3 4; 2 3 3];
b = [1; 1; 2];
x = A\b
3. Save the file, for example, example1.m.
4. Run the file, in the command line, by typing:
>> example1
x=
-0.5000
1.5000
-0.5000
When execution completes, the variables (A, b, and x) remain in the workspace. To see a listing of them,
enter whos at the command prompt.
Note: 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.
2
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
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.
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-file for short) has its own area of workspace, separated
from the MATLAB base workspace.
1) function f = factorial(n)
2) % FACTORIAL(N) returns the factorial of N.
3) % Compute a factorial value.
4) f = prod(1:n);
The first line of a function M-file starts with the keyword function. It gives the function name and order of
arguments. In the case of function factorial, there are up to one output argument and one input argument.
3
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Both functions and scripts can have all of these parts, except for the function definition line which applies to
function only. 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.
Function file can have none, one, or several output arguments. Table below illustrates some possible
combinations of input and output arguments.
4
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Example.
% This script file calculates the average of points
% scored in three games.
% The point from each game are assigned to a variable
% by using the `input' command.
The following shows the command prompt when this script file (saved as example) is executed.
>> example
>> Enter the points scored in the first game 15
>> Enter the points scored in the second game 23
>> Enter the points scored in the third game 10
average =
16
- Output commands
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:
5
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
The display disp function allows the programmer to display the contents of a string or a matrix in the
command window. Although the disp function is adequate for many display tasks, the fprintf function gives
the programmer considerably more control over the way results are displayed. Table below illustrates the
various formats supported by fprintf
Example 2:
Write a function file that converts temperature in degrees Fahrenheit (FO) to degrees Centigrade (CO). Use
input and fprintf commands to display a mix of text and numbers. Recall the conversion formulation,
C = 5/9 * (F - 32).
Answer
function [ C ] = FtoC( F )
F = input('Enter the temperature in degrees Fahrenheit ');
C = 5/9 * (F - 32)
fprintf(' The temperature in degrees Centigrade=%d\n', C);
end
6
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Example 3:
Consider the behavior of a freely falling object under the influence of gravity, where the position of the
object is described by:
1
𝑑= 𝑔 𝑡2
2
Where,
d - distance the object travels
g - acceleration due to gravity
t - elapsed time.
Describe the Input and Output as:
Input
Value of g the acceleration due to gravity, provided by the user (one value)
Time t provided by the user, (starting time, ending time, increments)
Output
Distances calculated for each value of time.
Find the distance traveled by a freely falling object with generate a table of output results (distances
calculated with time. Use disp and fprintf to create a table.
Answer
g = input('What is the value of acceleration due to gravity?');
start = input('What starting time would you like?');
finish = input('What ending time would you like?');
incr = input('What time increments would you like calculated?');
time = start:incr:finish;
%Calculate the distance
distance = 1/2*g*time.^2;
%Create a matrix of the output data
result = [time;distance]';
disp(' time,s distance,m')
disp(result)
%fprintf('%5d %10d\n',result)
7
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Lecture Six
1
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Introduction
MATLAB is also a programming language. Like other computer programming languages, MATLAB has
some decision making structures for control of command execution. These 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-files 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.
Control Flow
MATLAB has four control flow structures:
- The If statement,
- The For Loop,
- The While Loop,
- The Switch statement.
if expression
statements
end
2
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Note that the "equal to" relational operator consists of two equal signs (==) (with no space between them),
since = is reserved for the assignment operator.
3
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Comparisons are either true or false, and most computer programs (including MATLAB) use the number 1
for true and 0 for false. (MATLAB actually takes any number that is not 0 to be true.) If we define two scalars
x = 5;
y = 1;
and use a relational operator such as <, the result of the comparison
x<y
is either true or false. In this case, x is not less than y, so MATLAB responds
ans =
0
indicating that the comparison is false. MATLAB uses this answer in selection statements and in repetition
structures to make decisions.
Of course, variables in MATLAB ® usually represent entire matrices. If we redefine x and y, we can see how
MATLAB handles comparisons between matrices. For example,
x = [ 1, 2, 3, 4, 5];
y = [-2, 0, 2, 4, 6];
x<y
ans =
0 0 0 0 1
MATLAB also allows us to combine comparisons with the logical operators and , not , and or.
The code
x = [ 1, 2, 3, 4, 5];
y = [-2, 0, 2, 4, 6];
z = [ 8, 8, 8, 8, 8];
z>x & z>y
ans =
1 1 1 1 1
4
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Example:
Create a function to determine test grades based on the score and assuming a single input into the function.
The grades should be based on the following criteria:
Answer
5
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
for k = 1:3
a = 5^k
end
a=
5
a=
25
a=
125
A common way to use a for loop is in defining a new matrix. Consider, for example, the code
For k = 1:5
a(k) = k^2
end
This loop defines a new matrix, a , one element at a time. Since the program repeats its set of instructions five
times, a new element is added to the a matrix each time through the loop, with the following output in the
command window:
a=
1
a=
1 4
a=
1 4 9
a=
1 4 9 16
a=
1 4 9 16 25
6
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Another common use for a for loop is to combine it with an if statement and determine how many times
something is true. For example, in the list of test scores shown in the first line, how many are above 90?
scores = [76,45,98,97];
count = 0;
for k=1:length(scores)
if scores(k)>90
count = count + 1;
end
end
disp(count)
It is a good 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. The following
statements form the 5-by-5 symmetric matrix A with (i; j) element i/j for j> i:
n = 5; A = eye(n);
for j=2:n
for i=1:j-1
A(i,j)=i/j;
A(j,i)=i/j;
end
end
7
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Example:
Use MATLAB capability to create a degrees-to-radians table from 1 to 360 degree with step 10, you can
demonstrate the use of for loops.
for k=1:36
deg(k) = k*10;
rad(k)=deg(k)*pi/180;
end
t = [deg;rad]
disp('Degrees to Radians')
disp('Degrees Radians')
fprintf('%8.0f %8.2f \n',t)
Degrees to Radians
Degrees Radians
10 0.17
20 0.35
30 0.52
40 0.70
50 0.87
60 1.05
70 1.22
80 1.40
90 1.57
100 1.75
110 1.92
120 2.09
130 2.27
140 2.44
150 2.62
160 2.79
170 2.97
180 3.14
190 3.32
200 3.49
210 3.67
220 3.84
230 4.01
240 4.19
250 4.36
260 4.54
270 4.71
280 4.89
290 5.06
300 5.24
310 5.41
320 5.59
330 5.76
340 5.93
350 6.11
360 6.28
360 6.28
8
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Example:
R=12:-3:2.7;
A=100;
for m=1:2:4
A=A-R(m);
if A<=(14*R(m+1))
disp(A);
else
disp(R(m));
end
end
disp(m);
Answer:
R = 12 9 6 3
m= 1 3
1s loop
A= 100-12=88
88 <= (14*9) True
disp(A) = 88
2nd loop
A= 88-6 = 82
82 <= (14*3) False
disp(R(m)) = 6
disp(m) = 3
9
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Lecture Seven
``while...end'' loop
1
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
This loop is used when the number of passes is not specified. While loops are similar to for loops. The big
difference is the way MATLAB decides how many times to repeat the loop. While loops continue until some
criterion is met. The while loop has the form:
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.
One common use for a while loop is error checking of user input. Consider a program where we prompt the
user to input a positive number, and then we calculate the log base 10 of that value. We can use a while loop
to confirm that the number is positive, and if it is not, to prompt the user to enter an allowed value.
The program keeps on prompting for a positive value until the user finally enters a valid number.
If, when the code is executed, a positive value of x is entered, the while loop does not execute (since x is not
less than 0). If, instead, a zero or negative value is entered, the while loop is executed, an error message is sent
to the command window, and the user is prompted to reenter the value of x. The while loop continues to
execute until a positive value of x is finally entered.
2
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Example:
Create a new function called fact2 that uses a while loop to find N!. Include an if statement to check for
negative numbers and to confirm that the input is a scalar.
Answer
fact2(5)
ans =
120
fact2(-10)
ans =
The input must be a positive integer
fact2([1:10])
ans =
The input must be a positive integer
3
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Example:
Write out the values of 𝑥2 for all positive integer values 𝑥 such that 𝑥3<1000 using while.
Answer
x=1;
while x^3<1000
disp (x^2)
x=x+1;
end
Example:
Stop the summation operation when the value of 𝑃≥100, and display the value of the last 𝑘.
k=0;
sum=0;
p=1;
while p < 100
sum = sum + (k/(2*k+1))
p=4*sum
k=k+1;
end
disp(k)
4
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
switch variable
case option1
code to be executed if variable is equal to option 1
case option2
code to be executed if variable is equal to option 2
.
.
.
case option_n
code to be executed if variable is equal to option n
otherwise
code to be executed if variable is not equal to any of the options
end
Here’s an example: Suppose you want to create a function that tells the user what the airfare is to one of three
different cities:
5
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Example:
Create a program to prompt the user to enter the number of candy bars he or she would like to buy. The
input will be a number. Use the switch/case structure to determine the bill, where
1 bar _ $0.75
2 bars _ $1.25
3 bars _ $1.65
more than 3 bars= $1.65 +$0.30 (number ordered - 3)
Answer
6
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Lecture Eight
Plotting in MATLAB
1
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Introduction
MATLAB has an excellent set of graphic tools. Plotting a given data set or the results 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 mathematics. Being able to plot mathematical functions and data freely is the
most important step, and this section is written to assist you to do just that. Engineers use graphing techniques
to make the information easier to understand. With a graph, it is easy to identify trends, pick out highs and
lows, and isolate data points that may be measurement or calculation errors. Graphs can also be used as a
quick check to determine whether a computer solution is yielding expected results.
Basic Plotting
The basic MATLAB graphing procedure is to take a vector of x-coordinates, x = (x1; : : : ; xN), and a vector
of y-coordinates, y = (y1; : : : ; yN), locate the points (xi; yi), with i = 1; 2; : : : ; n and then join them by
straight lines. You need to prepare x and y in an identical array form; namely, x and y are both row arrays or
column arrays of the same length.
The MATLAB command to plot a graph is plot(x,y). The vectors x = (1; 2; 3; 4; 5; 6) and y = (3;¡1; 2; 4; 5;
1) produce the picture shown in below.
>> x = [1 2 3 4 5 6];
>> y = [3 -1 2 4 5 1];
>> plot (x,y)
2
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Note: 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.
For example, to plot the function sin (x) on the interval [0, 2π], we first create a vector of x values ranging
from 0 to 2π, then compute the sine of these values, and finally plot the result:
>> x = 0:pi/100:2*pi;
>> y = sin(x);
>> plot(x,y)
Notes:
- 0:pi/100:2*pi yields a vector that
- starts at 0,
- takes steps (or increments) of π/100,
- stops when 2π is reached.
- If you omit the increment, MATLAB automatically increments by 1.
3
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Suppose a set of time versus distance data were obtained through measurement. We can store the time values
in a vector called x (the user can define any convenient name) and the distance values in a vector called y :
x = [0:2:18];
y = [0, 0.33, 4.13, 6.29, 6.85, 11.19, 13.19, 13.96, 16.33,18.17];
plot(x,y)
4
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Good engineering practice requires that we include axis labels and a title in our plot. The following commands
add a title, x - and y -axis labels, and a background grid:
plot(x,y)
xlabel('Time, sec')
ylabel('Distance, ft')
grid on
These commands generate the plot in Figure below. As with any MATLAB commands, they could also be
combined onto one or two lines, separated by commas:
5
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
By default, MATLAB uses line style and color to distinguish the data sets plotted in the graph. However, you
can change the appearance of these graphic components or add annotations to the graph to help explain your
data for presentation.
It is possible to specify line styles, colors, and markers (e.g., circles, plus signs, . . . ) using the plot command:
Plot (x,y,'style_color_marker')
The following commands illustrate the use of line, color, and mark styles:
x = [1:10];
y = [58.5, 63.8, 64.2, 67.3, 71.5, 88.3, 90.1, 90.6, 89.5,90.4];
plot(x,y,':ok')
6
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Example:
Plot the polynomial 𝑦 = 𝑥 2 − 1 between x=0 and x=10 (using twenty points).
>>x=linspace(0,10,20); // or x=0:10/20:10;
>>y= x.^2-1;
>>plot(x,y)
7
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Lecture Nine
Plotting in MATLAB
SUBPLOTS
1
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
SUBPLOTS
You can use the subplot command to obtain several smaller “subplots” in the same figure. The subplot
command allows you to subdivide the graphing window into a grid of m rows and n columns. The function
subplot(m,n,p)
splits the figure into an m _ n matrix. The variable p identifies the portion of the window where the next plot
will be drawn. For example, if the command
subplot(2,2,1)
is used, the window is divided into two rows and two columns, and the plot is drawn in the upper left-hand
window (Figure below)
p=1 p=2
p=3 p=4
The windows are numbered from left to right, top to bottom. Similarly, the following commands split the
graph window into a top plot and a bottom plot.
subplot(3,2,5)
creates an array of six panes, three rows and two columns , and directs the next plot to appear in the fifth pane
(in the bottom left corner).
p=1 p=2
p=3 p=4
p=5 p=6
2
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Example 1:
- Subdivide a figure window into two rows and one column.
- In the top window, plot y = sin(x) for x from 0 to 2π with increment of π/20.
- In the bottom window, plot y = sin(2x) for the same range.
x = 0:pi/20:2*pi;
subplot(2,1,1)
plot(x,sin(x))
xlabel('x'),ylabel('y')
subplot(2,1,2)
plot(x,sin(2*x))
xlabel('x'),ylabel('y')
The first graph is drawn in the top window, since p =1. Then the subplot command is used again to draw the
next graph in the bottom window.
3
University of Anbar Computer Programming (MATLAB)
College of Engineering Dr. Maath Jasem
Dept. of Electrical Engineering 2019 - 2020
Example 2:
Use the subplot command to plot the functions (use an increment of 0.01):
𝑦 = |𝑥 3 − 100| 𝑓𝑜𝑟 − 6 ≤ 𝑥 ≤ 6
x = 0:0.01:5;
y = exp(-1.2*x).*sin(10*x+5);
subplot(1,2,1)
plot(x,y)
xlabel('x'),ylabel('y')
x = -6:0.01:6;
y = abs(x.^3-100);
subplot(1,2,2)
plot(x,y)
xlabel('x'),ylabel('y')