Variables, Numbers, Operators and Functions
Variables
MATLAB does not require a command to declare variables. A variable is created simply by directly allocating a value to it. For example:
>> v = 3
v =
3
The variable v will take the value 3 and using a new mapping will not change its value. Once the variable is declared, we can use it in calculations.
>> v ^ 3
ans =
27
>> v + 5
ans =
8
The value assigned to a variable remains fixed until it is explicitly changed or if the current MATLAB session is closed.
If we now write:
>> v = 3 + 7
v =
10
then the variable v has the value 10 from now on, as shown in the following calculation:
>> v ^ 4
ans =
10000
A variable name must begin with a letter followed by any number of letters, digits or underscores. However, bear in mind that MATLAB uses only the first 31 characters of the name of the variable. It is also very important to note that MATLAB is case sensitive. Therefore, a variable named with uppercase letters is different to the variable with the same name except in lowercase letters.
Vector Variables
A vector variable of n elements can be defined in MATLAB in the following ways:
V = [v1, v2, v3,..., vn]
V = [v1 v2 v3... vn]
When most MATLAB commands and functions are applied to a vector variable the result is understood to be that obtained by applying the command or function to each element of the vector:
>> vector1 = [1,4,9,2.25,1/4]
vector1 =
1.0000 4.0000 9.0000 2.2500 0.2500
>> sqrt (vector1)
ans =
1.0000 2.0000 3.0000 1.5000 0.5000
The following table presents some alternative ways of defining a vector variable without explicitly bracketing all its elements together, separated by commas or blank spaces.
variable = [a:b] |
Defines the vector whose first and last elements are a and b, respectively, and the intermediate elements differ by one unit. |
variable = [a:s:b] |
Defines the vector whose first and last elements are a and b, respectively, and the intermediate elements differ by an increase specified by s. |
variable = linespace [a, b, n] |
Defines the vector with n evenly spaced elements whose first and last elements are a and b respectively. |
variable = logspace [a, b, n] |
Defines the vector with n evenly logarithmically spaced elements whose first and last elements are 10a and 10b, respectively. |
Below are some examples:
>> vector2 = [5:5:25]
vector2 =
5 10 15 20 25
This yields the numbers between 5 and 25, inclusive, separated by 5 units.
>> vector3=[10:30]
vector3 =
Columns 1 through 13
10 11 12 13 14 15 16 17 18 19 20 21 22
Columns 14 through 21
23 24 25 26 27 28 29 30
This yields the numbers between 10 and 30, inclusive, separated by a unit.
>> t:Microsoft.WindowsMobile.DirectX.Vector4 = linspace (10,30,6)
t:Microsoft.WindowsMobile.DirectX.Vector4 =
10 14 18 22 26 30
This yields 6 equally spaced numbers between 10 and 30, inclusive.
>> vector5 = logspace (10,30,6)
vector5 =
1. 0e + 030 *
0.0000 0.0000 0.0000 0.0000 0.0001 1.0000
This yields 6 evenly logarithmically spaced numbers between 1010 and 1030, inclusive.
One can also consider row vectors and column vectors in MATLAB. A column vector is obtained by separating its elements by semicolons, or by transposing a row vector using a single quotation mark at the end of its definition.
>> a = [10;20;30;40]
a =
10
20
30
40
>> a = (10:14);b = a'
b =
10
11
12
13
14
>> c = (a')'
c =
10 11 12 13 14
You can also select an element of a vector or a subset of elements. The rules are summarized in the following table:
x (n) |
Returns the n-th element of the vector x. |
x(a:b) |
Returns the elements of the vector x between the a-th and the b-th elements, inclusive. |
x(a:p:b) |
Returns the elements of the vector x located between the a-th and the b-th elements, inclusive, but separated by p units (a > b). |
x(b:-p:a) |
Returns the elements of the vector x located between the b-th and a-th elements, both inclusive, but separated by p units and starting with the b-th element (b > a). |
Here are some examples:
>> x = (1:10)
x =
1 2 3 4 5 6 7 8 9 10
>> x (6)
ans =
6
This yields the sixth element of the vector x.
>> x (4:7)
ans =
4 5 6 7
This yields the elements of the vector x located between the fourth and seventh elements, inclusive.
>> x(2:3:9)
ans =
2 5 8
This yields the three elements of the vector x located between the second and ninth elements, inclusive, but separated in steps of three units.
>> x(9:-3:2)
ans =
9 6 3
This yields the three elements of the vector x located between the ninth and second elements, inclusive, but separated in steps of three units and starting at the ninth.
Matrix Variables
MATLAB defines arrays by inserting in brackets all its row vectors separated by a semicolon. Vectors can be entered by separating their components by spaces or by commas, as we already know. For example, a 3 × 3 matrix variable can be entered in the following two ways:
M = [a11a12 a13;a21a22a23;a31a32a33]
M = [a11,a12,a13;a21,a22,a23;a31,a32,a33]
Similarly we can define an array of variable dimension (M×N). Once a matrix variable has been defined, MATLAB enables many ways to insert, extract, renumber, and generally manipulate its elements. The following table shows different ways to define matrix variables.
A(m,n) |
Defines the (m, n)-th element of the matrix A (row m and column n). |
A(a:b,c:d) |
Defines the subarray of A formed between the a-th and the b-th rows and between the c-th and the d-th columns, inclusive. |
A(a:p:b,c:q:d) |
Defines the subarray of A formed by every p-th row between the a-th and the b-th rows, inclusive, and every q-th column between the c-th and the d-th column, inclusive. |
A([a b],[c d]) |
Defines the subarray of A formed by the intersection of the a-th through b-th rows and c-th through d-th columns, inclusive. |
A([a b c...],[e f g...]) |
Defines the subarray of A formed by the intersection of rows a, b, c,...and columns e, f, g,... |
A(:,c:d) |
Defines the subarray of A formed by all the rows in A and the c-th through to the d-th columns. |
A(:,[c d e...]) |
Defines the subarray of A formed by all the rows in A and columns c, d, e,... |
A(a:b,:) |
Defines the subarray of A formed by all the columns in A and the a-th through to the b-th rows. |
A([a b c...],:) |
Defines the subarray of A formed by all the columns in A and rows a, b, c,... |
A(a,:) |
Defines the a-th row of the matrix A. |
A(:,b) |
Defines the b-th column of the matrix A. |
A(:) |
Defines a column vector whose elements are the columns of A placed in order below each other. |
A(:,:) |
This is equivalent to the entire matrix A. |
[A, B, C,...] |
Defines the matrix formed by the matrices A, B, C,... |
SA = [ ] |
Clears the subarray of the matrix A, SA, and returns the remainder. |
diag (v) |
Creates a diagonal matrix with the vector v in the diagonal. |
diag (A) |
Extracts the diagonal of the matrix as a column vector. |
eye (n) |
Creates the identity matrix of order n. |
eye (m, n) |
Creates an m×n matrix with ones on the main diagonal and zeros elsewhere. |
zeros (m, n) |
Creates the zero matrix of order m×n. |
ones (m, n) |
Creates the matrix of order m×n with all its elements equal to 1. |
rand (m, n) |
Creates a uniform random matrix of order m×n. |
randn (m, n) |
Creates a normal random matrix of order m×n. |
flipud (A) |
Returns the matrix whose rows are those of A but placed in reverse order (from top to bottom). |
fliplr (A) |
Returns the matrix whose columns are those of A but placed in reverse order (from left to right). |
rot90 (A) |
Rotates the matrix A counterclockwise by 90 degrees. |
reshape(A,m,n) |
Returns an m×n matrix formed by taking consecutive entries of A by columns. |
size (A) |
Returns the order (size) of the matrix A. |
find (condA) |
Returns all A items that meet a given condition. |
length (v) |
Returns the length of the vector v. |
tril (A) |
Returns the lower triangular part of the matrix A. |
triu (A) |
Returns the upper triangular part of the matrix A. |
A’ |
Returns the transpose of the matrix A. |
Inv (A) |
Returns the inverse of the matrix A. |
Here are some examples:
We consider first the 2 × 3 matrix whose rows are the first six consecutive odd numbers:
>> A = [1 3 5; 7 9 11]
A =
1 3 5
7 9 11
Now we are going to change the (2,3)-th element, i.e. the last element of A, to zero:
>> A(2,3) = 0
A =
1 3 5
7 9 0
We now define the matrix B to be the transpose of A:
>> B = A'
B =
1 7
3 9
5 0
We now construct a matrix C, formed by attaching the identity matrix of order 3 to the right of the matrix B:
>> C = [B eye (3)]
C =
1 7 1 0 0
3 9 0 1 0
5 0 0 0 1
We are going to build a matrix D by extracting the odd columns of the matrix C, a matrix E formed by taking the intersection of the first two rows of C and its third and fifth columns, and a matrix F formed by taking the intersection of the first two rows and the last three columns of the matrix C:
>> D = C(:,1:2:5)
D =
1 1 0
3 0 0
5 0 1
>> E = C([1 2],[3 5])
E =
1 0
0 0
>> F = C([1 2],3:5)
F =
1 0 0
0 1 0
Now we build the diagonal matrix G such that the elements of the main diagonal are the same as those of the main diagonal of D:
>> G = diag(diag(D))
G =
1 0 0
0 0 0
0 0 1
We then build the matrix H, formed by taking the intersection of the first and third rows of C and its second, third and fifth columns:
>> H = C([1 3],[2 3 5])
H =
7 1 0
0 0 1
Now we build an array I formed by the identity matrix of order 5 × 4, appending the zero matrix of the same order to its right and to the right of that the unit matrix, again of the same order. Then we extract the first row of I and, finally, form the matrix J comprising the odd rows and even columns of I and calculate its order (size).
>> I = [eye(5,4) zeros(5,4) ones(5,4)]
ans =
1 0 0 0 0 0 0 0 1 1 1 1
0 1 0 0 0 0 0 0 1 1 1 1
0 0 1 0 0 0 0 0 1 1 1 1
0 0 0 1 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 0 1 1 1 1
>> I(1,:)
ans =
1 0 0 0 0 0 0 0 1 1 1 1
>> J = I(1:2:5,2:2:12)
J =
0 0 0 0 1 1
0 0 0 0 1 1
0 0 0 0 1 1
>> size(J)
ans =
3 6
We now construct a random matrix K of order 3 ×4, reverse the order of the rows of K, reverse the order of the columns of K and then perform both operations simultaneously. Finally, we find the matrix L of order 4 × 3 whose columns are obtained by taking the elements of K sequentially by columns.
>> K = rand(3,4)
K =
0.5269 0.4160 0.7622 0.7361
0.0920 0.7012 0.2625 0.3282
0.6539 0.9103 0.0475 0.6326
>> K(3:-1:1,:)
ans =
0.6539 0.9103 0.0475 0.6326
0.0920 0.7012 0.2625 0.3282
0.5269 0.4160 0.7622 0.7361
>> K(:,4:-1:1)
ans =
0.7361 0.7622 0.4160 0.5269
0.3282 0.2625 0.7012 0.0920
0.6326 0.0475 0.9103 0.6539
>> K(3:-1:1,4:-1:1)
ans =
0.6326 0.0475 0.9103 0.6539
0.3282 0.2625 0.7012 0.0920
0.7361 0.7622 0.4160 0.5269
>> L = reshape(K,4,3)
L =
0.5269 0.7012 0.0475
0.0920 0.9103 0.7361
0.6539 0.7622 0.3282
0.4160 0.2625 0.6326
Character Variables
A character variable (chain) is simply a character string enclosed in single quotes that MATLAB treats as a vector form. The general syntax for character variables is as follows:
c = 'string'
Among the MATLAB commands that handle character variables we have the following:
abs (‘character_string’) |
Returns the array of ASCII characters equivalent to each character in the string. |
setstr (numeric_vector) |
Returns the string of ASCII characters that are equivalent to the elements of the vector. |
str2mat (t1,t2,t3,...) |
Returns the matrix whose rows are the strings t1, t2, t3,..., respectively |
str2num (‘string’) |
Converts the string to its exact numeric value used by MATLAB. |
num2str (number) |
Returns the exact number in its equivalent string with fixed precision. |
int2str (integer) |
Converts the integer to a string. |
sprintf (‘format’, a) |
Converts a numeric array into a string in the specified format. |
sscanf (‘string’, ‘format’) |
Converts a string to a numeric value in the specified format. |
dec2hex (integer) |
Converts a decimal integer into its equivalent string in hexadecimal. |
hex2dec (‘string_hex’) |
Converts a hexadecimal string into its integer equivalent. |
hex2num (‘string_hex’) |
Converts a hexadecimal string into the equivalent IEEE floating point number. |
lower (‘string’) |
Converts a string to lowercase. |
upper (‘string’) |
Converts a string to uppercase. |
strcmp (s1, s2) |
Compares the strings s1 and s2 and returns 1 if they are equal and 0 otherwise. |
strcmp (s1, s2, n) |
Compares the strings s1 and s2 and returns 1 if their first n characters are equal and 0 otherwise. |
strrep (c, ‘exp1’, ‘exp2’) |
Replaces exp1 by exp2 in the chain c. |
findstr (c, ‘exp’) |
Finds where exp is in the chain c. |
isstr (expression) |
Returns 1 if the expression is a string and 0 otherwise. |
ischar (expression) |
Returns 1 if the expression is a string and 0 otherwise. |
strjust (string) |
Right justifies the string. |
blanks (n) |
Generates a string of n spaces. |
deblank (string) |
Removes blank spaces from the right of the string. |
eval (expression) |
Executes the expression, even if it is a string. |
disp (‘string’) |
Displays the string (or array) as has been written, and continues the MATLAB process. |
input (‘string’) |
Displays the string on the screen and waits for a key press to continue. |
Here are some examples:
>> hex2dec ('3ffe56e')
ans =
67102062
Here MATLAB has converted a hexadecimal string into a decimal number.
>> dec2hex (1345679001)
ans =
50356E99
The program has converted a decimal number into a hexadecimal string.
>> sprintf('%f',[1+sqrt(5)/2,pi])
ans =
2.118034 3.141593
The exact numerical components of a vector have been converted to strings (with default precision).
>> sscanf('121.00012', '%f')
ans =
121.0001
Here a numeric string has been passed to an exact numerical format (with default precision).
>> num2str (pi)
ans =
3.142
The constant π has been converted into a string.
>> str2num('15/14')
ans =
1.0714
The string has been converted into a numeric value with default precision.
>> setstr(32:126)
ans =
!"#$% &' () * +, -. / 0123456789:; < = >? @ABCDEFGHIJKLMNOPQRSTUVWXYZ [] ^ _'abcdefghijklmnopqrstuvwxyz {|}~
This yields the ASCII characters associated with the whole numbers between 32 and 126, inclusive.
>> abs('{]}><#¡¿?oa')
ans =
123 93 125 62 60 35 161 191 63 186 170
This yields the integers corresponding to the ASCII characters specified in the argument of abs.
>> lower ('ABCDefgHIJ')
ans =
abcdefghij
The text has been converted to lowercase.
>> upper('abcd eFGHi jKlMn')
ans =
ABCD EFGHI JKLMN
The text has been converted to uppercase.
>> str2mat ('The world',' The country',' Daily 16', ' ABC')
ans =
The world
The country
Daily 16
ABC
The chains comprising the arguments of str2mat have been converted to a text array.
>> disp('This text will appear on the screen')
ans =
This text will appear on the screen
Here the argument of the command disp has been displayed on the screen.
>> c = 'This is a good example';
>> strrep(c, 'good', 'bad')
ans =
This is a bad example
The string good has been replaced by bad in the chain c. The following instruction locates the initial position of each occurrence of is within the chain c.
>> findstr (c, 'is')
ans =
3 6
Numbers
In MATLAB the arguments of a function can take many different forms, including different types of numbers and numerical expressions, such as integers and rational, real and complex numbers.
Arithmetic operations in MATLAB are defined according to the standard mathematical conventions. MATLAB is an interactive program that allows you to perform a simple variety of mathematical operations. MATLAB assumes the usual operations of sum, difference, product, division and power, with the usual hierarchy between them:
x + y |
Sum |
x y |
Difference |
x * y or x y |
Product |
x/y |
Division |
x ^ y |
Power |
To add two numbers simply enter the first number, a plus sign (+) and the second number. Spaces may be included before and after the sign to ensure that the input is easier to read.
>> 2 + 3
ans =
5
We can perform power calculations directly.
>> 100 ^ 50
ans =
1. 0000e + 100
Unlike a calculator, when working with integers, MATLAB displays the full result even when there are more digits than would normally fit across the screen. For example, MATLAB returns the following value of 99 ^ 50 when using the vpa function (here to the default accuracy of 32 significant figures).
>> vpa '99 ^ 50'
ans =
. 60500606713753665044791996801256e100
To combine several operations in the same instruction one must take into account the usual priority criteria among them, which determine the order of evaluation of the expression. Consider, for example:
>> 2 * 3 ^ 2 + (5-2) * 3
ans =
27
Taking into account the priority of operators, the first expression to be evaluated is the power 3^2. The usual evaluation order can be altered by grouping expressions together in parentheses.
In addition to these arithmetic operators, MATLAB is equipped with a set of basic functions and you can also define your own functions. MATLAB functions and operators can be applied to symbolic constants or numbers.
One of the basic applications of MATLAB is its use in realizing arithmetic operations as if it were a conventional calculator, but with one important difference: the precision of the calculation. Operations are performed to whatever degree of precision the user desires. This unlimited precision in calculation is a feature which sets MATLAB apart from other numerical calculation programs, where the accuracy is determined by a word length inherent to the software, and cannot be modified.
The accuracy of the output of MATLAB operations can be relaxed using special approximation techniques which are exact only up to a certain specified degree of precision. MATLAB represents results with accuracy, but even if internally you are always working with exact calculations to prevent propagation of rounding errors, different approximate representation formats can be enabled, which sometimes facilitate the interpretation of the results. The commands that allow numerical approximation are the following:
format long |
Delivers results to 16 significant decimal figures. |
format short |
Delivers results to 4 decimal places. This is MATLAB’s default format. |
format long e |
Provides the results to 16 decimal figures more than the power of 10 required. |
format short e |
Provides the results to four decimal figures more than the power of 10 required. |
format long g |
Provides the results in optimal long format. |
format short g |
Provides the results in optimum short format. |
bank format |
Delivers results to 2 decimal places. |
format rat |
Returns the results in the form of a rational number approximation. |
format + |
Returns the sign (+, -) and ignores the imaginary part of complex numbers. |
format hex |
Returns results in hexadecimal format. |
vpa ‘operations’ n |
Returns the result of the specified operations to n significant digits. |
numeric (‘expr’) |
Provides the value of the expression numerically approximated by the current active format. |
digits (n) |
Returns results to n significant digits. |
Using format gives a numerical approximation of 174/13 in the way specified after the format command:
>> 174/13
ans =
13.3846
>> format long; 174/13
ans =
13.38461538461539
>> format long e; 174/13
ans =
1.338461538461539e + 001
>> format short e; 174/13
ans =
1.3385e + 001
>> format long g; 174/13
ans =
13.3846153846154
>> format short g; 174/13
ans =
13.385
>> format bank; 174/13
ans =
13.38
>> format hex; 174/13
ans =
402ac4ec4ec4ec4f
Now we will see how the value of sqrt (17) can be calculated to any precision that we desire:
>> vpa ' 174/13 ' 10
ans =
13.38461538
>> vpa ' 174/13 ' 15
ans =
13.3846153846154
>> digits (20); vpa ' 174/13 '
ans =
13.384615384615384615
Integers
In MATLAB all common operations with whole numbers are exact, regardless of the size of the output. If we want the result of an operation to appear on screen to a certain number of significant figures, we use the symbolic computation command vpa (variable precision arithmetic), whose syntax we already know.
For example, the following calculates 6^400 to 450 significant figures:
>> '6 vpa ^ 400' 450
ans =
182179771682187282513946871240893712673389715281747606674596975493339599720905327003028267800766283867331479599455916367452421574456059646801054954062150177042349998869907885947439947961712484067309738073652485056311556920850878594283008099992731076250733948404739350551934565743979678824151197232629947748581376.
The result of the operation is precise, always displaying a point at the end of the result. In this case it turns out that the answer has fewer than 450 digits anyway, so the solution is exact. If you require a smaller number of significant figures, that number can be specified and the result will be rounded accordingly. For example, calculating the above power to only 50 significant figures we have:
>> '6 vpa ^ 400' 50
ans =
. 18217977168218728251394687124089371267338971528175e312
Functions of Integers and Divisibility
There are several functions in MATLAB with integer arguments, the majority of which are related to divisibility. Among the most typical functions with integer arguments are the following:
rem (n, m) |
Returns the remainder of the division of n by m (also valid when n and m are real). |
sign (n) |
The sign of n (i.e. 1 if n > 0, - 1 if n < 0). |
max (n1, n2) |
The maximum of n1 and n2. |
min (n1, n2) |
The minimum of n1 and n2. |
gcd (n1, n2) |
The greatest common divisor of n1 and n2. |
lcm (n1, n2) |
The least common multiple of n1 and n2. |
factorial (n) |
n factorial (i.e. n(n-1) (n-2)...1) |
factor (n) |
Returns the prime factorization of n. |
Below are some examples.
The remainder of division of 17 by 3:
>> rem (17,3)
ans =
2
The remainder of division of 4.1 by 1.2:
>> rem (4.1,1.2)
ans =
0.5000
The remainder of division of - 4.1 by 1.2:
>> rem (-4.1,1.2)
ans =
-0.5000
The greatest common divisor of 1000, 500 and 625:
>> gcd (1000, gcd (500,625))
ans =
125.00
The least common multiple of 1000, 500 and 625:
>> lcm (1000, lcm (500,625))
ans =
5000.00
Alternative Bases
MATLAB allows you to work with numbers to any base, as long as the extended symbolic math toolbox is available. It also allows you to express all kinds of numbers in different bases. This is implemented via the following functions:
dec2base (decimal, n_base) |
Converts the specified decimal number to the new base n_base. |
base2dec(number,b) |
Converts the given number in base b to a decimal number. |
dec2bin (decimal) |
Converts the specified decimal number to base 2 (binary). |
dec2hex (decimal) |
Converts the specified decimal number to base 16 (hexadecimal). |
bin2dec (binary) |
Converts the specified binary number to decimal. |
hex2dec (hexadecimal) |
Converts the specified base 16 number to decimal. |
Below are some examples.
Represent in base 10 the base 2 number 100101.
>> base2dec('100101',2)
ans =
37.00
Represent in base 10 the hexadecimal number FFFFAA00.
>> base2dec ('FFFFAA0', 16)
ans =
268434080.00
Represent the result of the base 16 operation FFFAA2+FF-1 in base 10.
>> base2dec('FFFAA2',16) + base2dec('FF',16)-1
ans =
16776096.00
Real Numbers
As is well known, the set of real numbers is the disjoint union of the set of rational numbers and the set of irrational numbers. A rational number is a number of the form p/q, where p and q are integers. In other words, the rational numbers are those numbers that can be represented as a quotient of two integers. The way in which MATLAB treats rational numbers differs from the majority of calculators. If we ask a calculator to calculate the sum 1/2 + 1/3 + 1/4, most will return something like 1.0833, which is no more than an approximation of the result.
The rational numbers are ratios of integers, and MATLAB can work with them in exact mode, so the result of an arithmetic expression involving rational numbers is always given precisely as a ratio of two integers. To enable this, activate the rational format with the command format rat. If the reader so wishes, MATLAB can also return the results in decimal form by activating any other type of format instead (e.g. format short or format long). MATLAB evaluates the above mentioned sum in exact mode as follows:
>> format rat
>> 1/2 + 1/3 + 1/4
ans =
13/12
Unlike calculators, MATLAB ensures its operations with rational numbers are accurate by maintaining the rational numbers in the form of ratios of integers. In this way, calculations with fractions are not affected by rounding errors, which can become very serious, as evidenced by the theory of errors. Note that, once the rational format is enabled, when MATLAB adds two rational numbers the result is returned in symbolic form as a ratio of integers, and operations with rational numbers will continue to be exact until an alternative format is invoked.
A floating point number, or a number with a decimal point, is interpreted as exact if the rational format is enabled. Thus a floating point expression will be interpreted as an exact rational expression while any irrational numbers in a rational expression will be represented by an appropriate rational approximation.
>> format rat
>> 10/23 + 2.45/44
ans =
1183 / 2412
The other fundamental subset of the real numbers is the set of irrational numbers, which have always created difficulties in numerical calculation due to their special nature. The impossibility of representing an irrational number accurately in numeric mode (using the ten digits from the decimal numbering system) is the cause of most of the problems. MATLAB represents the results with an accuracy which can be set as required by the user. An irrational number, by definition, cannot be represented exactly as the ratio of two integers. If ordered to calculate the square root of 17, by default MATLAB returns the number 5.1962.
>> sqrt (27)
ans =
5.1962
MATLAB incorporates the following common irrational constants and notions:
pi |
The number π = 3.1415926... |
exp (1) |
The number e = 2.7182818... |
Inf |
Infinity (returned, for example, when it encounters 1/0). |
NaN |
Uncertainty (returned, for example, when it encounters 0/0). |
realmin |
Returns the smallest possible normalized floating-point number in IEEE double precision. |
realmax |
Returns the largest possible finite floating-point number in IEEE double precision. |
The following examples illustrate how MATLAB outputs these numbers and notions.
>> long format
>> pi
ans =
3.14159265358979
>> exp (1)
ans =
2.71828182845905
>> 1/0
Warning: Divide by zero.
ans =
Inf
>> 0/0
Warning: Divide by zero.
ans =
NaN
>> realmin
ans =
2. 225073858507201e-308
>> realmax
ans =
1. 797693134862316e + 308
Functions with Real Arguments
The disjoint union of the set of rational numbers and the set of irrational numbers is the set of real numbers. In turn, the set of rational numbers has the set of integers as a subset. All functions applicable to real numbers are also valid for integers and rational numbers. MATLAB provides a full range of predefined functions, most of which are discussed in the subsequent chapters of this book. Within the group of functions with real arguments offered by MATLAB, the following are the most important:
Trigonometric functions
Function |
Inverse |
---|---|
sin (x) |
asin (x) |
cos (x) |
acos (x) |
tan(x) |
atan(x) and atan2(y,x) |
csc (x) |
acsc (x) |
sec (x) |
asec (x) |
cot (x) |
acot (x) |
Hyperbolic functions
Function |
Inverse |
---|---|
sinh (x) |
asinh (x) |
cosh(x) |
acosh(x) |
tanh(x) |
atanh(x) |
csch(x) |
acsch(x) |
sech(x) |
asech(x) |
coth (x) |
acoth (x) |
Exponential and logarithmic functions
Function |
Meaning |
---|---|
exp (x) |
Exponential function in base e (e ^ x). |
log (x) |
Base e logarithm of x. |
log10 (x) |
Base 10 logarithm of x. |
log2 (x) |
Base 2 logarithm of x. |
pow2 (x) |
2 raised to the power x. |
sqrt (x) |
The square root of x. |
Numeric variable-specific functions
Function |
Meaning |
---|---|
abs (x) |
The absolute value of x. |
floor (x) |
The largest integer less than or equal to x. |
ceil (x) |
The smaller integer greater than or equal to x. |
round (x) |
The closest integer to x. |
fix (x) |
Removes the fractional part of x. |
rem (a, b) |
Returns the remainder of the division of a by b. |
sign (x) |
Returns the sign of x (1 if x > 0,0 if x = 0,- 1 if x < 0). |
Here are some examples:
>> sin(pi/2)
ans =
1
>> asin (1)
ans =
1.57079632679490
>> log (exp (1) ^ 3)
ans =
3.00000000000000
The function round is demonstrated in the following two examples:
>> round (2.574)
ans =
3
>> round (2.4)
ans =
2
The function ceil is demonstrated in the following two examples:
>> ceil (4.2)
ans =
5
>> ceil (4.8)
ans =
5
The function floor is demonstrated in the following two examples:
>> floor (4.2)
ans =
4
>> floor (4.8)
ans =
4
The fix function simply removes the fractional part of a real number:
» fix (5.789)
ans =
5
Complex Numbers
Operations on complex numbers are well implemented in MATLAB. MATLAB follows the convention that i or j represents the key value in complex analysis, the imaginary number √- 1. All the usual arithmetic operators can be applied to complex numbers, and there are also some specific functions which have complex arguments. Both the real and the imaginary part of a complex number can be a real number or a symbolic constant, and operations with them are always performed in exact mode, unless otherwise instructed or necessary, in which case an approximation of the result is returned. As the imaginary unit is represented by the symbol i or j, the complex numbers are expressed in the form a+bi or a+bj. Note that you don't need to use the product symbol (asterisk) before the imaginary unit:
>> (1-5i)*(1-i)/(-1+2i)
ans =
-1.6000 + 2.8000i
>> format rat
>> (1-5i) *(1-i) /(-1+2i)
ans =
-8/5 + 14/5i
Functions with Complex Arguments
Working with complex variables is very important in mathematical analysis and its many applications in engineering. MATLAB implements not only the usual arithmetic operations with complex numbers, but also various complex functions. The most important functions are listed below.
Trigonometric functions
Function |
Inverse |
---|---|
sin (z) |
asin (z) |
cos (z) |
acos (z) |
tan (z) |
atan(z) and atan2(imag(z),real(z)) |
csc (z) |
acsc (z) |
sec (z) |
asec (z) |
cot (z) |
acot (z) |
Hyperbolic functions
Function |
Inverse |
---|---|
sinh (z) |
asinh (z) |
cosh(z) |
acosh(z) |
tanh(z) |
atanh(z) |
csch(z) |
acsch(z) |
sech(z) |
asech(z) |
coth (z) |
acoth (z) |
Exponential and logarithmic functions
Function |
Meaning |
---|---|
exp (z) |
Exponential function in base e (e ^ z) |
log (z) |
Base e logarithm of z |
log10 (z) |
Base 10 logarithm of z. |
log2 (z) |
Base 2 logarithm of z. |
pow2 (z) |
2 to the power z. |
sqrt (z) |
The square root of z. |
Specific functions for the real and imaginary part
Function |
Meaning |
---|---|
floor (z) |
Applies the floor function to real(z) and imag(z). |
ceil (z) |
Applies the ceil function to real(z) and imag(z). |
round (z) |
Applies the round function to real(z) and imag(z). |
fix (z) |
Applies the fix function to real(z) and imag(z). |
Specific functions for complex numbers
Function |
Meaning |
---|---|
abs (z) |
The complex modulus of z. |
angle (z) |
The argument of z. |
conj (z) |
The complex conjugate of z. |
real (z) |
The real part of z. |
imag (z) |
The imaginary part of z. |
Below are some examples of operations with complex numbers.
>> round(1.5-3.4i)
ans =
2 - 3i
>> real(i^i)
ans =
0.2079
>> (2+2i)^2/(-3-3*sqrt(3)*i)^90
ans =
0502e-085 - 1 + 7. 4042e-070i
>> sin (1 + i)
ans =
1.2985 + 0. 6350i
Elementary Functions that Support Complex Vector Arguments
MATLAB easily handles vector and matrix calculus. Indeed, its name, MAtrix LABoratory, already gives an idea of its power in working with vectors and matrices. MATLAB allows you to work with functions of a complex variable, but in addition this variable can even be a vector or a matrix. Below is a table of functions with complex vector arguments.
max (V) |
The maximum component of V. (max is calculated for complex vectors as the complex number with the largest complex modulus (magnitude), computed with max(abs(V)). Then it computes the largest phase angle with max(angle(x)), if necessary.) |
min (V) |
The minimum component of V. (min is calculated for complex vectors as the complex number with the smallest complex modulus (magnitude), computed with min(abs(A)). Then it computes the smallest phase angle with min(angle(x)), if necessary.) |
mean (V) |
Average of the components of V. |
median (V) |
Median of the components of V. |
std (V) |
Standard deviation of the components of V. |
sort (V) |
Sorts the components of V in ascending order. For complex entries the order is by absolute value and argument. |
sum (V) |
Returns the sum of the components of V. |
prod (V) |
Returns the product of the components of V, so, for example, n! = prod(1:n). |
cumsum (V) |
Gives the cumulative sums of the components of V. |
cumprod (V) |
Gives the cumulative products of the components of V. |
diff (V) |
Gives the vector of first differences of V (Vt - V-t-1). |
gradient (V) |
Gives the gradient of V. |
del2 (V) |
Gives the Laplacian of V (5-point discrete). |
fft (V) |
Gives the discrete Fourier transform of V. |
fft2 (V) |
Gives the two-dimensional discrete Fourier transform of V. |
ifft (V) |
Gives the inverse discrete Fourier transform of V. |
ifft2 (V) |
Gives the inverse two-dimensional discrete Fourier transform of V. |
These functions also support a complex matrix as an argument, in which case the result is a vector of column vectors whose components are the results of applying the function to each column of the matrix.
Here are some examples:
>> V = 2:7, W = [5 + 3i 2-i 4i]
V =
2 3 4 5 6 7
W =
2.0000 - 1.0000i 0 + 4.0000i 5.0000 + 3.0000i
>> diff(V), diff(W)
ans =
1 1 1 1 1
ans =
-2.0000 + 5.0000i 5.0000 - 1.0000i
>> cumprod(V), cumsum(V)
ans =
2 6 24 120 720 5040
ans =
2 5 9 14 20 27
>> cumsum(W), mean(W), std(W), sort(W), sum(W)
ans =
2.0000 - 1.0000i 2.0000 + 3.0000i 7.0000 + 6.0000i
ans =
2.3333 + 2.0000i
ans =
3.6515
ans =
2.0000 - 1.0000i 0 + 4.0000i 5.0000 + 3.0000i
ans =
7.0000 + 6.0000i
>> mean(V), std(V), sort(V), sum(V)
ans =
4.5000
ans =
1.8708
ans =
2 3 4 5 6 7
ans =
27
>> fft(W), ifft(W), fft2(W)
ans =
7.0000 + 6.0000i 0.3660 - 0.1699i -1.3660 - 8.8301i
ans =
2.3333 + 2.0000i -0.4553 - 2.9434i 0.1220 - 0.0566i
ans =
7.0000 + 6. 0000i 0.3660 - 0. 1699i - 1.3660 - 8. 8301i
Elementary Functions that Support Complex Matrix Arguments
• Trigonometric |
|
sin (z) |
Sine function |
sinh (z) |
Hyperbolic sine function |
asin (z) |
Arcsine function |
asinh (z) |
Hyperbolic arcsine function |
cos (z) |
Cosine function |
cosh (z) |
Hyperbolic cosine function |
acos (z) |
Arccosine function |
acosh (z) |
Hyperbolic arccosine function |
tan(z) |
Tangent function |
tanh (z) |
Hyperbolic tangent function |
atan (z) |
Arctangent function |
atan2 (z) |
Fourth quadrant arctangent function |
atanh (z) |
Hyperbolic arctangent function |
sec (z) |
Secant function |
sech (z) |
Hyperbolic secant function |
asec (z) |
Arccosecant function |
asech (z) |
Hyperbolic arccosecant function |
csc (z) |
Cosecant function |
csch (z) |
Hyperbolic cosecant function |
acsc (z) |
Arccosecant function |
acsch (z) |
Hyperbolic arccosecant function |
cot (z) |
Cotangent function |
coth (z) |
Hyperbolic cotangent function |
acot (z) |
Arccotangent function |
acoth (z) |
Hyperbolic arccotangent function |
• Exponential |
|
exp (z) |
Base e exponential function |
log (z) |
Natural logarithm function (base e) |
log10 (z) |
Base 10 logarithm function |
sqrt (z) |
Square root function |
• Complex |
|
abs (z) |
Modulus or absolute value |
angle (z) |
Argument |
conj (z) |
Complex conjugate |
imag (z) |
Imaginary part |
real (z) |
Real part |
• Numerical |
|
fix (z) |
Removes the fractional part |
floor (z) |
Rounds to the nearest lower integer |
ceil (z) |
Rounds to the nearest greater integer |
round (z) |
Performs common rounding |
rem (z1, z2) |
Returns the remainder of the division of z1 by z2 |
sign (z) |
The sign of z |
• Matrix |
|
expm (Z) |
Matrix exponential function by default |
expm1 (Z) |
Matrix exponential function in M-file |
expm2 (Z) |
Matrix exponential function via Taylor series |
expm3 (Z) |
Matrix exponential function via eigenvalues |
logm (Z) |
Logarithmic matrix function |
sqrtm (Z) |
Matrix square root function |
funm(Z,‘function’) |
Applies the function to the array Z |
Here are some examples:
>> A = [7 8 9; 1 2 3; 4 5 6], B = [1+2i 3+i;4+i,i]
A =
7 8 9
1 2 3
4 5 6
B =
1.0000 + 2.0000i 3.0000 + 1.0000i
4.0000 + 1.0000i 0 + 1.0000i
>> sin(A), sin(B), exp(A), exp(B), log(B), sqrt(B)
ans =
0.6570 0.9894 0.4121
0.8415 0.9093 0.1411
-0.7568 -0.9589 -0.2794
ans =
3.1658 + 1.9596i 0.2178 - 1.1634i
-1.1678 - 0.7682i 0 + 1.1752i
ans =
1.0e+003 *
1.0966 2.9810 8.1031
0.0027 0.0074 0.0201
0.0546 0.1484 0.4034
ans =
-1.1312 + 2.4717i 10.8523 +16.9014i
29.4995 +45.9428i 0.5403 + 0.8415i
ans =
0.8047 + 1.1071i 1.1513 + 0.3218i
1.4166 + 0.2450i 0 + 1.5708i
ans =
1.2720 + 0.7862i 1.7553 + 0.2848i
2.0153 + 0.2481i 0.7071 + 0.7071i
The exponential functions, square root and logarithm used above apply to the array elementwise and have nothing to do with the matrix exponential and logarithmic functions that are used below.
>> expm(B), logm(A), abs(B), imag(B)
ans =
-27.9191 +14.8698i -20.0011 +12.0638i
-24.7950 + 17.6831i-17.5059 + 14.0445i
ans =
11.9650 12.8038 - 19.9093
-21.7328-22.1157 44.6052
11.8921 12.1200 - 21.2040
ans =
2.2361 3.1623
4.1231 1.0000
ans =
2 1
1 1
>> fix(sin(B)), ceil(log(A)), sign(B), rem(A,3*ones(3))
ans =
3.0000 + 1.0000i 0 - 1.0000i
-1.0000 0 + 1.0000i
ans =
2 3 3
0 1 2
2 2 2
ans =
0.4472 + 0.8944i 0.9487 + 0.3162i
0.9701 + 0.2425i 0 + 1.0000i
ans =
1 2 0
1 2 0
1 2 0
Random Numbers
MATLAB can easily generate (pseudo) random numbers. The function rand generates uniformly distributed random numbers and the function randn generates normally distributed random numbers. The most interesting features of MATLAB’s random number generator are presented in the following table.
rand |
Returns a uniformly distributed random decimal number from the interval [0,1]. |
rand (n) |
Returns an array of size n×n whose elements are uniformly distributed random decimal numbers from the interval [0,1]. |
rand (m, n) |
Returns an array of dimension m×n whose elements are uniformly distributed random decimal numbers from the interval [0,1]. |
rand (size (a)) |
Returns an array of the same size as the matrix A and whose elements are uniformly distributed random decimal numbers from the interval [0,1]. |
rand (‘seed’) |
Returns the current value of the uniform random number generator seed. |
rand(‘seed’,n) |
Assigns to n the current value of the uniform random number generator seed. |
randn |
Returns a normally distributed random decimal number (mean 0 and variance 1). |
randn (n) |
Returns an array of dimension n×n whose elements are normally distributed random decimal numbers (mean 0 and variance 1). |
randn (m, n) |
Returns an array of dimension m×n whose elements are normally distributed random decimal numbers (mean 0 and variance 1). |
randn (size (a)) |
Returns an array of the same size as the matrix A and whose elements are normally distributed random decimal numbers (mean 0 and variance 1). |
randn (‘seed’) |
Returns the current value of the normal random number generator seed. |
randn(‘seed’,n) |
Assigns to n the current value of the uniform random number generator seed. |
Here are some examples:
>> [rand, rand (1), randn, randn (1)]
ans =
0.9501 0.2311 -0.4326 -1.6656
>> [rand(2), randn(2)]
ans =
0.6068 0.8913 0.1253 -1.1465
0.4860 0.7621 0.2877 1.1909
>> [rand(2,3), randn(2,3)]
ans =
0.3529 0.0099 0.2028 -0.1364 1.0668-0.0956
0.8132 0.1389 0.1987 0.1139 0.0593 - 0.8323
Operators
MATLAB features arithmetic, logical, relational, conditional and structural operators.
Arithmetic Operators
There are two types of arithmetic operators in MATLAB: matrix arithmetic operators, which are governed by the rules of linear algebra, and arithmetic operators on vectors, which are performed elementwise. The operators involved are presented in the following table.
Operator |
Role played |
---|---|
+ |
Sum of scalars, vectors, or matrices |
- |
Subtraction of scalars, vectors, or matrices |
* |
Product of scalars or arrays |
.* |
Product of scalars or vectors |
|
AB = inv (A) * B, where A and B are matrices |
. |
A. B = [B(i,j) /A (i, j)], where A and B are vectors [dim (A) = dim (B)] |
/ |
Quotient, or B/A = B * inv (A), where A and B are matrices |
./ |
A / B = [A(i,j)/b (i, j)], where A and B are vectors [dim (A) = dim (B)] |
^ |
Power of a scalar or matrix (M p) |
.^ |
Power of vectors (A. ^ B = [A(i,j)B (i, j)], for vectors A and B) |
Simple mathematical operations between scalars and vectors apply the scalar to all elements of the vector according to the defined operation, and simple operators between vectors are performed element by element. Below is the specification of these operators:
a = {a1, a2,..., an}, b = {b1, b2,..., bn}, c = scalar |
|
a + c = [a1 +c, a2+ c,..., an+c] |
Sum of a scalar and a vector |
a * c = [a1 * c,a2* c ,..., an * c] |
Product of a scalar and a vector |
a + b = [ a1+b1 a2+b2 ... an+bn] |
Sum of two vectors |
a. * b = [ a1*b1 a2*b2 ... an*bn] |
Product of two vectors |
a. / b = [ a1/b1 a2/b2 ... an/bn] |
Ratio to the right of two vectors |
a. b = [ a11 a22 ... ann] |
Ratio to the left of two vectors |
a. ^ c = [a1 ^c, a2^ c ,..., an ^ c] |
Vector to the power of a scalar |
c. ^ a = [c ^ a1,c ^ a2,... ,c ^ an] |
Scalar to the power of a vector |
a.^b = [a1^b1 a2^b2 ... an^bn] |
Vector to the power of a vector |
It must be borne in mind that the vectors must be of the same length and that in the product, quotient and power the first operand must be followed by a point.
The following example involves all of the above operators.
>> X = [5,4,3]; Y = [1,2,7]; a = X + Y, b = X-Y, c = x * Y, d = 2. * X,...
e = 2/X, f = 2. Y, g = x / Y, h =. X, i = x ^ 2, j = 2. ^ X, k = X. ^ Y
a =
6 6 10
b =
4 2 -4
c =
5 8 21
d =
10 8 6
e =
0.4000 0.5000 0.6667
f =
0.5000 1.0000 3.5000
g =
5.0000 2.0000 0.4286
h =
5.0000 2.0000 0.4286
i =
25 16 9
j =
32 16 8
k =
5 16 2187
The above operations are all valid since in all cases the variable operands are of the same dimension, so the operations are successfully carried out element by element. For the sum and the difference there is no distinction between vectors and matrices, as the operations are identical in both cases.
The most important operators for matrix variables are specified below:
A + B, A - B, A * B |
Addition, subtraction and product of matrices. |
AB |
If A is square, AB = inv (A) * B. If A is not square, AB is the solution, in the sense of least-squares, of the system AX = B. |
B/A |
Coincides with (A ' B')'. |
An |
Coincides with A * A * A *... *A n times (n integer). |
pA |
Performs the power operation only if p is a scalar. |
Here are some examples:
>> X = [5,4,3]; Y = [1,2,7]; l = X'* Y, m = X * Y ', n = 2 * X, o = X / Y, p = YX
l =
5 10 35
4 8 28
3 6 21
m =
34
n =
10 8 6
o =
0.6296
p =
0 0 0
0 0 0
0.7143 0.5714 0.4286
All of the above matrix operations are well defined since the dimensions of the operands are compatible in every case. We must not forget that a vector is a particular case of matrix, but to operate with it in matrix form (not element by element), it is necessary to respect the rules of dimensionality for matrix operations. For example, the vector operations X. ' * Y and X.*Y' make no sense, since they involve vectors of different dimensions. Similarly, the matrix operations X * Y, 2/X, 2Y, X ^ 2, 2 ^ X and X ^ Y make no sense, again because of a conflict of dimensions in the arrays.
Here are some more examples of matrix operators.
>> M = [1,2,3;1,0,2;7,8,9]
M =
1 2 3
1 0 2
7 8 9
>> B = inv (M), C = M ^ 2, D = M ^(1/2), E = 2 ^ M
B =
-0.8889 0.3333 0.2222
0.2778 -0.6667 0.0556
0.4444 0.3333 -0.1111
C =
24 26 34
15 18 21
78 86 118
D =
0.5219 + 0.8432i 0.5793 - 0.0664i 0.7756 - 0.2344i
0.3270 + 0.0207i 0.3630 + 1.0650i 0.4859 - 0.2012i
1.7848 - 0.5828i 1.9811 - 0.7508i 2.6524 + 0.3080i
E =
1. 0e + 003 *
0.8626 0.9568 1.2811
0.5401 0.5999 0.8027
2.9482 3.2725 4.3816
Relational Operators
MATLAB also provides relational operators. Relational operators perform element by element comparisons between two matrices and return an array of the same size whose elements are zero if the corresponding relationship is true, or one if the corresponding relation is false. The relational operators can also compare scalars with vectors or matrices, in which case the scalar is compared to all the elements of the array. Below is a table of these operators.
< |
Less than (for complex numbers this applies only to the real parts) |
< = |
Less than or equal (only applies to real parts of complex numbers) |
> |
Greater than (only applies to real parts of complex numbers) |
> = |
Greater than or equal (only applies to real parts of complex numbers) |
x == y |
Equality (also applies to complex numbers) |
x ~ = y |
Inequality (also applies to complex numbers) |
Logical Operators
MATLAB provides symbols to denote logical operators. The logical operators shown in the following table offer a way to combine or negate relational expressions.
~ A |
Logical negation (NOT) or the complement of A. |
A & B |
Logical conjunction (AND) or the intersection of A and B. |
A | B |
Logical disjunction (OR) or the union of A and B. |
XOR (A, B) |
Exclusive OR (XOR) or the symmetric difference of A and B (takes the value 1 if A or B, but not both, are 1). |
Here are some examples:
>> A = 2:7;P =(A>3) & (A<6)
P =
0 0 1 1 0 0
Returns 1 when the corresponding element of A is greater than 3 and less than 6, and returns 0 otherwise.
>> X = 3 * ones (3.3); X > = [7 8 9; 4 5 6 ; 1 2 3]
ans =
0 0 0
0 0 0
1 1 1
The elements of the solution array corresponding to those elements of X which are greater than or equal to the equivalent entry of the matrix [7 8 9; 4 5 6 ; 1 2 3] are assigned the value 1. The remaining elements are assigned the value 0.
Logical Functions
MATLAB implements logical functions whose output can take the value true (1) or false (0). The following table shows the most important logical functions.
exist(A) |
Checks if the variable or function exists (returns 0 if A does not exist and a number between 1 and 5, depending on the type, if it does exist). |
any(V) |
Returns 0 if all elements of the vector V are null and returns 1 if some element of V is non-zero. |
any(A) |
Returns 0 for each column of the matrix A with all null elements and returns 1 for each column of the matrix A which has non-null elements. |
all(V) |
Returns 1 if all the elements of the vector V are non-null and returns 0 if some element of V is null. |
all(A) |
Returns 1 for each column of the matrix A with all non-null elements and returns 0 for each column of the matrix A with at least one null element. |
find (V) |
Returns the places (or indices) occupied by the non-null elements of the vector V. |
isnan (V) |
Returns 1 for the elements of V that are indeterminate and returns 0 for those that are not. |
isinf (V) |
Returns 1 for the elements of V that are infinite and returns 0 for those that are not. |
isfinite (V) |
Returns 1 for the elements of V that are finite and returns 0 for those that are not. |
isempty (A) |
Returns 1 if A is an empty array and returns 0 otherwise (an empty array is an array such that one of its dimensions is 0). |
issparse (A) |
Returns 1 if A is a sparse matrix and returns 0 otherwise. |
isreal (V) |
Returns 1 if all the elements of V are real and 0 otherwise. |
isprime (V) |
Returns 1 for all elements of V that are prime and returns 0 for all elements of V that are not prime. |
islogical (V) |
Returns 1 if V is a logical vector and 0 otherwise. |
isnumeric (V) |
Returns 1 if V is a numeric vector and 0 otherwise. |
ishold |
Returns 1 if the properties of the current graph are retained for the next graph and only new elements will be added and 0 otherwise. |
isieee |
Returns 1 if the computer is capable of IEEE standard operations. |
isstr (S) |
Returns 1 if S is a string and 0 otherwise. |
ischart (S) |
Returns 1 if S is a string and 0 otherwise. |
isglobal (A) |
Returns 1 if A is a global variable and 0 otherwise. |
isletter (S) |
Returns 1 if S is a letter of the alphabet and 0 otherwise. |
isequal (A, B) |
Returns 1 if the matrices or vectors A and B are equal, and 0 otherwise. |
ismember(V, W) |
Returns 1 for every element of V which is in W and 0 for every element V that is not in W. |
Below are some examples using the above defined logical functions.
>> V = [1,2,3,4,5,6,7,8,9], isprime(V), isnumeric(V), all(V), any(V)
V =
1 2 3 4 5 6 7 8 9
ans =
0 1 1 0 1 0 1 0 0
ans =
1
ans =
1
ans =
1
>> B = [Inf, -Inf, pi, NaN], isinf(B), isfinite(B), isnan(B), isreal(B)
B =
Inf - Inf 3.1416 NaN
ans =
1 1 0 0
ans =
0 0 1 0
ans =
0 0 0 1
ans =
1
>> ismember ([1,2,3], [8,12,1,3]), A = [2,0,1];B = [4,0,2]; isequal (2A * B)
ans =
1 0 1
ans =
1
EXERCISE 2-1
Find the number of ways of choosing 12 elements from 30 without repetition, the remainder of the division of 2134 by 3, the prime decomposition of 18900, the factorial of 200 and the smallest number N which when divided by 16,24,30 and 32 leaves remainder 5.
>> factorial (30) / (factorial (12) * factorial(30-12))
ans =
8.6493e + 007
The command vpa is used to present the exact result.
>> vpa 'factorial (30) / (factorial (12) * factorial(30-12))' 15
ans =
86493225.
>> rem(2^134,3)
ans =
0
>> factor (18900)
ans =
2 2 3 3 3 5 5 7
>> factorial (100)
ans =
9. 3326e + 157
The command vpa is used to present the exact result.
>> vpa ' factorial (100)' 160
ans =
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000.
N-5 is the least common multiple of 16, 24, 30 and 32.
>> lcm (lcm (16.24), lcm (30,32))
ans =
480
Then N = 480 + 5 = 485.
EXERCISE 2-2
In base 5 find the result of the operation defined by a25aaff616 + 6789aba12 + 356718 + 11002213 - 1250. In base 13 find the result of the operation (6665517 )* (aa199800a11 ) +(fffaaa12516 ) / (333314 + 6).
The result of the first operation in base 10 is calculated as follows:
>> base2dec('a25aaf6',16) + base2dec('6789aba',12) +...
base2dec('35671',8) + base2dec('1100221',3)-1250
ans =
190096544
We then convert this to base 5:
>> dec2base (190096544,5)
ans =
342131042134
Thus, the final result of the first operation in base 5 is 342131042134.
The result of the second operation in base 10 is calculated as follows:
>> base2dec('666551',7) * base2dec('aa199800a',11) +...
79 * base2dec('fffaaa125',16) / (base2dec ('33331', 4) + 6)
ans =
2. 7537e + 014
We now transform the result obtained into base 13.
>> dec2base (275373340490852,13)
ans =
BA867963C1496
EXERCISE 2-3
In base 13, find the result of the following operation:
(6665517 )* (aa199800a11 ) + (fffaaa12516 ) / (333314 + 6).
First, we perform the operation in base 10:
A more direct way of doing all of the above is:
>> base2dec('666551',7) * base2dec('aa199800a',11) +...
79 * base2dec('fffaaa125',16) / (base2dec ('33331', 4) + 6)
ans =
2. 753733404908515e + 014
We now transform the result obtained into base 13.
>> dec2base (275373340490852,13)
ans =
BA867963C1496
EXERCISE 2-4
Given the complex numbers X = 2 + 2i and Y=-3-3 , calculate Y3 X2/Y90, Y1/2, Y3/2 and ln (X).
>> X=2+2*i; Y=-3-3*sqrt(3)*i;
>> Y^3
ans =
216
>> X ^ 2 / Y ^ 90
ans =
050180953422426e-085 - 1 + 7. 404188256695968e-070i
>> sqrt (Y)
ans =
1.22474487139159 - 2.12132034355964i
>> sqrt(Y^3)
ans =
14.69693845669907
>> log (X)
ans =
1.03972077083992 + 0.78539816339745i
EXERCISE 2-5
Calculate the value of the following operations with complex numbers:
>> (i^8-i^(-8))/(3-4*i) + 1
ans =
1
>> i^(sin(1+i))
ans =
-0.16665202215166 + 0.32904139450307i
>> (2+log(i))^(1/i)
ans =
1.15809185259777 - 1.56388053989023i
>> (1+i)^i
ans =
0.42882900629437 + 0.15487175246425i
>> i^(log(1+i))
ans =
0.24911518828716 + 0.15081974484717i
>> (1+sqrt(3)*i)^(1-i)
ans =
5.34581479196611 + 1. 97594883452873i
EXERCISE 2-6
Calculate the real part, imaginary part, modulus and argument of each of the following expressions:
>> Z1 = i ^ 3 * i; Z2 = (1 + sqrt (3) * i) ^(1-i); Z3 =(i^i) ^ i;Z4 = i ^ i;
>> format short
>> real ([Z1 Z2 Z3 Z4])
ans =
1.0000 5.3458 0.0000 0.2079
>> imag ([Z1 Z2 Z3 Z4])
ans =
0 1.9759 - 1.0000 0
>> abs ([Z1 Z2 Z3 Z4])
ans =
1.0000 5.6993 1.0000 0.2079
>> angle ([Z1 Z2 Z3 Z4])
ans =
0 0.3541 - 1.5708 0
EXERCISE 2-7
Generate a square matrix of order 4 whose elements are uniformly distributed random numbers from [0,1]. Generate another square matrix of order 4 whose elements are normally distributed random numbers from [0,1]. Find the present generating seeds, change their value to ½ and rebuild the two arrays of random numbers.
>> rand (4)
ans =
0.9501 0.8913 0.8214 0.9218
0.2311 0.7621 0.4447 0.7382
0.6068 0.4565 0.6154 0.1763
0.4860 0.0185 0.7919 0.4057
>> randn (4)
ans =
-0.4326-1.1465 0.3273 - 0.5883
-1.6656 1.1909 0.1746 2.1832
0.1253 1.1892-0.1867-0.1364
0.2877-0.0376 0.7258 0.1139
>> rand ('seed')
ans =
931316785
>> randn ('seed')
ans =
931316785
>> randn ('seed', 1/2)
>> rand ('seed', 1/2)
>> rand (4)
ans =
0.2190 0.9347 0.0346 0.0077
0.0470 0.3835 0.0535 0.3834
0.6789 0.5194 0.5297 0.0668
0.6793 0.8310 0.6711 0.4175
>> randn (4)
ans =
1.1650-0.6965 0.2641 1.2460
0.6268 1.6961 0.8717 -0.6390
0.0751 0.0591-1.4462 0.5774
0.3516 1.7971-0.7012-0.3600
EXERCISE 2-8
Given the vector variables a = [π, 2π, 3π, 4π, 5π] and b = [e, 2e, 3e, 4e, 5e], calculate c = sin (a) + b, d = cos (a), e = ln (b), f = c * d, g = c/d, h = d ^ 2, i = d ^ 2-e ^ 2 and j = 3d ^ 3-2e ^ 2.
>> a = [pi, 2 * pi, 3 * pi, 4 * pi, 5 * pi],
b = [exp (1), 2 * exp (1), 3 * exp (1), 4 * exp (1),5*exp(1)],
c=sin(a)+b,d=cos(a),e = log(b),f = c.*d,g = c./d,]
h=d.^2, i = d.^2-e.^2, j = 3*d.^3-2*e.^2
a =
3.1416 6.2832 9.4248 12.5664 15.7080
b =
2.7183 5.4366 8.1548 10.8731 13.5914
c =
2.7183 5.4366 8.1548 10.8731 13.5914
d =
-1 1 -1 1 -1
e =
1.0000 1.6931 2.0986 2.3863 2.6094
f =
-2.7183 5.4366 - 8.1548 10.8731 - 13.5914
g =
-2.7183 5.4366 - 8.1548 10.8731 - 13.5914
h =
1 1 1 1 1
i =
0 - 1.8667 - 3.4042 - 4.6944 - 5.8092
j =
-5.0000 - 2.7335 - 11.8083 - 8.3888 - 16.6183
EXERCISE 2-9
Given a uniform random square matrix M of order 3, obtain its inverse, its transpose and its diagonal. Transform it into a lower triangular matrix (replacing the upper triangular entries by 0) and rotate it 90 degrees counterclockwise. Find the sum of the elements in the first row and the sum of the diagonal elements. Extract the subarray whose diagonal elements are at 11 and 22 and also remove the subarray whose diagonal elements are at 11 and 33.
>> M = rand(3)
M =
0.6868 0.8462 0.6539
0.5890 0.5269 0.4160
0.9304 0.0920 0.7012
>> A = inv(M)
A =
-4.1588 6.6947 -0.0934
0.3255 1.5930 -1.2487
5.4758 -9.0924 1.7138
>> B = M'
B =
0.6868 0.5890 0.9304
0.8462 0.5269 0.0920
0.6539 0.4160 0.7012
>> V = diag(M)
V =
0.6868
0.5269
0.7012
>> TI = tril(M)
TI =
0.6868 0 0
0.5890 0.5269 0
0.9304 0.0920 0.7012
>> TS = triu(M)
TS =
0.6868 0.8462 0.6539
0 0.5269 0.4160
0 0 0.7012
>> TR = rot90(M)
TR =
0.6539 0.4160 0.7012
0.8462 0.5269 0.0920
0.6868 0.5890 0.9304
>> s = M(1,1)+M(1,2)+M(1,3)
s =
2.1869
>> sd = M(1,1)+M(2,2)+M(3,3)
sd =
1.9149
>> SM = M(1:2,1:2)
SM =
0.6868 0.8462
0.5890 0.5269
>> SM1 = M([1 3], [1 3])
SM1 =
0.6868 0.6539
0.9304 0.7012
EXERCISE 2-10
Given the following complex square matrix M of order 3, find its square, its square root and its base 2 and – 2 exponential:
>> M = [i 2*i 3*i; 4*i 5*i 6*i; 7*i 8*i 9*i]
M =
0 + 1.0000i 0 + 2.0000i 0 + 3.0000i
0 + 4.0000i 0 + 5.0000i 0 + 6.0000i
0 + 7.0000i 0 + 8.0000i 0 + 9.0000i
>> C = M^2
C =
-30 -36 -42
-66 -81 -96
-102 -126 -150
>> D = M^(1/2)
D =
0.8570 - 0.2210i 0.5370 + 0.2445i 0.2169 + 0.7101i
0.7797 + 0.6607i 0.9011 + 0.8688i 1.0224 + 1.0769i
0.7024 + 1.5424i 1.2651 + 1.4930i 1.8279 + 1.4437i
>> 2^M
ans =
0.7020 - 0.6146i -0.1693 - 0.2723i -0.0407 + 0.0699i
-0.2320 - 0.3055i 0.7366 - 0.3220i -0.2947 - 0.3386i
-0.1661 + 0.0036i -0.3574 - 0.3717i 0.4513 - 0.7471i
>> (-2)^M
ans =
17.3946 -16.8443i 4.3404 - 4.5696i -7.7139 + 7.7050i
1.5685 - 1.8595i 1.1826 - 0.5045i -1.2033 + 0.8506i
-13.2575 +13.1252i -3.9751 + 3.5607i 6.3073 - 6.0038i
EXERCISE 2-11
Given the complex matrix M in the previous exercise, find its elementwise logarithm and its elementwise base e exponential. Also calculate the results of the matrix operations eM and ln (M).
>> M = [i 2*i 3*i; 4*i 5*i 6*i; 7*i 8*i 9*i]
>> log(M)
ans =
0 + 1.5708i 0.6931 + 1.5708i 1.0986 + 1.5708i
1.3863 + 1.5708i 1.6094 + 1.5708i 1.7918 + 1.5708i
1.9459 + 1.5708i 2.0794 + 1.5708i 2.1972 + 1.5708i
>> exp(M)
ans =
0.5403 + 0.8415i -0.4161 + 0.9093i -0.9900 + 0.1411i
-0.6536 - 0.7568i 0.2837 - 0.9589i 0.9602 - 0.2794i
0.7539 + 0.6570i -0.1455 + 0.9894i -0.9111 + 0.4121i
>> logm(M)
ans =
-5.4033 - 0.8472i 11.9931 - 0.3109i -5.3770 + 0.8846i
12.3029 + 0.0537i -22.3087 + 0.8953i 12.6127 + 0.4183i
-4.7574 + 1.6138i 12.9225 + 0.7828i -4.1641 + 0.6112i
>> expm(M)
ans =
0.3802 - 0.6928i -0.3738 - 0.2306i -0.1278 + 0.2316i
-0.5312 - 0.1724i 0.3901 - 0.1434i -0.6886 - 0.1143i
-0.4426 + 0.3479i -0.8460 - 0.0561i -0.2493 - 0.4602i
EXERCISE 2-12
Given the complex vector V = [1 + i, i, 1-i], find the mean, median, standard deviation, variance, sum, product, maximum and minimum of its elements, as well as its gradient, its discrete Fourier transform and its inverse discrete Fourier transform.
>> [mean(V),median(V),std(V),var(V),sum(V),prod(V),max(V),min(V)]'
ans =
0.6667 - 0.3333i
1.0000 + 1.0000i
1.2910
1.6667
2.0000 - 1.0000i
0 - 2.0000i
1.0000 + 1.0000i
0 - 1.0000i
>> gradient(V)
ans =
1.0000 - 2.0000i 0.5000 0 + 2.0000i
>> fft(V)
ans =
2.0000 + 1.0000i -2.7321 + 1.0000i 0.7321 + 1.0000i
>> ifft(V)
ans =
0.6667 + 0. 3333i 0.2440 + 0. 3333i - 0.9107 + 0. 3333i
EXERCISE 2-13
Given the arrays
calculate AB – BA, A2 + B2 + C2, ABC, sqrt (A)+sqrt(B)+sqrt(C), eA(eB+ eC), their transposes and their inverses. Also verify that the product of any of the matrices A, B, C with its inverse yields the identity matrix.
>> A = [1 1 0;0 1 1;0 0 1]; B = [i 1-i 2+i;0 -1 3-i;0 0 -i]; C = [1 1 1; 0 sqrt(2)*i -sqrt(2)*i;1 -1 -1];
>> M1 = A*B-B*A
M1 =
0 -1.0000 - 1.0000i 2.0000
0 0 1.0000 - 1.0000i
0 0 0
>> M2 = A^2+B^2+C^2
M2 =
2.0000 2.0000 + 3.4142i 3.0000 - 5.4142i
0 - 1.4142i -0.0000 + 1.4142i 0.0000 - 0.5858i
0 2.0000 - 1.4142i 2.0000 + 1.4142i
>> M3 = A*B*C
M3 =
5.0000 + 1.0000i -3.5858 + 1.0000i -6.4142 + 1.0000i
3.0000 - 2.0000i -3.0000 + 0.5858i -3.0000 + 3.4142i
0 - 1.0000i 0 + 1.0000i 0 + 1.0000i
>> M4 = sqrtm(A)+sqrtm(B)-sqrtm(C)
M4 =
0.6356 + 0.8361i -0.3250 - 0.8204i 3.0734 + 1.2896i
0.1582 - 0.1521i 0.0896 + 0.5702i 3.3029 - 1.8025i
-0.3740 - 0.2654i 0.7472 + 0.3370i 1.2255 + 0.1048i
>> M5 = expm(A)*(expm(B)+expm(C))
M5 =
14.1906 - 0.0822i 5.4400 + 4.2724i 17.9169 - 9.5842i
4.5854 - 1.4972i 0.6830 + 2.1575i 8.5597 - 7.6573i
3.5528 + 0.3560i 0.1008 - 0.7488i 3.2433 - 1.8406i
>> inv(A)
ans =
1 1 1
0 1 -1
0 0 1
>> inv(B)
ans =
0 - 1.0000i -1.0000 - 1.0000i -4.0000 + 3.0000i
0 -1.0000 1.0000 + 3.0000i
0 0 0 + 1.0000i
>> inv(C)
ans =
0.5000 0 0.5000
0.2500 0 -0.3536i -0.2500
0.2500 0 +0.3536i -0.2500
>> [A*inv(A) B*inv(B) C*inv(C)]
ans =
1 0 0 1 0 0 1 0 0
0 1 0 0 1 0 0 1 0
0 0 1 0 0 1 0 0 1
>> A'
ans =
1 0 0
1 1 0
0 1 1
>> B'
ans =
0 - 1.0000i 0 0
1.0000 + 1.0000i -1.0000 0
2.0000 - 1.0000i 3.0000 + 1.0000i 0 + 1.0000i
>> C'
ans =
1.0000 0 1.0000
1.0000 0 -1.4142i -1.0000
1.0000 0 +1.4142i -1.0000