The Language of Technical Computing
Reference:Kermit Sigmon, MATLAB Primer, Third Edition. Department of Mathematics University of Florida
On most systems, after logging in one can enter MATLAB with the system command
However, your local installation may permit MATLAB to be accessed from a menu or by clicking an icon.
Type the following command to add 2 numbers in the command window right after the command prompt >>
>> 13+24
ans = 37
The summand 37 of 13 and 24 is stored in the default variable called ans which is short for answer.
We can write comments in Matlab following the
13+24
ans = 37
All the characters in a given line that follow the percent character
It is very helpful to comment what is being done in the code.
You can create or reopen a diary file in Matlab to record your work.
Everything you typed or input and the corresponding output in the command window will be recorded in the diary file.
You can create or reopen a diary file by typing diary filename.txt
in
the command window.
>> diary blah.txt
>> 3+56
ans = 59
When you have finished recording, simply type diary off in the command window to turn off the diary file.
>> diary off
>> type blah.txt
3+56 ans = 59 diary off
>> diary blah.txt
>> 45-54
ans = -9
>> diary off
>> type blah.txt
3+56 ans = 59 diary off 45-54 ans = -9 diary off
The diary file with
To save space in these notes, we suppress the blank lines and excessive line breaks present in Matlab 's command window.
get(0,'diary')
Let's learn to store values in variables of our choice. Type the following at the command prompt :
>> VariableCalledX = 12
Matlab stores default value for some variables, such as pi ($\pi$), i and j (complex numbers).
>> pi ans = 3.1416 >> i ans = 0 + 1.0000i >> j ans = 0 + 1.0000i
All predefined symbols (variables, constants, function names, operators, etc) in Matlab are written in lower-case.
Therefore, it is a good practice to name the variable you define using upper and mixed case letters in order to prevent an unintended overwrite of some predefined Matlab symbol.
>> pi ans = 3.1416 >> eps ans = 2.2204e-16 >> inf ans = Inf >> NaN ans = NaN >> realmax ans = 1.7977e+308 >> i ans = 0 + 1.0000i >> j ans = 0 + 1.0000i
We can suppress the output on the screen by ending the command with a semi-colon.
>> p=45.89*1.00009; % multiplication >> m=5376.0-6.00; % subtraction >> d=89.0/23.3454; % division >> p=2^0.5; % exponentiation >> Sqrt_of_2=2^(1/2) Sqrt_of_2 = 1.4142 >> 2^1/2 ans = 1 >> 10/0 ans = Inf
We can clear the value we have assigned to a particular variable and reuse it. We demonstrate it by the following commands and their output:
>> X=7 X = 7 >> clear X >> X ??? Undefined function or variable 'X'.
Entering X after clearing it gives the above self-explanatory error message preceded by ???.
If you do not understand a Matlab function or command then type
>> help sin SIN Sine of argument in radians. SIN(X) is the sine of the elements of X. See also asin, sind. Overloaded methods: codistributed/sin Reference page in Help browser doc sin >> doc sin% this will open Help browser
Set the variable x to equal 17.13 and evaluate $\cos(x)$, $\log(x)$, $\exp(x)$, $\arccos(x)$, $|x|$, $\text{sign}(x)$
using the Matlab commands
>> x=17.13; >> cos(x) ans = -0.1482 >> log(x) ans = 2.8408 >> exp(x) ans = 2.7508e+07 >> arccos(x) ??? Undefined function or method 'arccos' for input arguments of type 'double'. >> acos(x) ans = 0 + 3.5331i >> abs(x) ans = 17.1300 >> sign(x) ans = 1
When we work with real numbers (floating-point numbers) or really large numbers, we might want the output to be displayed in concise notation.
This can be controlled in Matlab using the
>> format compact >> Y=15; >> Y = Y + acos(-1) Y = 18.1416 >> format short >> Y Y = 18.1416 >> format short e >> Y Y = 1.8142e+001 >> format long >> Y Y = 18.141592653589793 >> format long e >> Y Y = 1.814159265358979e+001 >> format >> Y Y = 18.1416
An M-file is a special text file with a
In this course we will be using two types of M-files: script and function files.
A script file is simply a list of commands that we want executed and saves us from retyping code modules we are pleased with.
A function file allows us to write specific tasks as functions with input and output. These functions can be called from other script files, function files or command window.
MATLAB works with essentially only one kind of object — a rectangular numerical matrix with possibly complex entries; all variables represent matrices.
In some situations, 1-by-1 matrices are interpreted as scalars and matrices with only one row or one column are interpreted as vectors.
For example, either of the statements
A = [1 2 3; 4 5 6; 7 8 9]and
A = [ 1 2 3 4 5 6 7 8 9 ]
creates the obvious 3-by-3 matrix and assigns it to a variable A.
>> A = [1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 >> A = [ 1 2 3 4 5 6 7 8 9 ] A = 1 2 3 4 5 6 7 8 9
The elements within a row of a matrix may be separated by commas as well as a blank.
MATLAB allows complex numbers in all its operations and functions.
Two convenient ways to enter complex matrices are:
>> A = [1 2;3 4] + i*[5 6;7 8] A = 1.0000 + 5.0000i 2.0000 + 6.0000i 3.0000 + 7.0000i 4.0000 + 8.0000i >> A = [1+5i 2+6i;3+7i 4+8i] A = 1.0000 + 5.0000i 2.0000 + 6.0000i 3.0000 + 7.0000i 4.0000 + 8.0000i
Either i or j may be used as the imaginary unit. If, however, you use i and j as variables and overwrite their values, you may generate a new imaginary unit with, say,
Listing entries of a large matrix is best done in an ASCII file with your local editor, where errors can be easily corrected.
The file should consist of a rectangular array of just the numeric matrix entries.
If this file is named, say, data.ext (where .ext is any extension), the MATLAB command
For example, the file data.ext is
0.2057 0.1123 0.4876 0.0924 0.3164 0.9879 0.3508 0.1249 0.4633 0.8092 0.9211 0.3174 0.6050 0.2238 0.8131 0.3883 0.7844 0.7690 0.0078 0.2176 0.1704 0.6855 0.0244 0.2122 0.7486 0.7947 0.8145 0.3872 0.3736 0.3833 0.5518 0.2916 0.3960 0.4231 0.2510 0.2578 0.2941 0.2902 0.0985 0.1202 0.5774 0.7891 0.1422 0.0875 0.6173 0.2290 0.6035 0.2729 0.6556 0.8929 0.3968 0.5306 0.3175 0.8236 0.5250 0.4400 0.8523 0.0251 0.6401 0.5755 0.6419 0.9644 0.0372 0.7229 0.7032 0.0740 0.8324 0.6537 0.1750 0.3258 0.2576 0.5056 0.4211 0.1806 0.5301 0.4845 0.4325 0.6733 0.5312 0.5557 0.6841 0.5975 0.9569 0.1636 0.5464 0.7519 0.6357 0.1841 0.0451 0.2751 0.1518 0.6948 0.4296 0.1088 0.1844 0.4024 0.3353 0.9357 0.6660 0.3989 0.2287 0.9509 0.7258 0.7232 0.2486 0.7819 0.7581 0.4517 0.6318 0.2120 0.9828 0.2992 0.4579 0.8944 0.4151 0.0642 0.4440 0.3704 0.3474 0.4516 0.1006 0.4326 0.6099 0.1265 0.0773 0.4022 0.4526 0.2405 0.5166 0.1807 0.7673 0.0600 0.8416 0.6606 0.2277 0.2941 0.6555 0.0594 0.1343 0.9138 0.6207 0.4226 0.7639 0.7027 0.2554 0.6712 0.8667 0.7342 0.3839 0.8044 0.2374 0.1098 0.3158 0.0986 0.7067 0.1544 0.3596 0.7593 0.1536 0.0205 0.7152 0.6312 0.5710 0.6273 0.9861 0.5309 0.9338 0.7727 0.1420 0.5578 0.3813 0.5583 0.7406 0.9535 0.9237 0.6421 0.3551 0.1769 0.0216 0.0300 0.0915 0.1875 0.6964 0.1683 0.3134 0.1611 0.7425 0.7437 0.5409 0.6537 0.4190 0.9970 0.9574 0.9106 0.5357 0.4053 0.2662 0.1253 0.1962 0.1662 0.7581 0.4243 0.1059 0.6797 0.9326 0.3908 0.2242 0.2653 0.8006 0.0871 0.1048 0.7978 0.1302 0.3175 0.6225 0.8711 0.4294 0.6816 0.0366 0.1635 0.8161 0.6525 0.9246 0.7458 0.8021
The built-in functions
The command
>> rand(5) ans = 0.6624 0.4116 0.5836 0.3545 0.4134 0.2442 0.6026 0.5118 0.9713 0.2177 0.2955 0.7505 0.0826 0.3464 0.1257 0.6802 0.5835 0.7196 0.8865 0.3089 0.5278 0.5518 0.9962 0.4547 0.7261
>> magic(3)% sum is 15 ans = 8 1 6 3 5 7 4 9 2 >> magic(5)% sum is 65 ans = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
For matrix generated by magic(n), the sum is $\frac{n(n^2+1)}{2}$.
>> hilb(5) ans = 1.0000 0.5000 0.3333 0.2500 0.2000 0.5000 0.3333 0.2500 0.2000 0.1667 0.3333 0.2500 0.2000 0.1667 0.1429 0.2500 0.2000 0.1667 0.1429 0.1250 0.2000 0.1667 0.1429 0.1250 0.1111
Matrices can also be generated with a for-loop. For example, the following codes also generate the Hilbert matrix.
>> m=5;n=5; >> for i = 1:m for j = 1:n H(i, j) = 1/(i+j-1); end end H H = 1.0000 0.5000 0.3333 0.2500 0.2000 0.5000 0.3333 0.2500 0.2000 0.1667 0.3333 0.2500 0.2000 0.1667 0.1429 0.2500 0.2000 0.1667 0.1429 0.1250 0.2000 0.1667 0.1429 0.1250 0.1111
Individual matrix and vector entries can be referenced with indices inside parentheses in the usual manner.
For example,
H = 1.0000 0.5000 0.3333 0.2500 0.2000 0.5000 0.3333 0.2500 0.2000 0.1667 0.3333 0.2500 0.2000 0.1667 0.1429 0.2500 0.2000 0.1667 0.1429 0.1250 0.2000 0.1667 0.1429 0.1250 0.1111 >> H(2,3) ans = 0.2500
The following matrix operations are available in MATLAB:
Operation | Name |
---|---|
addition | |
subtraction | |
multiplication | |
power | |
conjugate transpose | |
left division | |
right division |
These matrix operations apply, of course, to scalars (1-by-1 matrices) as well.
If the sizes of the matrices are incompatible for the matrix operation, an error message will result, except in the case of scalar-matrix operations (for addition, subtraction, and division as well as for multiplication) in which case each entry of the matrix is operated on by the scalar.
>> A=[1 2 3; 2 3 4; 3 4 5] A = 1 2 3 2 3 4 3 4 5 >> B=[1 2; 3 4] B = 1 2 3 4 >> A*B ??? Error using ==> mtimes Inner matrix dimensions must agree.
The “matrix division” operations deserve special comment.
If A is an invertible square matrix and b is a compatible column, resp. row, vector, then
That is $x = A\backslash b = A^{-1}b$ , $x = b/A = bA^{-1}$.
In left division, if A is square, then it is factored using Gaussian elimination and these factors are used to solve
If A is not square, it is factored using Householder orthogonalization with column pivoting and the factors are used to solve the under- or over- determined system in the least squares sense.
Right division is defined in terms of left division by
The matrix operations of addition and subtraction already operate entry-wise but the other matrix operations given above do not — they are matrix operations.
It is important to observe that these other operations,
For example, either
>> [1,2,3,4].*[1,2,3,4] ans = 1 4 9 16 >> [1,2,3,4].^2 ans = 1 4 9 16
MATLAB is an expression language; the expressions you type are interpreted and evaluated. MATLAB statements are usually of the form
Expressions are usually composed from operators, functions, and variable names. Evaluation of the expression produces a matrix, which is then displayed on the screen and assigned to the variable for future use.
If the variable name and
MATLAB is case-sensitive in the names of commands, functions, and variables. For
example,
The command
A variable can be cleared from the workspace with the command
The permanent variable eps (epsilon) gives the machine unit roundoff—about $10^{-16}$ on most machines. It is useful in specifying tolerences for convergence of iterative processes.
A runaway display or computation can be stopped on most machines without leaving
MATLAB with
When one logs out or exits MATLAB all variables are lost.
However, invoking the command
Convenient matrix building functions are
Function | Discription |
---|---|
identity matrix | |
matrix of zeros | |
matrix of ones | |
create or extract diagonals | |
upper triangular part of a matrix | |
lower triangular part of a matrix | |
randomly generated matrix | |
Hilbert matrix | |
magic square | |
see |
>> help triu triu Extract upper triangular part. triu(X) is the upper triangular part of X. triu(X,K) is the elements on and above the K-th diagonal of X. K = 0 is the main diagonal, K > 0 is above the main diagonal and K < 0 is below the main diagonal.
>> X=magic(8) X = 64 2 3 61 60 6 7 57 9 55 54 12 13 51 50 16 17 47 46 20 21 43 42 24 40 26 27 37 36 30 31 33 32 34 35 29 28 38 39 25 41 23 22 44 45 19 18 48 49 15 14 52 53 11 10 56 8 58 59 5 4 62 63 1 >> Y=triu(X) Y = 64 2 3 61 60 6 7 57 0 55 54 12 13 51 50 16 0 0 46 20 21 43 42 24 0 0 0 37 36 30 31 33 0 0 0 0 28 38 39 25 0 0 0 0 0 19 18 48 0 0 0 0 0 0 10 56 0 0 0 0 0 0 0 1 >> Z=triu(X,3) Z = 0 0 0 61 60 6 7 57 0 0 0 0 13 51 50 16 0 0 0 0 0 43 42 24 0 0 0 0 0 0 31 33 0 0 0 0 0 0 0 25 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 >> W=triu(X,-3) W = 64 2 3 61 60 6 7 57 9 55 54 12 13 51 50 16 17 47 46 20 21 43 42 24 40 26 27 37 36 30 31 33 0 34 35 29 28 38 39 25 0 0 22 44 45 19 18 48 0 0 0 52 53 11 10 56 0 0 0 0 4 62 63 1
>> n=3; >> eye(n)% returns the n-by-n identity matrix. ans = 1 0 0 0 1 0 0 0 1 >> eye(3,5) ans = 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 >> eye(5,3) ans = 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0 >> eye([5,3]) ans = 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0 >> eye([5 3]) ans = 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0
>> m=5;n=3; >> zeros(m,n)% produces an m-by-n matrix of zeros ans = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 >> zeros(n)% produces an n-by-n one. ans = 0 0 0 0 0 0 0 0 0 >> A=[1 2 3;2 3 4] A = 1 2 3 2 3 4 >> zeros(size(A))% produces a matrix of zeros having the same size as A ans = 0 0 0 0 0 0
>> x=[1 2 3 4 5] x = 1 2 3 4 5 >> diag(x) ans = 1 0 0 0 0 0 2 0 0 0 0 0 3 0 0 0 0 0 4 0 0 0 0 0 5 >> A=rand(5,5) A = 0.8147 0.0975 0.1576 0.1419 0.6557 0.9058 0.2785 0.9706 0.4218 0.0357 0.1270 0.5469 0.9572 0.9157 0.8491 0.9134 0.9575 0.4854 0.7922 0.9340 0.6324 0.9649 0.8003 0.9595 0.6787 >> diag(A) ans = 0.8147 0.2785 0.9572 0.7922 0.6787 >> diag(diag(A)) ans = 0.8147 0 0 0 0 0 0.2785 0 0 0 0 0 0.9572 0 0 0 0 0 0.7922 0 0 0 0 0 0.6787
>> A=rand(3) A = 0.7577 0.6555 0.0318 0.7431 0.1712 0.2769 0.3922 0.7060 0.0462 >> B = [A, zeros(3,2); zeros(2,3), eye(2)] B = 0.7577 0.6555 0.0318 0 0 0.7431 0.1712 0.2769 0 0 0.3922 0.7060 0.0462 0 0 0 0 0 1.0000 0 0 0 0 0 1.0000
>> n=10; x=[]; >> for i=1:n x=[x,i^2]% add element i^2 to the vector x end x = 1 x = 1 4 x = 1 4 9 x = 1 4 9 16 x = 1 4 9 16 25 x = 1 4 9 16 25 36 x = 1 4 9 16 25 36 49 x = 1 4 9 16 25 36 49 64 x = 1 4 9 16 25 36 49 64 81 x = 1 4 9 16 25 36 49 64 81 100 >> x x = 1 4 9 16 25 36 49 64 81 100
>> n=10; >> x = []; for i = n:-1:1, x=[x,i^2], end x = 100 x = 100 81 x = 100 81 64 x = 100 81 64 49 x = 100 81 64 49 36 x = 100 81 64 49 36 25 x = 100 81 64 49 36 25 16 x = 100 81 64 49 36 25 16 9 x = 100 81 64 49 36 25 16 9 4 x = 100 81 64 49 36 25 16 9 4 1
The variable just consecutively assumes the value of each column of the matrix. For example,
>> A=[1 2; 3 4] A = 1 2 3 4 >> s=0;k=0; >> for c=A %c s=s+sum(c); k=k+1; end >> s s = 10 >> k k = 2
NOTE: here c is the collum vector of matrix A.
This computes the sum of all entries of the matrix A by adding its column sums.
Of course,
>> A=[1 2 3;4 5 6;7 8 9] A = 1 2 3 4 5 6 7 8 9 >> sum(A) ans = 12 15 18 >> sum(sum(A)) ans = 45
The general form of a while loop is
while relation statements end
The statements will be repeatedly executed as long as the relation remains true.
For example, for a given number $a$, the following will compute and display the smallest nonnegative integer $n$ such that $2n ≥ a$:
>> n=0;a=100000; >> while 2^n < a n=n+1; end >> n n = 17 >> 2^16 ans = 65536 >> 2^17 ans = 131072
The general form of a simple
if relation statements end
The statements will be executed only if the relation is true. Multiple branching is also possible, as is illustrated by
>> n=7; >> if n < 0 parity=0; elseif rem(n,2)==0% rem( , ) : Remainder after division parity=2; else parity=1; end >> parity parity = 1 >> rem(n,2) ans = 1 >> rem(4,2) ans = 0
The relational operators in MATLAB are
Operator | Discription |
---|---|
less than | |
greater than | |
less than or equal | |
greater than or equal | |
equal | |
not equal |
Note that “
Logical operator | Discription |
---|---|
and | |
or | |
not |
When applied to scalars, a relation is actually the scalar 1 or 0 depending on whether the relation is true or false.
>> 3<5, 3>5, 3==5, 3==3
ans =
1
ans =
0
ans =
0
ans =
1
When applied to matrices of the same size, a relation is a matrix of 0’s and 1’s giving the value of the relation between corresponding entries.
>> a=rand(5), b=triu(a), a==b
a =
0.9649 0.8003 0.9595 0.6787 0.1712
0.1576 0.1419 0.6557 0.7577 0.7060
0.9706 0.4218 0.0357 0.7431 0.0318
0.9572 0.9157 0.8491 0.3922 0.2769
0.4854 0.7922 0.9340 0.6555 0.0462
b =
0.9649 0.8003 0.9595 0.6787 0.1712
0 0.1419 0.6557 0.7577 0.7060
0 0 0.0357 0.7431 0.0318
0 0 0 0.3922 0.2769
0 0 0 0 0.0462
ans =
1 1 1 1 1
0 1 1 1 1
0 0 1 1 1
0 0 0 1 1
0 0 0 0 1
A relation between matrices is interpreted by
>> c=(a==b) c = 1 1 1 1 1 0 1 1 1 1 0 0 1 1 1 0 0 0 1 1 0 0 0 0 1 >> if c x=1; else x=0; end >> x x = 0
Hence, if you wish to execute statement when matrices A and B are equal you could type
if A == B statement end
but if you wish to execute statement when A and B are not equal, you would type
if any(any(A ∼= B)) statement end
or, more simply,
if A == B else statement end
Note that the seemingly obvious
if A ∼= B, statement, end
will not give what is intended since statement would execute only if each of the corresponding entries of A and B differ.
The functions
Certain MATLAB functions operate essentially on scalars, but operate element-wise when applied to a matrix. The most common such functions are
sin | asin | exp | abs | round |
cos | acos | log (natural log) | sqrt | floor |
tan | atan | rem (remainder) | sign | ceil |
>> a=1;v=[1 2];A=[1 2; 0 1]; >> sin(a) ans = 0.8415 >> sin(v) ans = 0.8415 0.9093 >> sin(A) ans = 0.8415 0.9093 0 0.8415
Other MATLAB functions operate essentially on a vector (row or column), but act on an m-by-n matrix (m ≥ 2) in a column-by-column fashion to produce a row vector containing the results of their application to each column.
Row-by-row action can be obtained by using the transpose; for example,
max | sum | median | any |
min | prod | mean | all |
sort | std |
For example, the maximum entry in a matrix A is given by
>> A=rand(3) A = 0.0971 0.3171 0.4387 0.8235 0.9502 0.3816 0.6948 0.0344 0.7655 >> max(A) ans = 0.8235 0.9502 0.7655 >> max(max(A)) ans = 0.9502
Much of MATLAB’s power comes from its matrix functions. The most useful ones are
eig | eigenvalues and eigenvectors |
chol | cholesky factorization |
svd | singular value decomposition |
inv | inverse |
lu | LU factorization |
qr | QR factorization |
hess | hessenberg form |
schur | schur decomposition |
rref | reduced row echelon form |
expm | matrix exponential |
sqrtm | matrix square root |
poly | characteristic polynomial |
det | determinant |
size | size |
norm | 1-norm, 2-norm, F-norm, ∞-norm |
cond | condition number in the 2-norm |
rank | rank |
Let us consider a singular matrix \[ A=\begin{pmatrix} 1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9 \end{pmatrix} \]
\[ |\lambda E-A|=\lambda(\lambda^2-15\lambda-18), \]
so, the eigenvalues are \[ \lambda_1=0,\quad\lambda_2=\frac{15+\sqrt{297}}{2},\quad\lambda_3=\frac{15-\sqrt{297}}{2}. \]
Let's check it.
>> A=[1 2 3;4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 >> det(A)% should be zero ans = 6.661338147750939e-16 >> rank(A) ans = 2 >> eig(A) ans = 16.1168 -1.1168 -0.0000 >> (sqrt(297)+15)/2 ans = 16.1168 >> (-sqrt(297)+15)/2 ans = -1.1168 >> poly(A) ans = 1.0000 -15.0000 -18.0000 -0.0000 >> [U, D]=eig(A) U = -0.2320 -0.7858 0.4082 -0.5253 -0.0868 -0.8165 -0.8187 0.6123 0.4082 D = 16.1168 0 0 0 -1.1168 0 0 0 -0.0000
If A is positive definite, then
A = 1 0 0 0 1 0 1 0 1 >> B=A' B = 1 0 1 0 1 0 0 0 1 >> C=A*B C = 1 0 1 0 1 0 1 0 2 >> chol(C) ans = 1 0 1 0 1 0 0 0 1
In linear algebra, the singular value decomposition (SVD) is a factorization of a real or complex matrix, with many useful applications in signal processing and statistics.
Suppose $M$ is an $m×n$ matrix whose entries come from the field $K$, which is either the field of real numbers or the field of complex numbers. Then there exists a factorization of the form \[ M=U\Sigma V^*, \]
where $U$ is an $m×m$ unitary matrix over $K$, the matrix $\Sigma$ is an $m×n$ diagonal matrix with nonnegative real numbers on the diagonal, and $V^*$, an $n×n$ unitary matrix over $K$, denotes the conjugate transpose of $V$. Such a factorization is called the singular value decomposition of $M$.
The diagonal entries $σ_i$ of $Σ$ are known as the singular values of $M$. A common convention is to list the singular values in descending order. In this case, the diagonal matrix $Σ$ is uniquely determined by $M$ (though the matrices $U$ and $V$ are not).
>> A A = 1 2 3 4 5 6 7 8 9 >> svd(A) ans = 16.8481 1.0684 0.0000 >> norm(A)% n = norm(A) returns the largest singular value of A, max(svd(A)). ans = 16.8481
Vectors and submatrices are often used in MATLAB to achieve fairly complex data manipulation effects.
“Colon notation” (which is used both to generate vectors and reference submatrices) and subscripting by integral vectors are keys to efficient manipulation of these objects.
Creative use of these features to vectorize operations permits one to minimize the use of loops (which slows MATLAB) and to make code simple and readable. Special effort should be made to become familiar with them.
The expression
The numbers need not be integers nor the increment one. For example,
>> 1:5 ans = 1 2 3 4 5 >> 0.2:0.2:1.2 ans = 0.2000 0.4000 0.6000 0.8000 1.0000 1.2000 >> 5:-1:1 ans = 5 4 3 2 1
The following statements will, for example, generate a table of sines.
>> x = [0.0:0.1:2.0]' x = 0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000 1.1000 1.2000 1.3000 1.4000 1.5000 1.6000 1.7000 1.8000 1.9000 2.0000 >> y = sin(x)% Note that since sin operates entry-wise, it produces a vector y from the vector x. y = 0 0.0998 0.1987 0.2955 0.3894 0.4794 0.5646 0.6442 0.7174 0.7833 0.8415 0.8912 0.9320 0.9636 0.9854 0.9975 0.9996 0.9917 0.9738 0.9463 0.9093 >> [x y] ans = 0 0 0.1000 0.0998 0.2000 0.1987 0.3000 0.2955 0.4000 0.3894 0.5000 0.4794 0.6000 0.5646 0.7000 0.6442 0.8000 0.7174 0.9000 0.7833 1.0000 0.8415 1.1000 0.8912 1.2000 0.9320 1.3000 0.9636 1.4000 0.9854 1.5000 0.9975 1.6000 0.9996 1.7000 0.9917 1.8000 0.9738 1.9000 0.9463 2.0000 0.9093
>> A=rand(5) A = 0.5678 0.9340 0.3371 0.1656 0.7482 0.0759 0.1299 0.1622 0.6020 0.4505 0.0540 0.5688 0.7943 0.2630 0.0838 0.5308 0.4694 0.3112 0.6541 0.2290 0.7792 0.0119 0.5285 0.6892 0.9133 >> A(1:4,3) % is the column vector consisting of the first four entries of the third column of A. ans = 0.3371 0.1622 0.7943 0.3112 >> A(:,3) % is the third column of A ans = 0.3371 0.1622 0.7943 0.3112 0.5285 >> A(1:4,:) % is the first four rows ans = 0.5678 0.9340 0.3371 0.1656 0.7482 0.0759 0.1299 0.1622 0.6020 0.4505 0.0540 0.5688 0.7943 0.2630 0.0838 0.5308 0.4694 0.3112 0.6541 0.2290 >> A(:,[2 4]) % contains as columns, columns 2 and 4 of A ans = 0.9340 0.1656 0.1299 0.6020 0.5688 0.2630 0.4694 0.6541 0.0119 0.6892 >> B=eye(5) B = 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 >> A(:,[2 4 5])=B(:,1:3)% replaces columns 2,4,5 of A with the first three columns of B. A = 0.5678 1.0000 0.3371 0 0 0.0759 0 0.1622 1.0000 0 0.0540 0 0.7943 0 1.0000 0.5308 0 0.3112 0 0 0.7792 0 0.5285 0 0 >> A(:,[2,4])=A(:,[2,4])*[1 2; 3 4]% Columns 2 and 4 of A can be multiplied on the right by the 2-by-2 matrix A = 0.5678 1.0000 0.3371 2.0000 0 0.0759 3.0000 0.1622 4.0000 0 0.0540 0 0.7943 0 1.0000 0.5308 0 0.3112 0 0 0.7792 0 0.5285 0 0
If
>> A=[1 2 3; 4 5 6]' A = 1 4 2 5 3 6 >> B=fliplr(A) B = 4 1 5 2 6 3 >> A=[1:5] A = 1 2 3 4 5 >> B=fliplr(A) B = 5 4 3 2 1 >> B=B(5:-1:1) B = 1 2 3 4 5
If
>> A=[1 2 3; 4 5 6]' A = 1 4 2 5 3 6 >> B=flipud(A) B = 3 6 2 5 1 4 >> A=[1:5]' A = 1 2 3 4 5 >> B=flipud(A) B = 5 4 3 2 1 >> B=B(5:-1:1) B = 1 2 3 4 5
MATLAB can execute a sequence of statements stored in diskfiles.
Such files are called “M-files” because they must have the file type of “.m” as the last part of their filename.
Much of your work with MATLAB will be in creating and refining M-files. M-files are usually created using your local editor.
There are two types of M-files: script files and function files.
A script file consists of a sequence of normal MATLAB statements.
If the file has the filename, say, rotate.m, then the MATLAB command rotate will cause the statements in the file to be executed.
Variables in a script file are global and will change the value of variables of the same name in the environment of the current MATLAB session.
Script files may be used to enter data into a large matrix; in such a file, entry errors can be easily corrected. If, for example, one enters in a diskfile data.m
A = [ 1 2 3 4 5 6 7 8 ];
then the MATLAB statement data will cause the assignment given in data.m to be carried out. However, it is usually easier to use the MATLAB function
An M-file can reference other M-files, including referencing itself recursively.
You can create new functions specific to your problem which will then have the same status as other MATLAB functions.
Variables in a function file are by default local. A variable can, however, be declared global (see
We first illustrate with a simple example of a function file.
function a = RandInt(m,n) % RANDINT Randomly generated integral matrix. % RandInt(m,n) returns an m-by-n such matrix with entries % between 0 and 9. a = floor(10*rand(m,n));
A more general version of this function is the following:
function a = RandInteger(m,n,a,b) % RANDINT Randomly generated integral matrix. % RandInt(m,n) returns an m-by-n such matrix with entries between 0 and 9. % RandInteger(m,n,a,b) return entries between integers a and b. if nargin < 3, a = 0; b = 9; end a = floor((b-a+1)*rand(m,n)) + a;
This should be placed in a diskfile with filename RandInteger.m (corresponding to the function name, It seems that function name can be different from the filename).
The first line declares the function name, input arguments, and output arguments; without this line the file would be a script file.
Then a MATLAB statement
Note that use of
function [mean, stdev] = stat(x) % STAT Mean and standard deviation % For a vector x, stat(x) returns the mean of x; % [mean, stdev] = stat(x) both the mean and standard deviation. % For a matrix x, stat(x) acts columnwise. [m n] = size(x); if m == 1 m = n; % handle case of a row vector end mean = sum(x)/m; stdev = sqrt(sum(x. 2)/m - mean. 2);
Once this is placed in a diskfile stat.m, a MATLAB command
Single assignments can also be made with a function having multiple output arguments. For example,
The % symbol indicates that the rest of the line is a comment; MATLAB will ignore the rest of the line.
Moreover, the first few contiguous comment lines, which document
the M-file, are available to the on-line help facility and will be displayed if, for example,
This function illustrates some of the MATLAB features that can be used to produce efficient code.
Note, for example, that
Thus all operations are vectorized and loops avoided. If you can’t vectorize some computations, you can make your
For example, by including the second statement below, which uses the function zeros, space for storing E in memory is preallocated. Without this MATLAB must resize E one column larger in each iteration, slowing execution.
M = magic(6); E = zeros(6,50); for j = 1:50 E(:,j) = eig(M^i);% note that here i=0+1.0000i end
Some more advanced features are illustrated by the following function. As noted earlier, some of the input arguments of a function—such as tol in this example, may be made optional through use of nargin (“number of input arguments”). The variable
Note that the fact that a relation is a number (1 when true; 0 when
false) is used and that, when
Finally, the MATLAB function
function [b, steps] = bisect(fun, x, tol) %BISECT Zero of a function of one variable via the bisection method. % bisect(fun,x) returns a zero of the function. fun is a string % containing the name of a real-valued MATLAB function of a % single real variable; ordinarily functions are defined in % M-files. x is a starting guess. The value returned is near % a point where fun changes sign. For example, % bisect(’sin’,3) is pi. Note the quotes around sin. % % An optional third input argument sets a tolerence for the % relative accuracy of the result. The default is eps. % An optional second output argument gives a matrix containing a % trace of the steps; the rows are of form [c f(c)]. % Initialization if nargin < 3, tol = eps; end Trace = (nargout == 2); if x ~= 0, dx = x/20; else, dx = 1/20; end a = x - dx; fa = feval(fun,a); % Execute the specified function. b = x + dx; fb = feval(fun,b); % Find change of sign. while (fa > 0) == (fb > 0) dx = 2.0*dx; a = x - dx; fa = feval(fun,a); if (fa > 0) ~= (fb > 0), break, end b = x + dx; fb = feval(fun,b); end if Trace, steps = [a fa; b fb]; end % Main loop while abs(b - a) > 2.0*tol*max(abs(b),1.0) c = a + 0.5*(b - a); fc = feval(fun,c); if Trace, steps = [steps; [c fc]]; end if (fb > 0) == (fc > 0) b = c; fb = fc; else a = c; fa = fc; end end
Some of MATLAB’s functions are built-in while others are distributed as M-files.
The actual listing of any non-built-in M-file—MATLAB’s or your own—can be viewed with
the MATLAB command
>> type eig 'eig' is a built-in function. >> type vander function A = vander(v) %VANDER Vandermonde matrix. % A = VANDER(V) returns the Vandermonde matrix whose columns % are powers of the vector V, that is A(i,j) = v(i)^(n-j). % % Class support for input V: % float: double, single % Copyright 1984-2004 The MathWorks, Inc. % $Revision: 5.9.4.1 $ $Date: 2004/07/05 17:01:29 $ n = length(v); v = v(:); A = ones(n,class(v)); for j = n-1:-1:1 A(:,j) = v.*A(:,j+1); end >> type rank function r = rank(A,tol) %RANK Matrix rank. % RANK(A) provides an estimate of the number of linearly % independent rows or columns of a matrix A. % RANK(A,tol) is the number of singular values of A % that are larger than tol. % RANK(A) uses the default tol = max(size(A)) * eps(norm(A)). % % Class support for input A: % float: double, single % Copyright 1984-2007 The MathWorks, Inc. % $Revision: 5.11.4.5 $ $Date: 2007/08/03 21:26:23 $ s = svd(A); if nargin==1 tol = max(size(A)) * eps(max(s)); end r = sum(s > tol);