Numerical Variables, Vectors and Matrices
4.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.
4.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, determine 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 4-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 4-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.
4.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 4-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 4-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 4-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 4-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
4.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 4-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
4.5 Matrix Variables
MATLAB defines matrices 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 a matrix of general 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 list summarizes different ways to define matrix variables.
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 4-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))]
4.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:
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('{]}><#¡¿?°ª')
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.
4.7 Operators
MATLAB features arithmetic, logical, relational, conditional and structural operators.
4.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, which we have already seen, are summarized below.
EXERCISE 4-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.
4.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 summary of these operators.
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.
4.7.3 Logical Operators
MATLAB provides symbols to denote logical operators. The logical operators shown below offer a way to combine or negate relational expressions.
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.
4.8 Logic Functions
MATLAB implements logical functions whose output can take the value true (1) or false (0). The following list summarizes the most important logical functions.
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
4.9 Elementary Functions that Support Complex Matrix Arguments
• Trigonometric | |
sin (z) |
sine function |
sinh (z) |
hyperbolic sine function |
asin (z) |
arc sine function |
asinh (z) |
hyperbolic arc sine function |
cos (z) |
cosine function |
cosh (z) |
hyperbolic cosine function |
acos (z) |
arc cosine function |
acosh (z) |
hyperbolic arc cosine function |
tan (z) |
tangent function |
tanh (z) |
hyperbolic tangent function |
atan (z) |
arc tangent function |
atan2 (z) |
arc tangent function in the fourth quadrant |
atanh (z) |
hyperbolic arc tangent function |
sec (z) |
secant function |
sech (z) |
hyperbolic secant function |
asec (z) |
arc secant function |
asech (z) |
hyperbolic arc secant function |
csc (z) |
cosecant function |
csch (z) |
hyperbolic cosecant function |
acsc (z) |
arc cosecant function |
acsch (z) |
hyperbolic arc cosecant function |
cot (z) |
cotangent function |
coth (z) |
hyperbolic cotangent function |
acot (z) |
arc cotangent function |
acoth (z) |
hyperbolic arc cotangent function |
• Exponential | |
exp (z) |
base e exponential function |
log (z) |
Naperian logarithm |
log10 (z) |
base 10 logarithm |
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 decimal part |
floor (z) |
rounds decimals to the nearest lower integer |
ceil (z) |
round decimals to the nearest greater integer |
round (z) |
performs the common rounding of decimal |
rem (z1, z2) |
remainder of the division of z1 by z2 |
sign (z) |
sign function |
• 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) |
matrix logarithm |
sqrtm (Z) |
matrix square root |
funm(Z, ‘function’) |
applies the function to the matrix 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.
4.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
4.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 4-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))
4.12 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 4-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)