Numerical_Methods_Chap2
Numerical_Methods_Chap2
Contents
1 Getting started with MATLAB 3
1.1 Main characteristics of Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 What is Matlab? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.2 Strengths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.3 Weaknesses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Opening a Matlab session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Modes of operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.1 Interactive mode: using Matlab as a calculator . . . . . . . . . . . . . . . . . 4
1.3.2 Creating a script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4.1 Naming variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4.2 Special variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4.3 State of a variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5 Mathematical functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5.1 Built-in functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5.2 User-defined functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.6 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.6.1 What is an array? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.6.2 Generating arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.6.3 Special arrays and preallocation . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.6.4 Other operations on an array . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.6.5 Vector and matrix indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7 Flow control structures in Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7.1 Flow controls possibilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7.2 Loop structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.8 Efficient programming with Matlab: vectorization . . . . . . . . . . . . . . . . . . . 9
1.8.1 Efficient programming techniques . . . . . . . . . . . . . . . . . . . . . . . . 9
1.8.2 Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.9 Miscellenous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.10 Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1
3 Graphics and Visualization with MATLAB 14
3.1 2D Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.2 Subplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.3 3D Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2
1 Getting started with MATLAB
1.1 Main characteristics of Matlab
1.1.1 What is Matlab?
MATLAB was derived from ”Matrix Laboratory”. It is a technical computing environment whose
basic data type is the matrix (or array). That software package was originally designed for solving
numerical analysis and linear algebra type problems using matrices. Matlab is widely used in
engineering since it is well-suited for circuit analysis, signal processing, filter design, optimization,
graphics and animation, data analysis, etc. Matlab can be thought of as an advanced programming
language just like C, Fortran, and Python. MATLAB is more convenient for numerical analysis and
linear algebra.
Note that MATLAB is a registered trademark of MathWorks, Inc.
1.1.2 Strengths
The advantage of working with MATLAB are that:
- MATLAB may behave as a calculator or as a programming language
- MATLAB combine nicely calculation and graphic plotting
- MATLAB is relatively easy to learn
- MATLAB is interpreted (not compiled), errors are easy to fix
- MATLAB is optimized to be relatively fast when performing matrix operations
- MATLAB does have some object-oriented elements
1.1.3 Weaknesses
The issues with working with MATLAB are that:
- MATLAB is not a general purpose programming language such as C, C++, or FORTRAN
- MATLAB is designed for scientific computing, and is not well suitable for other applications
- MATLAB is an interpreted language, slower than a compiled language such as C++
- MATLAB commands are specific for MATLAB usage. Most of them do not have a direct
equivalent with other programming language commands
Note that competitors of Matlab are Python, Scilab, GNU Octave, Rlab, and Mathematica (very
good at symbolic computations).
3
1.3 Modes of operation
Matlab is useful for computing, visualizing and programming. It offers two modes of operation:
An interactive mode when statements are typed in a terminal/prompt (or login shell) and exe-
cuted immediately. In this mode, Matlab can be used as a calculator.
A script/code or batch mode when statements are written to form a code using an editor, then
saved on the disc as a text file or script before being run/executed).
4
x =
7
1.4 Variables
By default, Matlab’s variables are arrays. To create a variable, simply assign a value to a name.
5
>> pi=2;
>> pi outputs 2.
Example 4:
>> clear restores the default value.
1.6 Arrays
1.6.1 What is an array?
MATLAB treats all variables as arrays or tables. A matrix can be thought of as an array of order
or size n-by-m where n and m are all greater that one. Vectors are arrays that contain only one
6
row (row vector) OR one column (column vector). Scalars are matrices with only one row AND one
column.
7
• det : Matrix determinant
• inv : matrix inverse
• eig : evaluates eigenvalues and eigenvectors
• rank : rank of a matrix
8
else
commands3
end
Too many elseif’s? consider using switch
• for loops: use for a known number of iterations. Syntax:
The loop variable is defined as a vector, is a scalar within the command block, does not have to
have consecutive values (but it’s usually cleaner if they’re consecutive).
The command block is anything between the for line and the end.
• while loop The while loop is like a more general for loop, but is used when we do not need to
know number of iterations.
The command block will execute while the conditional expression is true.
Note: Beware of infinite looping! Use CTRL+C to force-stop the compilation! You can use break
to exit a loop.
1.8.2 Vectorization
Vectorization consists in avoiding the use of loops to increase the efficiency of a code in MATLAB. We
can use indexing and matrix operations to avoid loops. For instance, to add every two consecutive
terms.
Example 1: complicated and slow
a=rand(1,100); b=zeros(1,100);
for n=1:100
if n==1
b(n)=a(n);
else b(n)=a(n-1)+a(n);
end
end
Example 2: short and efficient
a=rand(1,100);
b=[0 a(1:end-1)]+a;
1.9 Miscellenous
• Commenting a statement: anything following the sign % is interpreted as a comment.
a %this is a comment
• Redeeming previous computation result (on the terminal):
>> a;
>> ans
Pressing UP direction key from the keyboard also writes ans and importantly, it allows to
browse the previous computations done on the terminal.
• Displaying
Displaying a result or the content of a variable
disp(a)
9
sprintf(a)
a % end the line without semicolon
Displaying a result with a text
disp(’Below is the value of a’)
disp(strcat(’The value of a=’, num2str(a)))
fsprintf(strcat(’The value of a=’, num2str(a)))
Displaying a formatted (boldtype) text
disp(’Hello <strong>World</strong>!’)
fsprintf(’Hello <strong>World</strong>! \n’)
1.10 Help
help is the most useful command to learn Matlab on your own. Where/how to get help? Click
on the help button or on F1 keyboard. Then you can search a function by typing keywords in the
search area of the new window that appears. Equivalent commands in MATLAB’s prompt type
are: help, lookfor, helpwin, helpdesk, demos
Help can also be obtained on the Web at:
http://www.mathworks.com/support
http://www.mathworks.com/products/demos/#
http://www.math.siu.edu/MATLAB/tutorials.html
http://math.ucsd.edu/~driver/21d -s99/MATLAB-primer.html
http://www.mit.edu/~pwb/cssm/
http://www.eecs.umich.edu/~aey/eecs216/.html
10
Matrix dimensions must agree.
Example:
>> a = [12,10,-3]; b = [3,5,6];
>> a+b
>> a-b
Matlab can increment all the elements of a matrix by a single value as follows:
Example:
>> a = [12,10,-3];
>> a+5
ans =
17 15 2
2.2.2 Multiplication
• Scalar multiplication
It is the multiplication of a matrix by a (real) number.
Example:
>> a = [12,10,-3;3,5,6]; b=2*a
• Matrix multiplication
Matrix multiplication in Matlab obeys linear algebra. In computing the product A*B, the number
of columns of matrix A should be the same as the number of rows of matrix B.
Example:
>> a = [12,10,-3;3,5,6]; b=[2;4;8]; a*b
11
2.2.4 Extracting a submatrix
Unlike C and Python, the index of an element in a Matlab’s array starts at 1 and ends at end.
A portion of a matrix can be extracted and stored in a smaller matrix by specifying the names
of both matrices and the rows and columns to extract.
The syntax for an element is:
a_nm = matrix ( n , m ) ;
Example :
>> X = [1,2,3; 4,5,6; 7,8,9]
>> X_23 = X(2,3)
The syntax for a submatrix is:
sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;
where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the beginning and
ending columns to be extracted to make the new matrix.
Example :
>> X = [1,2,3;4,5,6;7,8,9]
>> R3 = X(3,1:3)
>> R3 = X(3,:)
>> C2 = X(1:3,2)
>> C2 = X(:,2)
>> A13 = X(3,1:3)
>> A22 = X(1:2 , 2:3)
>> A21 = X(1:2,1)
12
Counter-Example:
>> [a,a;a]
• Form a block matrix by replication.
repmat – replicates and tiles a matrix:
>> b = [0,2;3,5]
b =
0 2
3 5
>> b_rep = repmat(b,1,3)
b_rep =
0 2 0 2 0 2
3 5 3 5 3 5
13
2.3.2 Logical operators
MATLAB supports three logical operators:
not ~ (highest precedence)
and & (equal precedence with OR)
or | (equal precedence with AND)
3.1 2D Plotting
The plot function generates dots at each (x, y) pair and then connects thedots with a line. The
vectors x and y must be same size or else an error message will be got.
Example:
x=linspace(0,2*pi,10); (evaluate at 10 points)
y=sin(x);
plot(y); (Plot values of y against their index)
plot(x,y); (Plot y against x)
To make plot of a function look smoother, evaluate at more points.
Explore plot options (color, marker, line style, ...). Look at help plot for a full list of colors,
markers, and line styles.
Exercise:
Open a new figure (use figure). Plot sin(x) and cos(x) over [0, 2π], on the same plot with
different colours.
3.2 Subplots
Subplot function allows to have multiple axes in one figure.
E.g. subplot(2,3,1) makes a figure with 2 rows and 3 columns of axes, and activates the first
axis for plotting. Each axis can have labels, a legend, and a title.
E.g. subplot(2,3,4:6) activates a range of axes and fuses them into one.
3.3 3D Plotting
We can plot in 3 dimensions just as easily as in 2D.
• 3D line plots
Example
time=0:0.001:4*pi; z=time; y=cos(time); x=sin(time);
plot3(x,y,z, ’k’, ’LineWidth’,2); zlabel(’time’)
• Surface plots and contour plots
Use surf, surfc, mesh, meshc, contour, contourf, pcolor...
surf puts vertices at specified points in the space (x,y,z), and connects all the vertices to make
a surface.
Example
x=-pi:0.001:pi; y=-pi:0.001:pi; [X,Y]=meshgrid(x,y); F=cos(X).*sin(Y);
surf(x,y,F)
surf(X,Y,F)
contour(X,Y,F)
NOTE:
We can use tools on figure to rotate it.
14
We can set limits on all 3 axes Use xlim, ylim, zlim.
We can change the colormap.
References
[1] David Houcque, Introduction to Matlab programming, Lecture notes, Northwestern University,
(version 1.2, August 2005)
15