Array Operations and Linear Equations
Array Operations and Linear Equations
30
.* Element-by-element multiplication
./ Element-by-element division
.^ Element-by-element exponentiation
>> C = A.*B
produces another matrix C of the same size with elements cij = aij bij . For example, using
the same 3 × 3 matrices,
1 2 3 10 20 30
A= 4 5 6 ,
B = 40 50 60
7 8 9 70 80 90
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
>> 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 elements U = [ui ] and V = [vj ].
U. ∗ V produces [u1 v1 u2 v2 . . . un vn ]
U./V produces [u1 /v1 u2 /v2 . . . un /vn ]
U.ˆV produces [uv11 uv22 . . . uvnn ]
31
Operation Matrix Array
Addition + +
Subtraction − −
Multiplication ∗ .∗
Division / ./
Left division \ .\
Exponentiation ˆ .ˆ
Ax = b (3.2)
This equation can be solved for x using linear algebra. The result is x = A−1 b.
There are typically two ways to solve for x in MATLAB:
32
>> A = [1 2 3; 4 5 6; 7 8 0];
>> b = [1; 1; 1];
>> x = inv(A)*b
x =
-1.0000
1.0000
-0.0000
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
This problem is at the heart of many problems in scientific computation. Hence it is impor-
tant that we know how to solve this type of problem efficiently.
Now, we know how to solve a system of linear equations. In addition to this, we will
see some additional details which relate to this particular topic.
Calculating the inverse of A manually is probably not a pleasant work. Here the hand-
calculation of A−1 gives as a final result:
−16 8 −1
1
A−1 = 14 −7 2
9
−1 2 −1
33
>> A = [1 2 3; 4 5 6; 7 8 0];
>> inv(A)
ans =
-1.7778 0.8889 -0.1111
1.5556 -0.7778 0.2222
-0.1111 0.2222 -0.1111
>> det(A)
ans =
27
For further details on applied numerical linear algebra, see [10] and [11].
det Determinant
diag Diagonal matrices and diagonals of a matrix
eig Eigenvalues and eigenvectors
inv Matrix inverse
norm Matrix and vector norms
rank Number of linearly independent rows or columns
3.3 Exercises
Note: Due to the teaching class during this Fall Quarter 2005, the problems are temporarily
removed from this section.
34
Chapter 4
Introduction to programming in
MATLAB
4.1 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:
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
35
4.2.1 Examples
Here are two simple scripts.
Example 1
A = [1 2 3; 3 3 4; 2 3 3];
b = [1; 1; 2];
x = A\b
>> 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. 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.
There is another way to open the editor:
36
>> edit
or
to open filename.m.
Example 2
Plot the following cosine functions, y1 = 2 cos(x), y2 = cos(x), and y3 = 0.5 ∗ cos(x), in the
interval 0 ≤ x ≤ 2π. This example has been presented in previous Chapter. Here we put
the commands in a file.
x = 0:pi/100:2*pi;
y1 = 2*cos(x);
y2 = cos(x);
y3 = 0.5*cos(x);
plot(x,y1,’--’,x,y2,’-’,x,y3,’:’)
xlabel(’0 \leq x \leq 2\pi’)
ylabel(’Cosine functions’)
legend(’2*cos(x)’,’cos(x)’,’0.5*cos(x)’)
title(’Typical example of multiple plots’)
axis([0 2*pi -3 3])
• The execution of the script can be affected by the state variables in the workspace.
As a result, because scripts have some undesirable side-effects, it is better to code any
complicated applications using rather function M-file.
37
4.3 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.
f = prod(1:n); (4)
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. Table 4.1 summarizes the M-file function.
As an example, for n = 5, the result is,
>> f = factorial(5)
f =
120
Both functions and scripts can have all of these parts, except for the function definition
line which applies to function only.
38
In addition, it is important to note that function name must begin with a letter, and
must be no longer than 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.
Table 4.2 summarizes the differences between scripts and functions.
Scripts Functions
- Do not accept input - Can accept input arguments and
arguments or return output return output arguments.
arguments.
- Store variables in a - Store variables in a workspace
workspace that is shared internal to the function.
with other scripts
- Are useful for automating - Are useful for extending the MATLAB
a series of commands language for your application
39
4.3.2 Input and output arguments
As mentioned above, the input arguments are listed inside parentheses following the function
name. The output arguments are listed inside the brackets on the left side. They are used
to transfer the output from the function file. The general form looks like this
Function file can have none, one, or several output arguments. Table 4.3 illustrates some
possible combinations of input and output arguments.
We have already seen the two first cases. Here, we will focus our attention on the third one.
In this case, the variable is defined in the script file. When the file is executed, the user is
prompted to assign a value to the variable in the command prompt. This is done by using
the input command. Here is an example.
40
game2 = input(’Enter the points scored in the second game ’);
game3 = input(’Enter the points scored in the third game ’);
average = (game1+game2+game3)/3
The following shows the command prompt when this script file (saved as example3) is
executed.
>> example3
>> 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
The input command can also be used to assign string to a variable. For more information,
see MATLAB documentation.
A typical example of M-file function programming can be found in a recent paper which
related to the solution of the ordinary differential equation (ODE) [12].
41
4.6 Exercises
1. Liz buys three apples, a dozen bananas, and one cantaloupe for $2.36. Bob buys a dozen
apples and two cantaloupe for $5.26. Carol buys two bananas and three cantaloupe
for $2.77. How much do single pieces of each fruit cost?
3. Write a user-defined MATLAB function, with two input and two output arguments
that determines the height in centimeters (cm) and mass in kilograms (kg)of a person
from his height in inches (in.) and weight in pounds (lb).
(a) Determine in SI units the height and mass of a 5 ft.15 in. person who weight 180
lb.
(b) Determine your own height and weight in SI units.
42
Chapter 5
5.1 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. MATLAB has thousand of functions, and you can add your own using m-files.
MATLAB provides several tools that can be used to control the flow of a program
(script or function). In a simple program as shown in the previous Chapter, the commands
are executed one after the other. Here we introduce the flow control structure that make
possible to skip commands or to execute specific group of commands.
• if ... end
43
• if ... elseif ... else ... end
if expression
statements
end
44
5.2.2 Relational and logical operators
A relational operator compares two numbers by determining whether a comparison is true
or false. Relational operators are shown in Table 5.1.
Operator Description
Note that the “equal to” relational operator consists of two equal signs (==) (with no space
between them), since = is reserved for the assignment operator.
Usually, expression is a vector of the form i:s:j. A simple example of for loop is
for ii=1:5
x=ii*ii
end
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:
45
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
while expression
statements
end
x = 1
while x <= 10
x = 3*x
end
It is important to note that if the condition inside the looping is not well defined, the looping
will continue indefinitely. If this happens, we can stop the execution by pressing Ctrl-C.
• The continue statement can also be used to exit a for loop to pass immediately to
the next iteration of the loop, skipping the remaining statements in the loop.
• Other control statements include return, continue, switch, etc. For more detail
about these commands, consul MATLAB documentation.
46
5.2.6 Operator precedence
We can build expressions that use any combination of arithmetic, relational, and logical
operators. Precedence rules determine the order in which MATLAB evaluates an expression.
We have already seen this in the “Tutorial Lessons”.
Here we add other operators in the list. The precedence rules for MATLAB are shown
in this list (Table 5.2), ordered from highest (1) to lowest (9) precedence level. Operators
are evaluated from left to right.
Precedence Operator
1 Parentheses ()
2 Transpose (. 0 ), power (.ˆ), matrix power (ˆ)
3 Unary plus (+), unary minus (−), logical negation (∼)
4 Multiplication (. ∗), right division (. /), left division (.\),
matrix multiplication (∗), matrix right division (/),
matrix left division (\)
5 Addition (+), subtraction (−)
6 Colon operator (:)
7 Less than (<), less than or equal to (≤), greater (>),
greater than or equal to (≥), equal to (==), not equal to (∼=)
8 Element-wise AND, (&)
9 Element-wise OR, (|)
47
% write some variable length strings to a file
op = fopen(’weekdays.txt’,’wt’);
fprintf(op,’Sunday\nMonday\nTuesday\nWednesday\n’);
fprintf(op,’Thursday\nFriday\nSaturday\n’);
fclose(op);
This file (weekdays.txt) can be opened with any program that can read .txt file.
5.4 Exercises
Note: Due to the teaching class during this Fall Quarter 2005, the problems are temporarily
removed from this section.
48