Edward Neuman - Department of Mathematics
Edward Neuman
Department of Mathematics
Southern Illinois University at Carbondale
edneuman@siu.edu
Introduction to MATLAB
One of the nice features of MATLAB is its ease of computations with vectors and matrices. In this tutorial the following topics are discussed: vectors and matrices in MATLAB, solving systems of linear equations, the inverse of a matrix, determinants, vectors in n-dimensional Euclidean space, linear transformations, real vector spaces, and the matrix eigenvalue problem. Applications of linear algebra to the curve fitting, message coding, and computer graphics are also included.
Special Characters and MATLAB Functions
For the reader's convenience, we include lists of special characters and MATLAB functions that are used in this tutorial.
Special Characters
- Semicolon operator: ;
- Conjugated transpose: '
- Transpose: .'
- Times: *
- Dot operator: .
- Power operator: ^
- Empty vector operator: [ ]
- Colon operator: :
- Assignment: =
- Equality: ==
- Backslash or left division: \
- Right division: /
- Imaginary unit: i, j
- Logical not: ~
- Logical not equal: ~=
- Logical and: &
- Logical or: |
- Cell: { }
Function Description
- Inverse cosine: acos
- Control axis scaling and appearance: axis
- Create character array: char
- Cholesky factorization: chol
- Cosine function: cos
- Vector cross product: cross
- Determinant: det
- Diagonal matrices and diagonals of a matrix: diag
- Convert to double precision: double
- Eigenvalues and eigenvectors: eig
- Identity matrix: eye
- Filled 2-D polygons: fill
- Round towards zero: fix
- Flip matrix in left/right direction: fliplr
- Floating point operation count: flops
- Grid lines: grid
- Hadamard matrix: hadamard
- Hilbert matrix: hilb
- Hold current graph: hold
- Matrix inverse: inv
- True for empty matrix: isempty
- Graph legend: legend
- Length of vector: length
- Linearly spaced vector: linspace
- Convert numerical values to logical: logical
- Magic square: magic
- Largest component: max
- Smallest component: min
- Matrix or vector norm: norm
- Null space: null
- Convert numeric array into cell array: num2cell
- Convert number to string: num2str
- Ones array: ones
- Pascal matrix: pascal
- Linear plot: plot
- Convert roots to polynomial: poly
- Evaluate polynomial: polyval
- Uniformly distributed random numbers: rand
- Normally distributed random numbers: randn
- Matrix rank: rank
- Reduced row echelon form: rref
- Remainder after division: rem
- Change size: reshape
- Find polynomial roots: roots
- Sine function: sin
- Size of matrix: size
- Sort in ascending order: sort
- Symbolic substitution: subs
- Construct symbolic numbers and variables: sym
- Start a stopwatch timer: tic
- Graph title: title
- Read the stopwatch timer: toc
- Toeplitz matrix: toeplitz
- Extract lower triangular part: tril
- Extract upper triangular part: triu
- Vandermonde matrix: vander
- Variable length input argument list: varargin
- Zeros array: zeros
Creating and Transforming Vectors and Matrices in MATLAB
This section demonstrates how to create and transform vectors and matrices in MATLAB.
Creating Vectors
This command creates a row vector:
a = [1 2 3]
Result:
a = 1 2 3
Column vectors are inputted similarly, but semicolons must separate the components:
b = [1;2;3]
Result:
b = 1 2 3
Transpose and Conjugate Transpose
The quote operator ' is used to create the conjugate transpose of a vector (matrix), while the dot-quote operator .' creates the transpose vector (matrix). To illustrate this, let us form a complex vector a + i*b' and apply these operations to obtain:
(a+i*b')'
Result:
ans = 1.0000 - 1.0000i 2.0000 - 2.0000i 3.0000 - 3.0000i
While:
(a+i*b').'
Result:
ans = 1.0000 + 1.0000i 2.0000 + 2.0000i 3.0000 + 3.0000i
Vector Length
Command length returns the number of components of a vector:
length(a)
Result:
ans = 3
Componentwise Operations
The dot operator . plays a specific role in MATLAB. It is used for the componentwise application of the operator that follows the dot operator:
a.*a
Result:
ans = 1 4 9
The same result is obtained by applying the power operator ^ to the vector a:
a.^2
Result:
ans = 1 4 9
Componentwise division of vectors a and b can be accomplished using the backslash operator \ together with the dot operator:
a.\b'
Result:
ans = 1 1 1
Dot and Outer Product
For the next example, let us change vector a to the column vector:
a = a'
Result:
a = 1 2 3
The dot product and the outer product of vectors a and b are calculated as follows:
dotprod = a'*b
Result:
dotprod = 14
Outer product:
outprod = a*b'
Result:
outprod = 1 2 3 2 4 6 3 6 9
Cross Product
The cross product of two three-dimensional vectors is calculated using the command cross. Let vector a be the same as above and let:
b = [-2 1 2];
Note that the semicolon after a command avoids the display of the result. The cross product of a and b is:
cp = cross(a,b)
Result:
cp = 1 -8 5
The cross product vector cp is perpendicular to both a and b:
[cp*a cp*b']
Result:
ans = 0 0
Matrix Operations
We will now deal with operations on matrices. Addition, subtraction, and scalar multiplication are defined in the same way as for the vectors.
Matrix Creation
This creates a 3-by-3 matrix:
A = [1 2 3;4 5 6;7 8 10]
Result:
A = 1 2 3 4 5 6 7 8 10
Note that the semicolon operator ; separates the rows.
Submatrix Extraction
To extract a submatrix B consisting of rows 1 and 3 and columns 1 and 2 of the matrix A:
B = A([1 3], [1 2])
Result:
B = 1 2 7 8
Row Interchange
To interchange rows 1 and 3 of A, use the vector of row indices together with the colon operator:
C = A([3 2 1],:)
Result:
C = 7 8 10 4 5 6 1 2 3
The colon operator : stands for all columns or all rows. For the matrix A from the last example, the following command:
A(:)
Result:
ans = 1 4 7 2 5 8 3 6 10
Creates a vector version of the matrix A.
Row Deletion
To delete a row (column) use the empty vector operator [ ]:
A(:, 2) = []
Result:
A = 1 3 4 6 7 10
The second column of the matrix A is now deleted.
Row Insertion
To insert a row (column), we use the technique for creating matrices and vectors:
A = [A(:,1) [2 5 8]' A(:,2)]
Result:
A = 1 2 3 4 5 6 7 8 10
Matrix A is now restored to its original form.
Matrix Entry Extraction
Using MATLAB commands, one can easily extract those entries of a matrix that satisfy an imposed condition. Suppose that one wants to extract all entries that are greater than one. First, we define a new matrix:
A = [-1 2 3;0 5 1]
Result:
A = -1 2 3 0 5 1
Command A > 1 creates a matrix of zeros and ones:
A > 1
Result:
ans = 0 1 1 0 1 0
With ones on positions where the entries of A satisfy the imposed condition and zeros everywhere else. This illustrates logical addressing in MATLAB. To extract those entries of the matrix A that are greater than one, execute the following command:
A(A > 1)
Result:
ans = 2 5 3
Entry-by-Entry Product
The dot operator . works for matrices too. Let now:
A = [1 2 3; 3 2 1];
The following command:
A.*A
Result:
ans = 1 4 9 9 4 1
Computes the entry-by-entry product of A with A. However, the following command:
A*A
Generates an error message:
Error using ==> *Inner matrix dimensions must agree.
Diagonal Matrices
Function diag will be used on several occasions. This creates a diagonal matrix with the diagonal entries stored in the vector d:
d = [1 2 3]; D = diag(d)
Result:
D = 1 0 0 0 2 0 0 0 3
To extract the main diagonal of the matrix D, use function diag again:
d = diag(D)
Result:
d = 1 2 3
Linear Combination of Matrices
In some problems that arise in linear algebra, one needs to calculate a linear combination of several matrices of the same dimension. In order to obtain the desired combination, both the coefficients and the matrices must be stored in cells. In MATLAB, a cell is inputted using curly braces { }.
This is an example of the cell:
c = {1,-2,3}
Result:
c = [1] [-2] [3]
Function lincomb will be used later on in this tutorial.
function M = lincomb(v,A)
% Linear combination M of several matrices of the same size.
% Coefficients v = {v1,v2,…,vm} of the linear combination and the
% matrices A = {A1,A2,...,Am} must be inputted as cells.
m = length(v);
[k, l] = size(A{1});
M = zeros(k, l);
for i = 1:m
M = M + v{i}*A{i};
end
Solving Systems of Linear Equations
MATLAB has several tools needed for computing a solution of the system of linear equations. Let A be an m-by-n matrix and let b be an m-dimensional (column) vector. To solve the linear system Ax = b, one can use the backslash operator \, which is also called the left division.
Case m = n
In this case, MATLAB calculates the exact solution (modulo the roundoff errors) to the system in question.
Let:
A = [1 2 3;4 5 6;7 8 10]
Result:
A = 1 2 3 4 5 6 7 8 10
And let:
b = ones(3,1);
Then:
x = A\b
Result:
x = -1.0000 1.0000 0.0000
In order to verify the correctness of the computed solution, let us compute the residual vector r:
r = b - A*x
Result:
r = 1.0e-015 * 0.1110 0.6661 0.2220
Entries of the computed residual theoretically should all be equal to zero. This example illustrates an effect of the roundoff errors on the computed solution.
Case m > n
If m > n, then the system Ax = b is overdetermined, and in most cases, the system is inconsistent. A solution to the system Ax = b, obtained with the aid of the backslash operator \, is the least-squares solution.
Let now:
A = [2 -1; 1 10; 1 2];
And let the vector of the right-hand sides be the same as the one in the last example. Then:
x = A\b
Result:
x = 0.5849 0.0491
The residual r of the computed solution is equal to:
r = b - A*x
Result:
r = -0.1208 -0.0755 0.3170
Theoretically, the residual r is orthogonal to the column space of A. We have:
r'*A
Result:
ans = 1.0e-014 * 0.1110 0.6994
Case m < n
If the number of unknowns exceeds the number of equations, then the linear system is underdetermined. In this case, MATLAB computes a particular solution provided the system is consistent. Let now:
A = [1 2 3; 4 5 6];
And:
b = ones(2,1);
Then:
x = A\b
Result:
x = -0.5000 0.5000
A general solution to the given system is obtained by forming a linear combination of x with the columns of the null space of A. The latter is computed using the MATLAB function null:
z = null(A)
Result:
z = 0.4082 -0.8165 0.4082
Suppose that one wants to compute a solution being a linear combination of x and z, with coefficients 1 and -1. Using function lincomb, we obtain:
w = lincomb({1,-1},{x,z})
Result:
w = -0.9082 0.8165 0.0918
The residual r is calculated in a usual way:
r = b - A*w
Result:
r = 1.0e-015 * -0.4441 0.1110
Reduced Row Echelon Form
The built-in function rref allows a user to solve several problems of linear algebra. In this section, we shall employ this function to compute a solution to the system of linear equations and also to find the rank of a matrix. Other applications are discussed in the subsequent sections of this tutorial.
Function rref takes a matrix and returns the reduced row echelon form of its argument. Syntax of the rref command is:
B = rref(A) [B, pivot] = rref(A)
The second output parameter pivot holds the indices of the pivot columns.
Let:
A = magic(3); b = ones(3,1);
A solution x to the linear system Ax = b is obtained in two steps.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
-
Appunti Calcolo numerico + Matlab
-
Calcolo numerico teoria + Matlab
-
Calcolo numerico - il calcolo scientifico
-
Calcolo Numerico – Elaborato