Matrix and Vector Variables (Numeric and Symbolic)
1.1 Variables
The concept of variable, like the concept of function, is essential when working with mathematical software. Obviously, the theoretical concept of a mathematical variable is fixed and independent of the software package, but how to implement and manage variables is very characteristic of each particular program. MATLAB allows you to define and manage variables, and store them in files, in a very simple way.
When extensive calculations are performed, it is convenient to give names to intermediate results. Each intermediate result is assigned to a variable to make it easier to use. For example, we can define the variable x and assign the value 5 to it in the following way:
>> x = 5
x =
5
From now on, whenever the variable x appears it will be replaced by the value 5, and it will not change its value until it is redefined.
>> x ^ 2
ans =
25
The variable x will not change until we explicitly assign another value to it.
>> x = 7 + 4
x =
11
From this moment on, the variable x will take the value 11.
It is very important to stress that the value assigned to a variable will remain fixed until it is expressly changed or if the current MATLAB session is closed. It is common to forget the definitions given to variables during a MATLAB session, causing misleading errors when the variables are used later in the session. For this reason, it is convenient to be able to remove the assignment of a value to a variable. This operation is performed by using the command clear. It is also useful to recall the variables we have defined in the present session, which is done using the command who:
Here are some examples that use the variable handling commands defined above:
>> x = 7, y = 4 + i, z = sqrt (3)
x =
7
y =
4.0000 + 1.0000i
z =
1.7321
>> p=x+y+z
p =
12.7321 + 1.0000i
>> who
Your variables are:
ans p x y z
>> whos
Name Size Elements Bytes Density Complex
ANS 1 by 1 1 8 Full No
p 1 by 1 1 16 Full Yes
x 1 by 1 1 8 Full No
y 1 by 1 1 16 Full Yes
z 1 by 1 1 8 Full No
Grand total is 5 elements using 56 bytes
Now we are going to change the value of the variable y, and delete the variable x.
>> y = pi
y =
3.1416
>> clear x;
>> whos
Name Size Elements Bytes Density Complex
ANS 1 by 1 1 8 Full No
p 1 by 1 1 16 Full Yes
y 1 by 1 1 8 Full No
z 1 by 1 1 8 Full No
Grand total is 4 elements using 40 bytes
We see that the variable x has disappeared and that the variable y has the new value assigned, but the variable p has not changed, despite having changed two of its components. For an expression that contains a variable whose value has been changed, to update its value it is necessary to rerun it:
>> p=y+z
p =
4.8736
>> whos
Name Size Elements Bytes Density Complex
ANS 1 by 1 1 8 Full No
p 1 by 1 1 8 Full No
y 1 by 1 1 8 Full No
z 1 by 1 1 8 Full No
Grand total is 4 elements using 32 bytes
Now all values are updated, including that of p.
As for the names that can be given to the variables, the only restriction is that they cannot start with a number or contain punctuation characters that are assigned a special meaning in MATLAB. It is also advisable to name variables with words that begin with lowercase letters, and in general with words completely in lowercase. This avoids collisions with MATLAB functions beginning with an uppercase letter. MATLAB is case sensitive. There can be any number of characters in the name of a variable, but MATLAB will handle only the first 19.
1.2 Variables and Special Constants
In many kinds of calculations we need to work with variables and special constants that the program has enabled. Here are some examples:
Here are some examples:
First we check if our computer is an IEEE machine, what type of computer it is, and find the current date and time:
>> isieee
ans =
1
>> computer
ans =
PCWIN
>> clock
ans =
1.0e + 003 *
1.9950 0.0110 0.0140 0.0100 0.0150 0.0079
>> date
ans =
14-mar-99
Now we check the CPU time (in seconds) that has passed since the beginning of the MATLAB session, as well as the number of floating-point operations that have occurred during that time:
>> cputime
ans =
23.5100
>> flops
ans =
1180
EXERCISE 1-1
Calculate the time in seconds that the computer takes to return the irrational number π to 50 decimal places.
>> tic; vpa 'pi' 50; toc
elapsed_time =
0.110000000000001
EXERCISE 1-2
Calculate the number of floating-point operations required to calculate the numerical value of the square root of the irrational number π to default accuracy. Consider the number π first as a numerical constant, and secondly, as a symbolic constant.
>> flops(0);numeric((pi)^(1/2));flops
ans =
427
>> flops(0);numeric('(pi)^(1/2)'),flops
ans =
6
We see that much fewer floating-point operations are required when we consider π as a symbolic constant. The calculations are faster when we work in the symbolic field.
1.3 Symbolic and Numeric Variables
MATLAB deems as symbolic any algebraic expression whose variables have previously been defined as symbolic via the command syms. For example, if we want to treat as symbolic the expression 6ab + 3a2 + 2ab in order to simplify it, we need to declare the two variables a and b as symbolic as shown below:
>> syms a b
>> simplify(6*a*b + 3*a^2 + 2*a*b)
ans =
8 * a * b + 3 * a ^ 2
The command sym can be used to transform a numeric expression into a symbolic expression. For example, if we want to simplify the numeric expression 2/5 + 6/10 + 8/20, we first need to transform it into a symbolic expression via sym(2/5+6/10+8/20), making the simplification as follows:
>> simplify (sym(2/5+6/10+8/20))
ans =
7/5
The variables contained in a symbolic expressions must be symbolic. Some commands for working with symbolic and numerical variables are described below:
EXERCISE 1-3
Solve the equation ax2 + bx + c = 0 assuming that the variable is x. Solve it when the variables are a, b or c, respectively.
Since by default MATLAB considers x to be the only symbolic variable, to solve the equation in x we don’t need to declare x as symbolic. We simply use the command solve as follows:
>> solve('a*x^2+b*x+c=0')
ans =
[1/2/a*(-b+(b^2-4*a*c)^(1/2))]
[1/2/a*(-b-(b^2-4*a*c)^(1/2))]
But to solve the equation with respect to the variables a, b or c respectively, it is necessary to first specify them as symbolic variables:
>> syms a
>> solve('a*x^2+b*x+c=0',a)
ans =
-(b*x+c)/x^2
>> syms b
>> solve('a*x^2+b*x+c=0',b)
ans =
-(a*x^2+c)/x
>> syms c
>> solve('a*x^2+b*x+c=0',c)
ans =
-a * x ^ 2-b * x
EXERCISE 1-4
Find the roots of the polynomial x4 - 8x2 + 16 = 0 obtaining the result to default accuracy, to 20 significant figures and with double-precision. Also generate the vector of coefficients associated with the polynomial.
>> p = solve('x^4-8*x^2-16=0')
p =
[ 2*(2^(1/2)+1)^(1/2)]
[-2*(2^(1/2)+1)^(1/2)]
[ 2*(1-2^(1/2))^(1/2)]
[-2*(1-2^(1/2))^(1/2)]
>> vpa(p)
ans =
[ 3.1075479480600746146883179061262]
[ -3.1075479480600746146883179061262]
[ 1.2871885058111652494708868748364*i]
[ -1.2871885058111652494708868748364*i]
>> numeric(p)
ans =
3.1075
-3.1075
0 + 1.2872i
0 - 1.2872i
>> vpa(p,20)
ans =
[ 3.1075479480600746146]
[ -3.1075479480600746146]
[ 1.2871885058111652495*i]
[-1.2871885058111652495*i]
>> syms x
>> sym2poly(x^4-8*x^2-16)
ans =
1 0 -8 0 -16
EXERCISE 1-5
Find the numerical value to default precision of the abscissa of the intersection point in the first quadrant of the curves y = sin(x) and y = cos(x). Find the symbolic solution. Find the abscissa to 12 significant figures.
>> p = numeric(solve ('sin(x) = cos(x)'))
p =
0.7854
>> q = sym(p)
q =
PI/4
>> digits(12);r = numeric(solve('sin(x)=cos(x)'))
r =
.785398163398
EXERCISE 1-6
Simplify the following expressions as much as possible:
1 / 2m - 1 / 3m + 1 / 4 m + 1 / 5m + 1 / 6m
1/2 - 1/3 + 1/4 + 1/5 + 1/6
>> syms m
>> simplify(1/(2*m) - 1/(3*m) + 1/(4*m) + 1/(5*m) + 1/(6*m))
ans =
47/60m
>> pretty(simplify(1/(2*m) - 1/(3*m) + 1/(4*m) + 1/(5*m) + 1/(6*m)))
47
---
60m
>> sym(1/2 - 1/3 + 1/4 + 1/5 + 1/6)
ans =
47/60
1.4 Vector Variables
A variable that represents a vector of length n can be defined in MATLAB in the following ways:
variable = [e1, e2, e3,..., en]
variable = [e1 e2 e3... en]
Therefore, to define a vector variable, simply insert the vector elements between brackets separated by commas or blank spaces.
When you apply most MATLAB commands and functions to a vector variable, the result obtained is that found by applying the command or function to each element of the vector:
>> vector1 = [1,3,5,2.3,1/2]
vector1 =
1.0000 3.0000 5.0000 2.3000 0.5000
>> sin(vector1)
ans =
0.8415 0.1411 - 0.9589 0.7457 0.4794
>> exp(vector1)
ans =
2.7183 20.0855 148.4132 9.9742 1.6487
>> log(vector1)
ans =
0 1.0986 1.6094 0.8329 - 0.6931
There are different ways of defining a vector variable without explicitly bracketing all its elements, separated by commas or blank spaces.
Here are some examples:
>> vector2 = [0:5:20]
vector2 =
0 5 10 15 20
We have obtained the numbers between 0 and 20 separated by 5 units.
>> vector3 = [0:20]
vector3 =
Columns 1 through 12
0 1 2 3 4 5 6 7 8 9 10 11
Columns 13 through 21
12 13 14 15 16 17 18 19 20
We have obtained the numbers between 0 and 20 separated by units.
>> vector4 = linspace(0,10,11)
Vector4 =
0 1 2 3 4 5 6 7 8 9 10
We have obtained the numbers between 0 and 10 separated by units.
>> vector5 = linspace (0,20,6)
vector5 =
0 4 8 12 16 20
We have obtained 6 equally spaced numbers between 0 and 20.
>> vector6 = logspace (0,2,6)
vector6 =
1.0000 2.5119 6.3096 15.8489 39.8107 100.0000
We have obtained 6 evenly logarithmically spaced numbers between 100 and 102.
We can also consider row 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 apostrophe at the end of its definition.
>> a = [1;2;3;4]
a =
1
2
3
4
>> a = [1:4];b=a'
b =
1
2
3
4
>> c = (a')'
c =
1 2 3 4
You can also select an element of a vector or a subset of elements.
Here are some examples:
>> x = (1:10)
x =
1 2 3 4 5 6 7 8 9 10
>> x(6)
ans =
6
We have obtained the sixth element of the vector x.
>> x(4:7)
ans =
4 5 6 7
We have obtained the elements of the vector x located between the fourth and the seventh elements, both inclusive.
>> x(2:3:9)
ans =
2 5 8
We have obtained the elements of the vector x located between the second and ninth elements, both inclusive, but separated from each other by three units.
>> x(9:-3:2)
ans =
9 6 3
We have obtained the elements of the vector x located between the ninth and second elements, both inclusive, but separated from each other by three units and starting at the ninth.
Simple mathematical operations between scalars and vectors scale each element of the vector according to the defined operation, and simple operations between vectors are performed elementwise.
Below is a summary of these operations:
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 is followed by a point.
On the other hand, you can also set the vector variables to be symbolic using the command syms.
>> syms t
>> A=sym([sin(t),cos(t)])
A =
[sin (t), cos (t)]
EXERCISE 1-7
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
1.5 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 = [a11 a12 a13; a21 a22 a23; a31 a32 a33]
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 columns, 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
EXERCISE 1-8
Given the square matrix of order 3 whose entries are the first nine natural numbers, find its inverse, its transpose and its diagonal. Transform it into a lower triangular matrix and an upper triangular matrix and rotate it by 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 is formed by the elements at 11 and 22 and also remove the subarray whose diagonal elements are at 11 and 33.
>> M = [1,2,3;4,5,6;7,8,9]
M =
1 2 3
4 5 6
7 8 9
>> A = inv(M)
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 2.937385e-018
A =
1.0e + 016 *
0.3152 - 0.6304 0.3152
-0.6304 1.2609 - 0.6304
0.3152 - 0.6304 0.3152
>> B = M'
B =
1 4 7
2 5 8
3 6 9
>> V = diag(M)
V =
1
5
9
>> TI = tril(M)
TI =
1 0 0
4 5 0
7 8 9
>> TS = triu(M)
TS =
1 2 3
0 5 6
0 0 9
>> TR = rot90(M)
TR =
3 6 9
2 5 8
1 4 7
>> s = M(1,1)+M(1,2)+M(1,3)
s =
6
>> sd = M(1,1)+M(2,2)+M(3,3)
sd =
15
>> SM = M(1:2,1:2)
SM =
1 2
4 5
>> SM1 = M([1 3],[1 3])
SM1 =
1 3
7 9
The most important matrix operations are summarized below:
Here are some examples:
>> A = [1, 3, 5; pi exp(pi) sin(1); i 2 * i 1 + i]
A =
1.0000 3.0000 5.0000
3.1416 2.7183 0.0000
1.0000i 2.0000i 1.0000 + 1.0000i
We have defined a complex matrix. Next we will calculate its inverse, its square and its square root:
>> B = inv(A)
B =
0.0711 - 0.2874i 0.5810 - 0.0806i 0.5407 + 0.8963i
-0.0822 + 0.3322i -0.3036 + 0.0932i -0.6249 – 1.0359i
0.2351 - 0.1418i 0.0659 - 0.0398i 0.2668 + 0.4423i
>> C = A^2
C =
10.425 + 5i 72.422 + 10i 12.524 + 5i
75.84 + 0.84147i 544.92 + 1.6829i 36.022 + 0.84147i
-1 + 8.2832i -2 + 51.281i 0 + 8.6829i
>> A ^ (1/2)
ans =
0.7181 + 0.3784i 0.6691 - 0.6583i 2.0360 - 1.1395i
1.2547 - 0.3193i 1.6690 + 0.3804i -0.5550 + 0.8311i
-0.1046 + 0.1852i 0.1152 + 0.5870i 1.2790 + 0.2869i
Now we check that the product of the matrix A with its inverse is the identity matrix of order 3:
>> A*B
ans =
1.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i
0.0000 + 0.0000i 1.0000 + 0.0000i 0.0000 + 0.0000i
0.0000 + 0.0000i 0.0000 + 0.0000i 1.0000 + 0.0000i
Now we find the exponential of A with bases 2 and - 2:
>> 2^A
ans =
1.0e+07 *
0.0218 + 0.0057i 0.1569 + 0.0384i 0.0106 + 0.0031i
0.1673 + 0.0176i 1.2036 + 0.1080i 0.0816 + 0.0110i
-0.0024 + 0.0157i -0.0156 + 0.1131i -0.0014 + 0.0076i
>> (-2)^A
ans =
1.0e+06 *
0.0585 - 0.1313i 0.4059 - 0.9492i 0.0305 - 0.0634i
0.2852 - 1.0365i 1.9345 - 7.4766i 0.1545 - 0.5029i
0.0965 + 0.0316i 0.6969 + 0.2161i 0.0468 + 0.0168i
So far, we have always worked with numeric matrices. To work with symbolic matrices, we simply define the variables to be symbolic using the command syms.
>> syms t
>> A=sym([sin(t),cos(t);tan(t),exp(t)])
A =
[sin (t), cos (t)]
[tan (t), exp (t)]
>> b = inv (A)
b =
[-exp (t) / (-sin (t) * exp (t) + cos (t) * tan (t)), cos (t) / (-sin (t) * exp (t) + cos (t) * tan (t))]
[tan (t) / (-sin (t) * exp (t) + cos (t) * tan (t)), - sin (t) / (-sin (t) * exp (t) + cos (t) * tan (t))]
1.6 Character Variables
MATLAB is a powerful numerical calculation program, but it is also a versatile character variable (i.e. text) manipulator. A character variable (or chain) is simply a string of characters contained within single quotes that MATLAB interprets as a vector form. For example:
>> c = 'string'
c =
character string
We have thus defined the character variable c. 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 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:
>> eval('4 * atan (1)')
ans =
3.1416
This shows how MATLAB numerically evaluates the contents of a string (according to the program’s standard interpretation of the syntax).
>> hex2dec('3ffe56e')
ans =
67102062
MATLAB has converted a hexadecimal string to a decimal string.
>> dec2hex(1345679001)
ans =
50356E99
The program has converted a decimal string to 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 a string (to default precision).
>> sscanf('121.00012', '%f')
ans =
121.0001
A numeric string has been passed to exact numerical format (with default precision). Later we will see which alternative formats are possible.
>> num2str(pi)
ans =
3.142
The exact number π has been approximated to default precision and converted to a string.
>> str2num('15/14')
ans =
1.0714
A string representing a rational number has been approximated to default precision and converted to a string.
>> setstr(32:126)
ans =
!"#$% &' () * +, -. / 0123456789:; < = >? @ABCDEFGHIJKLMNOPQRSTUVWXYZ [] ^ _'abcdefghijklmnopqrstuvwxyz {|}~
The ASCII characters associated with whole numbers between 32 and 126 have been generated.
>> abs('{]}><#¡¿?°a')
ans =
123 93 125 62 60 35 161 191 63 186 170
The integers corresponding to the given ASCII characters have been generated.
>> lower('ABCDefgHIJ')
ans =
abcdefghij
The given string has been converted to lowercase text.
>> upper('abcd eFGHi jKlMn')
ans =
ABCD EFGHI JKLMN
The given string has been converted to uppercase text.
>> str2mat(' The world ',' The country ',' Daily 16 ', ' ABC ')
ans =
The world
The country
Daily 16
ABC
The chains given as arguments of the command str2mat have been converted into rows of an array.
>> disp('This text will appear on the screen')
This text will appear on the screen
The argument of the command disp is displayed on screen.
>> c = 'this is a good example';
>> strrep(c, 'good', 'bad')
ans =
this is a bad example
The string good has been replaced by the string bad in the string c.
>> findstr(c, 'is')
ans =
3 6
The positions of the first character of the string is in c are given.
1.7 Operators
MATLAB features arithmetic, logical, relational, conditional and structural operators.
1.7.1 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. We have already seen these operations earlier.
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 (Mp) |
.^ | Power of vectors (A. ^ B = [A(i,j)B (i, j)], for vectors A and B) |
EXERCISE 1-9
Where X = [1 2 3] and Y = [4 5 6], calculate X + Y, X-Y, X * Y, X'* Y, X * Y', X.*Y, X.' * Y, X.*Y', 2 * X, 2.*X, X/Y, YX, X. / Y, YX, 2/X, 2. / X, 2Y, 2. Y, X ^ Y, X. ^ Y, X ^ 2, X^ 2, 2 ^ X and 2. ^ X.
>> X = [1,2,3]; Y = [4,5,6]; 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 =
5 7 9
b =
-3 -3 -3
c =
4 10 18
d =
2 4 6
e =
2.0000 1.0000 0.6667
f =
2.0000 2.5000 3,0000
g =
0.2500 0.4000 0.5000
h =
0.2500 0.4000 0.5000
i =
1 4 9
j =
2 4 8
k =
1 32 729
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.
>> X = [1,2,3]; Y = [4,5,6]; l = X'* Y, m = X * Y ', n = 2 * X, o = X / Y, p = YX
l =
4 5 6
8 10 12
12 15 18
m =
32
n =
2 4 6
o =
0.4156
p =
0 0 0
0 0 0
0.1667 0.3333 0.5000
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.
1.7.2 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 one if the corresponding relationship is true, or zero 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) |
Here are some examples:
>> X = 5 * ones (3,3); X > = [1 2 3; 4 5 6; 7 8 9]
ans =
1 1 1
1 1 0
0 0 0
The elements of the array X which are greater than or equal to the corresponding element of the matrix [1 2 3; 4 5 6; 7 8 9] are given the value 1 in the response matrix. The rest of the elements are assigned the value 0 (the result of the operation would have been the same if we had compared the scalar 5 to the matrix [1 2 3; 4 5 6; 7 8 9] using the expression X = 5; X > = [1 2 3; 4 5 6; 7 8 9]).
Next we see another example that combines an arithmetic operation with a relational operation:
>> A = 1:9, B = 9-A, Y = A > 4, Z = B-(A>2)
A =
1 2 3 4 5 6 7 8 9
B =
8 7 6 5 4 3 2 1 0
Y =
0 0 0 0 1 1 1 1 1
Z =
8 7 5 4 3 2 1 0 -1
The values of Y equal to 1 correspond to elements of A larger than 4. The Z values result from subtracting 1 from the corresponding elements of B if the corresponding element of A is greater than 2, or 0 if the corresponding element of A is less than or equal to 2.
1.7.3 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 = 1:9; P = (A>2) &(A<6)
P =
0 0 1 1 1 0 0 0 0
Returns 1 when A is greater than 2 and less than 6, and returns 0 otherwise.
>> A = [1 1 2 2 3 4 5 6 7 8 9],P = (A>=1)&(A<6),xor(A,P)
A =
1 1 2 2 3 4 5 6 7 8 9
P =
1 1 1 1 1 1 1 0 0 0 0
ans =
0 0 0 0 0 0 0 1 1 1 1
Returns 1 when A or P, but not both, have the value 1.
1.8 Logic 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. |
Here are some examples:
>> isinf([pi NaN Inf - Inf])
ans =
0 0 1 1
>> any([pi NaN Inf -Inf])
ans =
1
>> ismember([1,2,3,5],[8,12,1,3,56,5])
ans =
1 0 1 1
>> A = [2,0,1]; B = [4,0,2];
>> isequal(2*A,B)
ans =
1
>> V = [-10,5,3,12,0];
>> isprime(V)
ans =
0 1 1 0 0
>> isnumeric(V)
ans =
1
>> all(V)
ans =
0
>> any(V)
ans =
1
>> C = [0 2 3; 0 1 2;0 4 6],D = [0 0 0 0;4 3 1 2;6 0 0 4]
>> any(C),all(C),any(D),all(D)
ans =
0 1 1
ans =
0 1 1
ans =
1 1 1 1
ans =
0 0 0 0
1.9 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 = [1 2 3; 4 5 6;7 8 9]
A =
1 2 3
4 5 6
7 8 9
>> sin(A)
ans =
0.8415 0.9093 0.1411
-0.7568 -0.9589 -0.2794
0.6570 0.9894 0.4121
>> B = [1+i 2+i;3+i,4+i]
B =
1.0000 + 1.0000i 2.0000 + 1.0000i
3.0000 + 1.0000i 4.0000 + 1.0000i
>> sin(B)
ans =
1.2985 + 0.6350i 1.4031 - 0.4891i
0.2178 - 1.1634i -1.1678 - 0.7682i
>> exp(A)
ans =
1.0e + 003 *
0.0027 0.0074 0.0201
0.0546 0.1484 0.4034
1.0966 2.9810 8.1031
>> exp(B)
ans =
1.4687 + 2.2874i 3.9923 + 6.2177i
10.8523 +16.9014i 29.4995 +45.9428i
>> log(B)
ans =
0.3466 + 0.7854i 0.8047 + 0.4636i
1.1513 + 0.3218i 1.4166 + 0.2450i
>> sqrt(B)
ans =
1.0987 + 0.4551i 1.4553 + 0.3436i
1.7553 + 0.2848i 2.0153 + 0.2481i
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)
ans =
1.0e+002 *
-0.3071 + 0.4625i -0.3583 + 0.6939i
-0.3629 + 1.0431i -0.3207 + 1.5102i
>> logm(A)
ans =
-5.6588 + 2.7896i 12.5041 - 0.4325i -5.6325 - 0.5129i
12.8139 - 0.7970i -23.3307 + 2.1623i 13.1237 - 1.1616i
-5.0129 - 1.2421i 13.4334 - 1.5262i -4.4196 + 1.3313i
>> abs(B)
ans =
1.4142 2.2361
3.1623 4.1231
>> imag(B)
ans =
1 1
1 1
>> fix(sin(B))
ans =
1.0000 1.0000
0 - 1.0000i -1.0000
>> ceil(log(A))
ans =
0 1 2
2 2 2
2 3 3
>> sign(B)
ans =
0.7071 + 0.7071i 0.8944 + 0.4472i
0.9487 + 0.3162i 0.9701 + 0.2425i
>> rem(A,3*ones(3))
ans =
1 2 0
1 2 0
1 2 0
>> funm(B,'sinh')
ans =
-15.8616 +23.2384i -17.6536 +34.7072i
-17.7736 +52.1208i -16.2216 +75.4791i
The result of the last function is equivalent to sinh(B), but the algorithm used is different.
1.10 Elementary Functions that Support 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 - Vt-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 = 1:5, W = [1-i 2i 2 + 3i]
V =
1 2 3 4 5
W =
1.0000 - 1.0000i 0 + 2.0000i 2.0000 + 3.0000i
>> diff(V)
ans =
1 1 1 1
>> diff(W)
ans =
-1.0000 + 3.0000i 2.0000 + 1.0000i
>> cumprod(V)
ans =
1 2 6 24 120
>> cumsum(W)
ans =
1.0000 - 1.0000i 1.0000 + 1.0000i 3.0000 + 4.0000i
>> mean(W)
ans =
1.0000 + 1.3333i
>> std(V)
ans =
1.5811
>> sort(W)
ans =
1.0000 - 1.0000i 0 + 2.0000i 2.0000 + 3.0000i
>> sum(W)
ans =
3.0000 + 4.0000i
>> prod(V)
ans =
120
>> gradient(W)
ans =
-1.0000 + 3.0000i 0.5000 + 2.0000i 2.0000 + 1.0000i
>> del2(W)
ans =
0 1.5000 - 1.0000i 0
>> fft(W)
ans =
3.0000 + 4.0000i -0.8660 - 1.7679i 0.8660 - 5.2321i
>> ifft(W)
ans =
1.0000 + 1.3333i 0.2887 - 1.7440i -0.2887 - 0.5893i
>> fft2(W)
ans =
3.0000 + 4.0000i - 0.8660 - 1.7679i 0.8660 - 5.2321i
1.11 Vector Functions of Several Variables
Functions of one or several variables are defined via the command maple as follows:
To find the value of the function (x, y, z) - > f(x,y,z…) at the point (a, b, c,…) the expression maple ('f(a,b,c,…)') is used.
We find the value of the vector function f:=(x,y,..)-> (f1(x,y,..), f2(x,y,..),…) at the point (a, b,…) by using the expression maple ('f(a,b,..)').
The function f(x,y) = 2x + y is defined in the following way:
>> maple('f:=(x,y) - > 2 * x + y '),
f(2,3) and f(a,b) are calculated as follows:
>> maple('f(2,3)')
ans =
7
>> maple('f(a,b)')
ans =
2 * a + b
EXERCISE 1-10
Given the function h defined by: h(x,y) = (cos(x2-y2), sin(x2-y2)), calculate h (1,2), h(-Pi,Pi) and h (cos (a2), cos (1 -a2)).
As h is a vector function of two variables, we use the command maple:
>> maple ('h:=(x,y) - > (cos(x^2-y^2), sin(x^2-y^2))'),
>> maple ('A = h (1, 2), B = h(-pi,pi), C = h (cos(a^2), cos(1-a^2))')
ans =
A = (cos (3),-sin(3)), B = (1, 0),
C = (cos (cos(a^2) ^ 2-cos(-1+a^2) ^ 2), sin(cos(a^2) ^ 2-cos(-1+a^2) ^ 2))
1.11.1 Functions of One Variable
Functions of one variable are a special case of functions of several variables, but they can also be defined in MATLAB via the command f = 'function'.
To find the value of the function f at a point, you use the command subs, whose syntax is as follows:
Let's see how to define the function f (x) = x ^ 2 :
>> f = 'x ^ 2'
f =
x ^ 2
Now we calculate the values f (4), f (a+1) and f(3x+x^2):
>> syms a x
>> A = subs(f,4),B = subs(f,a+1),C = subs(f,3*x+x^2)
A =
16
B =
(a+1) ^ 2
C =
(3 * x + x ^ 2) ^ 2
It should also be borne in mind that if we use the command maple, the special constants π , e, i, and ∞ are defined as maple('Pi'), maple ('exp (1)'), maple('i') and maple('infinity') respectively.
EXERCISE 1-11
Define the functions f (x) = x2, g(x) = x1/2 and h(x) = x + sin (x). Calculate f(2), g(4) and h(a-b2).
>> f = 'x ^ 2'; g = 'x ^(1/2)'; h = 'x+sin (x)';
>> syms a b
>> a = subs(f,2),b = subs(g,4),c = subs(h,'a-b^2')
a =
4
b =
4^(1/2)
c =
a-b ^ 2 + sin(a-b^2)
We could also have done the following:
>> maple('f:=x->x^2: g:=x->sqrt(x):h:=x->x+sin(x)'),
>> maple('f(2),g(4),h(a-b^2)')
ans =
4, 2, a-b ^ 2 + sin(a-b^2)