C1&2
C1&2
C1&2
The name MATLAB stands for matrix laboratory. MATLAB allows you to focus on your course work and applications rather
than on programming details. It enables you to solve many numerical problems in a fraction of the time it would take you to
write a program in a lower-level language such as C, C++, or Fortran.
Simulink is an interactive tool for modeling, simulating, and analyzing dynamic systems, including controls, signal processing,
communications, and other complex systems.
Many college courses recommend MATLAB as standard instructional software. In some cases, the courses may require
particular toolboxes. Toolboxes are add-on products that extend MATLAB and Simulink with domain-specific capabilities.
Some of the toolboxes include: Symbolic Math Toolbox, Control System Toolbox, Image Processing Toolbox, Signal
Processing Toolbox, Bioinformatics Toolbox, Statistics Toolbox …etc.
1
The MATLAB system consists of five main parts:
➢ Development Environment: This is the set of tools and facilities that help you use MATLAB functions and files. Many of
these tools are graphical user interfaces. It includes the MATLAB desktop, a command Window, a command history, an
editor and debugger, browsers for viewing help, the workspace, files, and the search path.
➢ The MATLAB Mathematical Function Library: This is a vast collection of computational algorithms ranging from
elementary functions, like sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse,
matrix eigenvalues, Bessel functions, and fast Fourier transforms.
➢ The MATLAB Language: This is a high-level matrix/array language with control flow statements, functions, data structures,
input/output, and object-oriented programming features. It allows both “programming in the small” to rapidly create
quick and dirty throw-away programs, and “programming in the large” to create large and complex application programs.
➢ Graphics: MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing
these graphs. It includes high-level functions for two-dimensional and three-dimensional data visualization, image
processing, animation, and presentation graphics. It also includes low-level functions that allow you to fully customize the
appearance of graphics as well as to build complete graphical user interfaces on your MATLAB applications.
➢ The MATLAB Application Program Interface (API): This is a library that allows you to write C and Fortran programs that
interact with MATLAB. It includes facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a
computational engine, and for reading and writing MAT-files.
2
MATLAB Desktop
3
Chapter 2: Matrices and Arrays
Entering matrices
You only have to follow a few basic conventions:
• Separate the elements of a row with blanks or commas.
• Use a semicolon, ; , to indicate the end of each row.
• Surround the entire list of elements with square brackets, [ ].
1 −15 3 0
To enter the matrix 7 4 20 −5 , simply type in the Command Window: A = [1 -15 3 0; 7 4 20 -5; 2 9 -1 6; 6 -4 8 10]
2 9 −1 6
6 −4 8 10
Once you have entered the matrix, it is automatically remembered in the MATLAB workspace. You can refer to it simply as A.
ans = When you do not specify an output variable, You have computed a row
MATLAB uses the variable ans, short for answer, to vector containing the sums
16 -6 30 11 store the results of a calculation of the columns of A. 4
How about the row sums?
The easiest way to get the row sums using Matlab is to transpose the matrix, compute the column sums of the transpose, and
then transpose the result. The transpose operation is denoted by an apostrophe or single quote, '.
So and
A’ sum(A')’
ans = ans =
1 7 2 6 -11
-15 4 9 -4 26
3 20 -1 8 16
0 -5 6 10 20
5
The other diagonal, the so-called antidiagonal, is not so
Q1: How do we obtain the sum of the main important mathematically, so MATLAB does not have a
diagonal of matrix A ? ready-made function for it. But a function originally
intended for use in graphics, fliplr, flips a matrix from left
The sum of the elements on the main diagonal is to right.
obtained with the sum and the diag functions.
diag(A) Q2: What is the result of the command fliplr(A) and how to
obtain the sum of the antidiagonal for the matrix A using this
produces: command ?
ans =
1
sum(diag(fliplr(A)))
4
ans =
-1
10
35
and
sum(diag(A))
produces:
ans =
14
6
1 −15 3 0
7 4 20 −5
A=
2 9 −1 6
6 −4 8 10
Subscripts
The element in row i and column j of A is denoted by A(i,j). For example, A(4,2) is the number in the fourth row and second
column. For our matrix, A(4,2) is -4.
So to compute the sum of the elements in the fourth column of A, type A(1,4) + A(2,4) + A(3,4) + A(4,4). This produces:
ans =
11
It is also possible to refer to the elements of a matrix with a single subscript, A(k). This is the usual way of referencing row
and column vectors. But it can also apply to a fully two-dimensional matrix, in which case the array is regarded as one long
column vector formed from the columns of the original matrix. So, for our matrix, A(8) is another way of referring to the
value -4 stored in A(4,2).
If you try to use the value of an element outside of the matrix, it is an error.
t = A(4,5)
Index exceeds matrix dimensions. X=
1 -15 3 0 0
On the other hand, if you store a value in an element outside of the matrix, the
7 4 20 -5 0
size increases to accommodate the newcomer.
2 9 -1 6 0
X = A; 7
6 -4 8 10 17
X(4,5) = 17
The colon, :, is one of the most important MATLAB operators. It occurs in several different forms. The expression
1:10
1 2 3 4 5 6 7 8 9 10
100:-7:50
is
100 93 86 79 72 65 58 51
and
0:pi/4:pi
is
But there is a better way. The colon by itself refers to all the elements in a row or column of a matrix and the keyword
end refers to the last row or column. So
sum(A(:,end))
computes the sum of the elements in the last column of A.
ans =
11
To swap two rows or the two columns, for exapmle the two middle columns,
C = A(:,[1 3 2 4])
This says, for each of the rows of matrix A, reorder the columns in the order 1, 3, 2, 4. It produces:
C=
1 3 -15 0
7 20 4 -5
2 -1 9 6
6 8 -4 10
9
Exercise 1:
Then calculate:
1. The sum of different rows
2. The sum of different columns
3. The sum of the two main diagonals
4. Only the sum of third column
5. The mean value of the sum of different rows using the mean command
6. The mean value of the sum of different columns using the mean command
10
Expressions
Like most other programming languages, MATLAB provides mathematical expressions, but unlike most programming
languages, these expressions involve entire matrices. The building blocks of expressions are:
• Variables
• Numbers
• Operators
• Functions
Variables
MATLAB does not require any type declarations or dimension statements. When MATLAB encounters a new variable name,
it automatically creates the variable and allocates the appropriate amount of storage. If the variable already exists,
MATLAB changes its contents and, if necessary, allocates new storage.
For example,
num_students = 25
creates a 1-by-1 matrix named num_students and stores the value 25 in its single element.
Variable names consist of a letter, followed by any number of letters, digits, or underscores. MATLAB uses only the first 31
characters of a variable name. MATLAB is case sensitive; it distinguishes between uppercase and lowercase letters. A and a
are not the same variable. To view the matrix assigned to any variable, simply enter the variable name.
11
Numbers
MATLAB uses conventional decimal notation, with an optional decimal point and leading plus or minus sign, for numbers.
Scientific notation uses the letter e to specify a power-of-ten scale factor. Imaginary numbers use either i or j as a suffix.
Some examples of legal numbers are:
3 -99 0.0001
1i -3.14159j 3e5i
Operators
+ Addition
- Subtraction
* Multiplication
/ Division
\ Left division (described in “Matrices and Linear Algebra” in the MATLAB documentation)
^ Power
‘ Complex conjugate transpose
() Specify evaluation order
12
Functions
MATLAB provides a large number of standard elementary mathematical functions, including abs, sqrt, exp, and sin. MATLAB
also provides many more advanced mathematical functions, including Bessel and gamma functions. For a list of the
elementary mathematical functions, type:
help elfun
help specfun
Also:
help elmat
Some of the functions, like sqrt and sin, are built in. Built-in functions are part of the MATLAB core so they are very efficient,
but the computational details are not readily accessible. Other functions, like gamma and sinh, are implemented in M-files.
Difference between built-in functions and other functions: for built-in functions, you cannot see the code. for other
functions, you can see the code and even modify it if you want.
13
Several special functions provide values of useful constants.
pi 3.14159265…
i Imaginary unit, −1
j Same as i
eps Floating-point relative precision, 𝜀 = 2−52
realmin Smallest floating-point number,
realmax Largest floating-point number,
Inf Infinity
NaN Not-a-number
✓ Infinity is generated by dividing a nonzero value by zero, or by evaluating well defined mathematical expressions that
overflow, i.e., exceed realmax.
✓ Not-a-number is generated by trying to evaluate expressions like 0/0 or Inf-Inf that do not have well defined mathematical
values.
Remark:
The function names are not reserved. It is possible to overwrite any of them with a new variable, such as
eps = 1.e-6
and then use that value in subsequent calculations. The original function can be restored with
clear eps 14
Examples of Expressions: Generating Matrices
rho = (1+sqrt(5))/2 MATLAB provides four functions that generate basic matrices:
rho = ✓ Zeros All zeros
1.6180 ✓ Ones All ones
✓ Rand Uniformly distributed random elements
a = abs(3+4i) ✓ Randn Normally distributed random elements
a=
5
Examples:
huge = exp(log(realmax)) Z = zeros(2,4) F = 5*ones(3,3) R = randn(4,4)
huge =
1.7977e+308 Z= F= R=
0 0 0 0 5 5 5 -1.3499 0.7147 1.4090 0.7172
toobig = pi*huge 0 0 0 0 5 5 5 3.0349 -0.2050 1.4172 1.6302
toobig = 5 5 5 0.7254 -0.1241 0.6715 0.4889
Inf -0.0631 1.4897 -1.2075 1.0347
N = fix(10*rand(1,10))
N=
8 9 1 9 6 0 2 5 9 9
15
The load Function
The text file should be organized as a rectangular table of numbers, separated by blanks, with one row per line, and an equal
number of elements in each row.
Example 1:
Outside of MATLAB, create a text file containing these two lines:
01234
56789
Store the file under the name x1.txt. Then, the statement:
load x1.txt
reads the file and creates a variable, x1, containing our example 1 matrix.
M-Files:
You can create your own matrices using M-files, which are text files containing MATLAB code.
Example 2:
For example, create a text file containing: x2=[0 1 2 3 4 ; 5 6 7 8 9]
Store the file under the name, for exapmle, File1.m. Then the statement
File1
reads the file and creates a variable, x2, containing our example 2 matrix.
16
Concatenation
Concatenation is the process of joining small matrices to make bigger ones. For an example, start with the 2-by-2 matrix,
A=[1 2 ; 3 4], and form
B = [A 2*A; -2*A -A]
The result is a 4-by-4 matrix, obtained by joining the four submatrices.
.* Element-by-element multiplication Note that the elementary math functions operate on arrays
element by element. For example:
./ Element-by-element division
x = (1:0.1:2)'
.\ Element-by-element left division
logs = [x log10(x)]
builds a table of logarithms.
.^ Element-by-element power
logs =
.’ Unconjugated array transpose
1.0000 0
1.1000 0.0414
1.2000 0.0792
1.3000 0.1139
1.4000 0.1461
1.5000 0.1761
1.6000 0.2041
1.7000 0.2304
1.8000 0.2553
1.9000 0.2788
2.0000 0.3010 19
Logical Subscripting
Suppose A is an ordinary matrix and L is a matrix of the same size that is the result of some logical operation. Then A(L)
specifies a row which contains the elements of X where the elements of L are nonzero.
This kind of subscripting can be done in one step by specifying the logical operation as the subscripting expression.
x = [2.1 1.7 1.6 1.5 NaN 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8];
The NaN is a marker for a missing observation, such as a failure to respond to an item. To remove the missing data with
logical indexing, use isfinite(x), which is true for all finite numerical values and false for NaN and Inf.
x = x(isfinite(x))
x=
2.1 1.7 1.6 1.5 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8
Now there is one observation, 5.1, which seems to be very different from the others. It is an outlier. The following statement
removes outliers, in this case those elements more than three from the mean.
x = x(abs(x-mean(x)) <= 3)
x=
2.1 1.7 1.6 1.5 1.9 1.8 1.5 1.8 1.4 2.2 1.6 1.8
20
For another example, highlight the location of the prime numbers in the square matrix using isprime(A), logical indexing
and scalar expansion to set the nonprime numbers to to 0.
A=
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
A(~isprime(A)) = 0
A=
0 3 2 13
5 0 11 0
0 0 7 0
0 0 0 0
The find Function
The find function determines the indices of array elements that meet a given
logical condition L. In its simplest form, find returns a column vector of
indices. Again, for example:
A= k = find(isprime(A))'
16 3 2 13
5 10 11 8 picks out the locations, using one-dimensional indexing, of the primes in the square matrix A.
9 6 7 12 k=
4 15 14 1 2 5 9 10 11 13
21
Controlling the Command Window Input and Output
The format Function
The format function controls the numeric format of the values displayed by MATLAB. The function affects only how numbers
are displayed, not how MATLAB computes or saves them.
x = [4/3 1.2345e-6]
format short
1.3333 0.0000 format long g
1.33333333333333 1.2345e-006
format short e
1.3333e+000 1.2345e-006 format bank
1.33 0.00
format short g
1.3333 1.2345e-006 format rat
4/3 1/810045
format long
1.33333333333333 0.00000123450000
format long e
1.333333333333333e+000 1.234500000000000e-006 22
Suppressing Output
If you simply type a statement and press Enter, MATLAB automatically displays the results on screen. However, if you end the
line with a semicolon, MATLAB performs the computation but does not display any output. This is particularly useful when you
generate large matrices. For example,
A = ones(100);
Entering Long Statements
If a statement does not fit on one line, use an ellipsis (three periods), ..., followed by Enter to indicate that the statement
continues on the next line. For example,
Note that blank spaces around the =, +, and - signs are optional, but they improve readability.
Command Line Editing
23
24