M02 - Programming in Matlab - XXXX - CH02
M02 - Programming in Matlab - XXXX - CH02
Matrix
Operations and Applications
2.1 Introduction
The concept of arrays and matrices is important in solving problems of variegated nature. This
concept is important in solving algebraic and differential equations, sorting, statistical opera-
tions, plotting, and various other applications. MATLAB is extremely efficient in representing
and manipulating arrays and matrices, as the name MATLAB (Matrix Laboratory) suggests. In
MATLAB, the same operators that are used in normal arithmetic can also be used with arrays
and matrices. There is no need for special looping constructs to operate on individual elements
one by one. For example, the operation A/B is valid, if A and B are two numbers or two matrices
of compatible size. This facility makes your program lucid and compact. MATLAB allows you
to operate with arrays, matrices, scalars, and complex numbers in a similar manner without
much distinction in the operating rules. However, you must be cautious to avoid confusion and
serious bugs that may be difficult to recognize. In this chapter, you will learn about matrix con-
cepts, creation of matrices in many possible ways, and matrix operations.
1.23e5 is equal to 1.23 × 105 = 123,000 and similarly, 15.6e−3 is equal to 15.6 × 10−3 =
0.0156.
3. Complex numbers: They are represented by special complex operators i and j. You can use
either i or j to represent the imaginary part. The number 3 + 4i can be specified in MATLAB
in either of the following ways:
>> a = 3 + 4 * i
or
>> a = 3 + 4 * j
or
>> a = 3 + 4i
4. Constants: There are several pre-defined constants in MATLAB. Some of the important
ones are shown in Table 2.1:
5. Text strings: These are arrays of characters specified by enclosing the characters within
single quotes. 'Hello' and 'Plot Number 1' are examples of text strings.
6. Vectors: Vectors of integers, floating point numbers, and complex numbers or characters
are specified by listing the elements of the vector within square brackets. The elements are
separated by blank spaces or commas. The vectors are by default row vectors. For example,
A = [10 2.1 3.69 1] is a vector of dimension 1 × 4 containing the elements 10, 2.1,
3.69, and 1.
7. Matrices: These are specified just like vectors where each vector represents one row. The
rows are separated by a semicolon (;) or an ENTER key. For example:
>> A = [10 17.1 13; 11.99 15.2 33; 66 34.3 55.6]
A =
10 17.1 13
11.9 15.2 33
66 34.3 455.6
8. Boolean: Boolean variables are used in decision-making. Boolean means a set of only two
possible values or outcomes such as TRUE and FALSE. In MATLAB, zero represents
FALSE and any non-zero integer represents TRUE. The variable c is a Boolean as follows:
>> c = 9 > 4
c =
1
9. Arrays: MATLAB works with a single object type, the MATLAB array. All MATLAB vari-
ables, including scalars, vectors, matrices, and strings, are stored as MATLAB arrays. A
matrix or a vector can be treated as an array depending on the context.
10. Cells and structures: These are special data types to store elements that may not be of simi-
lar type and size. They are discussed in Chapter 11 (Advanced Concepts in MATLAB).
In case of a matrix, the first element indicates the row, while the second element indicates the
column. Thus, B(1, 3) denotes the element corresponding to row 1 and column 3. You can also
retrieve individual characters from a string array as shown in the following example:
>> C(1) % C stores the string 'Sitaram'
ans =
S
The length of a vector can be determined by the length command, whereas the order of a
matrix is determined using the size command. Consider the previous example again:
>> A = [1,2,3,4,5]
A =
1 2 3 4 5
>> length(A) % gives the length (i.e., number of
% elements) of the vector A
ans =
5
>> B = [1,4,7;2,5,8;3,6,9]
B =
1 4 7
2 5 8
3 6 9
>> size(B) % gives the order of the given matrix
ans =
3 3
The length and size commands are useful when you wish to compute a function over
all or selected elements in a vector or matrix. Consider the example of finding out the sum
of all the elements in a vector by running a loop from the beginning to the end of the vector.
These commands are also useful in determining whether some matrix operation is allowed.
For example, before multiplying matrices A and B, you can use the size command to check
if their dimensions match for performing matrix multiplication. You can also use the length
command to access a particular element as shown in the following example:
>> C = 'Sitaram'
C =
Sitaram
>> length(C)
ans =
7
>> C(length(C)-2)
% This is equivalent to writing >> c(7-2)
ans =
r
You can also access the last element in a vector using the end keyword as shown in the follow-
ing example:
>> C(end) % Access the last element
ans =
m
MATLAB automatically interprets the keyword end as the last element of a particular vector.
In other words, end = length(C) in relation to the above example.
Sometimes, the number of vector elements could be large. In such cases, the elements might
overflow to the next line. You can use the three continuous dots (…) to break the array in
several lines. Consider the following example showing the creation of a vector B with 12
elements:
>> B =[1 2 3 4 ...
5 6 7 8 ...
9 10 11 12]
B =
1 2 3 4 5 6 7 8 9 10 11 12
Another important way of creating a vector is to use the colon notation (:). This is especially
useful if the vector elements are to be uniformly spaced. The general format to create a vector
V is as follows:
V = s:d:f
The vector V contains elements [s s + d s + 2 × d s + 3 × d … s + k × d], where k is chosen
such that s + k × d is less than or equal to f. The following example illustrates the use of colon
operator:
>> 1:2:10
ans =
1 3 5 7 9
>> X = 2*pi:-pi/2:-2*pi
X =
Columns 1 through 7
6.2832 4.7124 3.1416 1.5708 0 -1.5708 -3.1416
Columns 8 through 9
-4.7124 -6.2832
When the increment/decrement step d is omitted, MATLAB assumes d = 1. Following are some
more examples of using the colon operator to generate vectors:
>> 1:10
ans =
1 2 3 4 5 6 7 8 9 10
>> Y = -pi: pi
Y = -3.1416 -2.1416 -1.1416 -0.1416 0.8584 1.8584 2.8584
Another important way of creating uniformly separated elements in a vector is by using the
linspace command. The command linspace(x1, x2, n) generates n points between
two numbers x1 and x2. For n < 2, linspace returns x2.
If n equally spaced values on a logarithmic scale are desired, then you can use:
y = logspace(x1,x2,n)
In this case, the first element of the resultant array "y", is 10x1, the last element is 10x2, and the
total number of elements is n. Following are two examples of vector creation using linspace
and logspace commands:
>> p = linspace(100, 20, 9)
p =
100 90 80 70 60 50 40 30 20
>> q = logspace(1, 5, 5)
q =
10 100 1000 10000 100000
A simple way to create matrices is to separate each element in a row either by a blank space
or by a comma (,). The rows are separated either by a semicolon (;) or by the ENTER key. The
following example illustrates this method of creating matrices:
>>B = [1 2 3 4; 5 6 7 8; 9 10 11 12]
B =
1 2 3 4
5 6 7 8
9 10 11 12
>> B = [ 1 2 3 4
5 6 7 8
9 10 11 12]
B =
1 2 3 4
5 6 7 8
9 10 11 12
A =
1 3 5
2 4 6
11 9 7
3 4 5
Following are some of the different ways of creating and accessing parts of the matrix A:
A(i, j) returns the (i, j) entry of the matrix A. In other words, the output would be a scalar
number corresponding to the entry at ith row and jth column. Observe the following examples:
>> A(3, 1) % (third row, first column) entry
ans =
11
>> A(2, 3)
ans =
6
>> A(2, 4)
??? Index exceeds matrix dimensions.
A(2, 4) results in an error because the matrix A has only three columns.
A(i, :) returns the ith row of A. The output is a row vector as shown in the following example :
>> A(2,:)
ans =
2 4 6
A(:, j) returns the jth column of A. The output is a column vector as shown in the following example:
>> A(:,3)
ans =
5
6
7
5
A(2 : 4, 1 : 2) returns rows 2 to 4 and columns 1 to 2. Thus, a 3 × 2 matrix is returned as follows:
>> A(2 : 4, 1 : 2)
ans =
2 4
11 9
3 4
You can also access rows 2 to 4 with all the columns by A(2 : 4, :) as follows:
>> A(2:4,:)
ans =
2 4 6
11 9 7
3 4 5
A([2 4], :) returns rows 2 and 4 and all columns. The output is a 2 × 3 matrix as follows:
>> A([2 4], :)
ans =
2 4 6
3 4 5
You can change certain elements in matrix A without modifying the values of other elements.
The following example illustrates how you can change one entry at a time:
>> A(3, 2) = 7 % resets the (3, 2) entry to 7
A =
9.0000 1.0000 7.0000
2.5000 7.5000 12.0000
5.0000 7.0000 11.0000
Since there is a change in matrix A, the next operation is performed over this changed matrix.
The following example shows how you can change a row or a column:
This assignment results in an error because of dimension mismatch. Since A(:,1) is a column
vector of length 3, it can only be assigned a vector of length 3.
You can also delete rows and columns by using colon operator and an empty pair of square
brackets. Consider the following example where the first row of A is deleted:
>> A(1,:)=[ ] % this expression implies that the
% first row is eliminated.
A =
2.5000 1.0000 12.0000
7.0000 7.0000 9.0000
Example 2.1
Example 2.1:
Given an array A, the task is to exchange the second and third rows of
Exchanging
the rows of a the array.
matrix
Solution
>> A = [9 1 7; 2.5 7.5 12; 5 6.2 11];
>> A([2 3], :) = A([3 2], :)
% exchanges rows 2 and 3 of A
A =
9.0000 1.0000 7.0000
5.0000 6.2000 11.0000
2.5000 7.5000 12.0000
A(2, :) represents an array consisting of all the elements of matrix A in the second row and
A(3, :) represents an array consisting of all the elements of matrix A in the third row. Similarly,
the expression A([2 3], :) represents an augmented array consisting of elements of both
A(2, :) and A(3, :). Thus, in the expression given in Example 2.1, the second and third rows
of the modified matrix A get the values of the third and second rows of the original matrix A,
respectively.
some particular value. Let us say you want to create a matrix with all of its elements initialized
to the value 3. This can be done using the ones command as follows:
>> A = 3 * ones(2,4) % Creates a 2 × 4 matrix
A =
3 3 3 3
3 3 3 3
>> A = 3 * ones(3) % Creates a 3 × 3 matrix
A =
3 3 3
3 3 3
3 3 3
The command ones(m, n) creates a matrix of size m × n with m rows and n columns with
all its elements as 1. However, ones(n)are equivalent to ones(n, n), that is, the same
number of rows and columns are assumed thereby generating a square matrix.
Similarly, you can create a matrix with all of its elements initialized to zero with another
special function zeros:
>> B = zeros(3)
B =
0 0 0
0 0 0
0 0 0
You can create a diagonal matrix with the given elements by using the diag command as follows:
>> d = [1 3 5 7], A = diag(d)
d =
1 3 5 7
A =
1 0 0 0
0 3 0 0
0 0 5 0
0 0 0 7
Many times, special matrices are required for testing your functions. One command that is
frequently used in such cases is magic. The magic function creates a square matrix in which
the sum of elements in all columns and rows and the two diagonals are equal. Consider the fol-
lowing example:
2.4.4 Concatenation
Larger matrices can be formed by concatenating smaller matrices. The pair of square brackets,
[ ], is also known as the concatenation operator. The basic idea behind concatenation is that two
matrices A and B can be concatenated as [A B] to form a larger matrix C, provided the dimen-
sions of A and B match the concatenation (in this case, the number of rows should be same
for both A and B). If matrices A and B have n and m numbers of columns, respectively, then C
would have n + m number of columns. The number of rows in A, B, and C should be equal. The
following example illustrates how concatenation works:
V =
-5 2 3 4 5 6 7 10
The vector V is formed by concatenating element –5, vector 2:7, and element 10. You can do the
same with matrices as follows:
>> A = eye(2) % A is a matrix
A =
1 0
0 1
>> B = 2 * ones(2) % B is a matrix
B =
2 2
2 2
>> C = [A B] % creates the augmented matrix
C =
1 0 2 2
0 1 2 2
You can also place a matrix B below another matrix A by using C = [A; B]. This is like an exten-
sion of the semicolon (;) notation, indicating a new set of rows in the formation of a matrix.
The new matrix C would have the same number of columns as A and B. The following example
illustrates this form of concatenation:
>> D = [A;B]
D =
1 0
0 1
2 2
2 2
>> E = [A 2*A; ones(2,2)*4 zeros(2,2)]
% a concatenated matrix
E =
1 0 2 0
0 1 0 2
4 4 0 0
4 4 0 0
Example 2.2
What is the output when you execute the following Example 2.2:
command? Forming a matrix by
>> A = [1:2:9; 2:2:10; 11:-2:3; 3:7] concatenation of arrays
Solution
There are four rows in matrix A as three semicolons are used. Each row is a vector, which
is constructed using a colon. Since the length of all four vectors is the same, they can be
concatenated to form the following matrix A:
A =
1 3 5 7 9
2 4 6 8 10
11 9 7 5 3
3 4 5 6 7
Solution
X will contain a vector starting with element –5 and other elements incremented succes-
sively by 2 as follows:
X =
-5 -3 -1 1 3 5
The keyword end in the second command gives the length of X, that is, 6. The vector
2:2:6 is [2 4 6]. X(2) will retrieve the element number 2, that is, −3. Similarly, X([2 4 6])
will retrieve the second, fourth, and sixth elements as a vector. Thus, the output of the
second command is as follows:
>> X(2 : 2 : end)
ans =
-3 1 5
The result is a vector consisting of only even indexed elements of the vector X, that is,
x(2), x(4), and x(6).
Example 2.4
Example 2.4:
What is the output of the following commands?
Adding extra
>> A = [21 22 23;
elements (rows/
columns) to a 31 32 33]
given matrix >> A = [[7 8 9]; A]
Solution
After the first command, matrix A would be created with two rows and three columns
as follows:
A =
21 22 23
31 32 33
After the second command, which performs concatenation on A, the output is as follows:
A =
7 8 9
21 22 23
31 32 33
The new matrix A has vector [7 8 9] in its first row and the previous value of matrix
A in its second row.
2.5 Operators
The operators can be divided into three general categories. They are as follows:
1. Matrix operators and operators used in general algebra
2. Relational operators
3. Logical operators
Symbol Operation
+ Addition
- Subtraction or negation
* Multiplication
^ Power
' Transpose (real) or conjugate transpose (complex)
.' Transpose (real or complex)
\ Left division or inverse division
/ Right division
array A. Similarly, you can multiply all the elements of an array with a scalar or a numerical
expression as follows:
>> A * 4
ans =
4 8 12 16 20 24 36 32 28
>> C = [2 3 4]*(2 + 3^2)
% This will multiply 11 to [2 3 4]
C =
22 33 44
Similar rules hold good for subtraction and division operations of an array with a scalar.
However, when you apply power (^) with matrix A, it implies matrix multiplication as shown
in the following example:
>> A = [1 2; 3 4]
A =
1 2
3 4
>> A^2 % MATLAB interprets A^2 as A * A
ans =
7 10
15 22
The operators can also be applied to vectors and matrices as well. For example, you can add two
vectors of equal length using the "+" operator as follows:
>> A = [1 2 3 4 5 6 9 8 7];
>> B = A + 2
B =
3 4 5 6 7 8 11 10 9
>> C = A + B
C =
4 6 8 10 12 14 20 18 16
Subtraction of vectors of the same length works in exactly the same way:
>> D = [2,3,4]-[1 2 3]
ans =
1 1 1
However, two vectors of unequal size cannot be added, and hence, the following results in an
error:
>> E = [2 3 4] + [1 2]
??? Error using ==> +
Matrix dimensions must agree.
Since the addition or subtraction is an element-by-element operation, the size of the two matri-
ces (or vectors) must necessarily match. In addition, if A is a (m × n) matrix and B is a (n × k)
matrix, multiplication is possible but not addition.
Another useful operator is the transpose operator ( ' ). The transpose of a matrix is a new
matrix produced by writing the entries in each row of the original matrix as entries in the corre-
sponding column of the transpose matrix. An equivalent operation is to write the entries in each
column of the original matrix as entries in the corresponding row of the transpose matrix. Thus,
a column vector becomes a row vector after the transpose operation. The transpose of a matrix
A is A'. Following are some examples that illustrate the functioning of a transpose operator:
>> A = [1;3;5] % creates a column matrix A
A =
1
3
5
>> B = A'
% the ' operator is used to get the row vector
B =
1 3 5
C =
1 2
3 4
5 6
D =
1 3 5
2 4 6
In case of matrices of complex numbers, the transpose operator ' gives the conjugated
transpose. To get the non-conjugated transpose, the .' operator is used. For example:
>> A = [2+3i, 2-3i, 1; 1+i, 1-i, 0]
A =
2.0000 + 3.0000i 2.0000 - 3.0000i 1.0000
1.0000 + 1.0000i 1.0000 - 1.0000i 0
>> A' %gives conjugate transpose
ans =
2.0000 - 3.0000i 1.0000 - 1.0000i
2.0000 + 3.0000i 1.0000 + 1.0000i
1.0000 0
>> A.' % the dot (.) preceding (') makes it
>> B * A
ans =
8 12
8 12
Example 2.5
Consider matrices A and B that are created as follows: Example 2.5:
Using the
>> A = [8 1 6; 3 5 7; 4 9 2]; matrix operators
>> B = inv(A);
What will be the output for the following commands?
(a) >> C = A * B
(b) >> D = C/B
(c) >> E = B\C
Solution
(a) The matrix C is the result of multiplying matrix A with its inverse. Thus, the expected
output for C is an identity matrix as follows :
A =
8 1 6
3 5 7
4 9 2
B =
0.1472 -0.1444 0.0639
-0.0611 0.0222 0.1056
-0.0194 0.1889 -0.1028
>> C = A * B
C =
1.0000 0 -0.0000
-0.0000 1.0000 0
0.0000 0 1.0000
As expected C is an identity matrix. The -0.0000 entries in C appear because of
precision error in computation and they indicate very small values.
(b) The matrix D = C/B in MATLAB means C*inv(B). Since C is identity matrix,
D will be equal to the inverse of B. Note that B is the inverse of A. Therefore, the
inverse of B should be equal to A, since inv(inv(A)) = A. Thus, the output of matrix
A should be as follows:
>> D = C/B % symbol / is right division operator.
D =
8.0000 1.0000 6.0000
3.0000 5.0000 7.0000
4.0000 9.0000 2.0000
E =
8.0000 1.0000 6.0000
3.0000 5.0000 7.0000
4.0000 9.0000 2.0000
In this array operation, X(1) is multiplied with Y(1), X(2) is multiplied with Y(2), and X(3) is
multiplied with Y(3). The result is a vector of the same size as X and Y. It can be easily verified
that element-by-element multiplication is not the same as vector or matrix multiplication. For
example, X and Y cannot be multiplied with the matrix multiplication operator * because their
dimensions do not agree.
>> X * Y
??? Error using ==> *
Inner matrix dimensions must agree.
You can also apply power, left division, and right division operations on arrays as shown here:
Array Power
>> D = X.^Y % Array power
D =
1 32 729
The element D(1) is formed by X(1)^Y(1). Similarly, all the other elements can be computed.
Array Division
>> E = X./Y % Element-by-element division
E =
0.2500 0.4000 0.5000
The element E(1) is formed by X(1)/Y(1). All the other elements can be computed in a similar
manner.
Array Inverse Division
>> F = X.\Y
F =
4.0000 2.5000 2.0000
The element F(1) is formed by Y(1) and divided by X(1). All the other elements can be com-
puted in a similar manner.
You can even divide a scalar by each element of a vector or a matrix as shown here:
>> G = 12./Y
G =
3.0000 2.4000 2.0000
The element G(1) is computed as 12/Y(1). The other elements can be computed in a similar manner.
Example 2.6
Assume matrices E and F have been created as follows:
>> E = [1 2; 3 4];
>> F = [2 3; 4 5]; Example 2.6:
Element-by-
What is the output of the following commands? element opera-
(i) X = E * F; (ii) G = E .* F; tions using the
(iii) H = E^3; (iv) J = E.^3; array operators
(v) K = E./F; (vi) L = E.^F
Solution
1. X = E * F involves normal matrix multiplication as follows:
E =
1 2
3 4
F =
2 3
4 5
>> X = E * F
X =
10 13
22 29
2. G = E .* F involves element-by-element multiplication as follows:
G =
2 6
12 20
3. Since E is a square matrix, you can also multiply it by itself as many times as you
like by raising it to a given power as shown here:
>>H = E^3 % taking E as in previous example
H =
37 54
81 118
Matrix H is equivalent to the resultant matrix obtained by E*E*E
4. J = E.^3 computes the cube of each element in the matrix as follows:
>> J = E.^3
% note the dot operator before power operator(^)
J =
1 8
27 64
Example 2.7
What is the output generated by the following MATLAB Example 2.7:
commands? Element-by-
element opera-
1. X = [1, 2, 3; 4, 5, 6]; Y = exp(X) tions in exponen-
2. X = [-pi:pi/2:pi]; Y = sin(X).^2 + cos(X).^2 tial and trigono-
metric functions
Solution
1. X = [1,2,3;4,5,6] command would create a matrix X with 2 rows and 3
columns as follows:
X =
1 2 3
4 5 6
The command Y = exp (X ) implies that the exponential function should be applied to
each element of X separately. This is because exponential function has the flexibil-
ity to accept scalar, vector, or a matrix as an input and perform element-by-element
computation. There are several other functions in MATLAB such as log, sin, and
cos that have the same flexibility. Thus, Y(1) would be equal to exp(X(1)). Other ele-
ments would be computed in a similar fashion. The resultant Y matrix is shown here:
Y =
2.7183 7.3891 20.0855
54.5982 148.4132 403.4288
2. The functions sin and cos in this example operate on a vector X. Observe the
vector sin(X) and sin(X).^2 here:
>> X = [-pi:pi/2:pi] % Elements in step of pi/2
X =
-3.1416 -1.5708 0 1.5708 3.1416
>> L = sin(X) % sin(X) returns a vector
ans =
-0.0000 -1.0000 0 1.0000 0.0000
>> K = L.^2 % This is sin(X).^2
ans =
0.0000 1.0000 0 1.0000 0.0000
The elements in vector K are squares of the elements in vector L. The resultant vec-
tor Y is shown here:
>> Y = sin(X).^2 + cos(X).^2
Y =
1 1 1 1 1
1 2 1
A = 4 3 0 ;
6 5 4
2 3 5
B = 1 0 6 ;
2 3 1
5 1 9 0
C = 4 0 6 2 ;
3 1 2 4
3 2 5
4 1 3
D= ;
6 2 1
2 5 6
Compute the following using MATLAB and verify manually. If it results in an error message,
then explain the same with reasoning.
(a) A − 2.*B
(b) (A-2).*B
(c) A.^2
(d) sqrt(A)
(e) C' + D
(f) C.*D
(g) A-2*eye(3,3)
(h) C'.*D'
Example 2.8
The (n + 1)th term in a Fibonacci series is given as: Example 2.8:
Finding the
Tn + 1 = 1/ 5[((1 + 5)/2)n − ((1 − 5)/2)n], sum of 'n' terms
n = 0, 1, 2, 3, … of a series
Display the first 10 terms of the series and find out the sum.
Solution
The MATLAB code is saved in the file 'Fib.m':
Fib.m
The two MATLAB functions used here are sqrt and sum. The function sqrt(x)
computes the square root of the number X while sum(Y) computes the sum of the
elements of the vector Y. The sqrt function can accept vectors or matrices as
input in addition to scalars. Thus, a vector N is created using the colon operator and
passed to sqrt as input. You can run the program by typing the command given
here:
>> Fib
The output is as follows:
Fibonacci Series =
Columns 1 through 7
0 1.0000 1.0000 2.0000 3.0000
5.0000 8.0000
Columns 8 through 10
13.0000 21.0000 34.0000
sum_terms =
88
Note: Do not use 'sum' as a variable, which will otherwise make the standard function
sum provided by MATLAB inaccessible if used in consecutive operations. Therefore,
sum_terms is chosen as the variable name in this program.
Tn = 3 (n 3 + 1) − n
Find the first 10 even terms of the series and find the sum of their squares. Use the vector
notation of MATLAB to accomplish the task.
C = dot(A,B) returns the scalar product of the vectors A and B. A and B must be vectors of
the same length. A vector X = 6i − 7j + 2k in mathematics can be represented as X = [6 −7 2] in
MATLAB. Consider the following examples:
>> X = [3 -9 2]; % Corresponds to 3i -9j + 2k
>> Y = [2 0 3]; % Corresponds to 2i + 3k
>> dot(X,Y)
ans =
12
The vectors can also be column vectors as shown in the following example:
>> X = [1;4;5]
X =
1
4
5
>> Y = [3; 2; 1]
Y =
3
2
1
>> dot(X,Y) % This is equal to 1*3 + 4*2 + 5*1
ans =
16
D = cross(A,B) returns the cross product of the vectors A and B, that is, C = A × B. The
vectors A and B must be three element vectors. A dot product of two vectors is always a scalar,
whereas the cross product always results in a vector. Consider the following example:
>> X = [1; 4; 5];
>> Y = [3; 2; 1];
>> cross (X,Y)
ans =
-6
14
-10
The input vectors can also be row vectors as shown here:
>> X = [1 4 5]
X =
1 4 5
>> Y = [3 2 1]
Y =
3 2 1
>> cross(X,Y)
ans =
-6 14 -10
When matrices are used with relational operators, the size of the matrices should be the same.
Comparison is made on the element-by-element basis (an array operation) for matrices and
vectors. Consider the following examples:
>> [1 2]==[1 3]
ans =
1 0
>> [1 2 3; 3 5 6]>[0 4 3; 1 3 7]
ans =
1 0 0
1 1 0
>> (1 + 10i) < (2 + i)
ans =
1
In this example(1 + 10i) < (2 + i), the first complex number proves to be smaller than
the second number. The reason is that any logical operator in MATLAB compares only the real
parts in case of complex numbers. If the comparison of the magnitude is required, it should be
done in the following way:
>> abs(1 + 10i) < abs(2 + i)
ans =
0
Here, the function abs(x) is the absolute value of a number x. When x is complex, abs(x)
gives the magnitude of the complex number x. The relational operators can also be used with
the string data as shown in the following command:
>> 'raman'=='samir'
ans =
0 1 1 0 0
MATLAB treats a string as an array and compares equivalence element-wise. Such compari-
sons can be useful in arranging the names in alphabetical order, verifying login and password,
and many other similar purposes.
It should be noted that "=" is an assignment operator, whereas "= =" is a relational operator.
Typing errors in these operators can result in a programming bug as shown here:
>> b = 4; % Scalar initialization
… % Some statements
>> a = [1 2 3]; % a is a vector
>> b == a; % Mistype here
% You wanted to assign b equal to a,
% i.e., b = a
>> b(2) % Later, error results as b is a
% scalar with value 4
% b is not an array
??? Index exceeds matrix dimensions.
Symbol Operation
& And
| Or
~ Not
of the expressions are true and returns "false" only if both expressions are false. Consider the
following examples:
>> 8 > 6&'c' > 'b'
ans =
1
>> 2 > 3|(1 + 2i) < 2
ans =
1
The relational operator can also be applied to vectors or matrices of equal dimensions as shown
in the following example:
>> A = [1 4 9];
>> B = [2 2 5];
>> C = [0 5 2];
>> d = A > B & A > C
d =
0 0 1
The expression d = A > B & A > C is evaluated by taking "and" of the two vectors A > B and
A > C, both of which are shown here:
>> A > B
ans =
0 1 1
>> A > C
ans =
1 0 1
ans =
-63
>> rank(A) % is the rank of matrix A
ans =
4
The number 2.5 has been copied into two rows and three columns to form matrix P.
Consider a vector X where X = [a b c]. Here a, b, and c are some scalars. Observe the com-
mand below to make tiling of X:
>> Q = repmat(X, 3, 3),
Q =
a b c a b c a b c
a b c a b c a b c
a b c a b c a b c
The resultant matrix Q is a copy of vector X. It has three rows and three columns, as if the whole
vector is one element. Consider the following example:
>> R = repmat ([1, 2]', 2, 3)
% the symbol ' indicates transpose of vector R
R =
1 1 1
2 2 2
1 1 1
2 2 2
The resultant matrix R is tiling the vector[1, 2]'into two rows and three columns. You can
also tile a matrix into any number of rows and columns as shown in the following example:
>> s = repmat([3 7; 5 9], 2, 3)
% produces (2×3) tiles of given matrix [3 7;5 9]
s =
3 7 3 7 3 7
5 9 5 9 5 9
3 7 3 7 3 7
5 9 5 9 5 9
Another useful command for preparing vectors for plotting is the meshgrid command. [X, Y] =
meshgrid (x, y), transforms the domain specified by vectors x and y into matrices X and Y that
can be used for evaluating functions of two variables and 3-D surface plots. The rows of the
output matrix X are copies of the vector x and the columns of the output matrix Y are copies of
the vector y. Consider the following example:
>> x = [1 2 3 4];
>> y = [5 6 7 8];
>> [X Y] = meshgrid(x,y)
X =
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
Y =
5 5 5 5
6 6 6 6
7 7 7 7
8 8 8 8
Both X and Y are matrices of the same size (4 × 4) and they make a proper combination of coor-
dinates to be used for plotting purposes.
5. Almost all the library functions in MATLAB use only small case letters. Be careful not to
use any upper case letters. For example, exp(3) is correct but Exp(3) and EXP(3) are
invalid usages of the function exp.
6. The order of elements in matrix operations is important. Sometimes both A*B and B*A will
be valid for the two matrices A and B, but the results may be completely different.
SUMMARY
In this chapter the representations of different data types in MATLAB, creating and manip-
ulating arrays and matrices, and the usage of different operators and their applications in
problem solving are discussed. MATLAB gives efficient ways for handling matrix multi-
plication and inversion operations and has a rich collection of library functions for many
operations on matrices. The colon operator is especially useful in creating matrices. The
elements of matrix are accessed using indices inside parentheses. The square bracket pair
[] is useful in concatenating the matrices.
The concept of element-by-element operation, that is, array operation and matrix opera-
tions, plays a crucial role in solving larger computational problems. Matrix operators (such
as *, /, ^, and \) when preceded by a dot operator ( . ) are called array operators.
Several MATLAB functions such as sin, cos, and exp and relational operators can
accept scalar, vector, or matrix as an input argument. These functions perform element-by-
element operation.
EXERCISES
(d) Write MATLAB commands to eliminate the last row and last column of a given matrix
A, regardless of its size.
(e) Write MATLAB commands to access the second last row and second last column of
any given matrix A, irrespective of its size.
2.4. Explain the output for the following expressions in MATLAB.
(a) >> [1+2i]'
(b) >> 2\[2, 4, 6]
(c) >> 20/2\10^2 - 3 + 1
(d) >> 20\200/5 * 10 - 3 + 1
(e) >> 2\[2, 4, 6]/[1 2 3]
(Hint: Follow the operator precedence rules)
2.5. Matrix A is given as
A = [11, 12, 13, 14; 21, 22, 23, 24; 31, 32, 33, 34; 41, 42, 43, 44].
Perform the following operations on matrix A:
(a) Interchange the first and the fourth rows.
(b) Interchange the second and the third columns.
(c) Interchange the second row with the second column; you are allowed to use more than
one line of code, if necessary.
(d) Reset all elements with odd row and column numbers to zero; rest of the elements
must remain unchanged.
(e) Rearrange all the columns of the matrix A with their order changed to the sequence: 3,
1, 4, 2
(Ans: P = A(:, [3 1 4 2]) )
(f) What will be the result of the following operation? Explain.
>> P = A([1 3 4 2], [3 1 4 2])
2.6. Show that the matrix z = (1/ 2 )*[-1 -1; -1 1] is an orthogonal matrix.
(Note: A matrix P is said to be an orthogonal matrix if P'P = I; where I is the identity
matrix.)
2.7. (a) Find the relationship between Fahrenheit and Kelvin scales.
(b) Give a table in the form of a matrix, which gives Kelvin values in the second column
for the corresponding temperature values in Fahrenheit, shown in the first column:
–75, –50, –25, 0, 25, …, 200°F.
(c) Plot a graph that describes the relationship between Fahrenheit and Kelvin scales
between 200°K and 540°K.
(Hint: The relationship between °C, °F, and °K scales is as follows:
°C = 5/9(°F – 32),
°K = °C + 273
plot (x, y ) is used for plotting an array "y" versus an array "x")
2.8. Find the solution of the following set of algebraic equations:
(a) 2x1 + x2 + 5x3 = -1
(b) x1 - 2x2 + x3 = 1
(c) x2 + 2x3 = 0
Path Segment 1 2 3 4 5
Force (N) 75 95 60 55 40
Distance (m) 10.95 7.125 13.5 12.2 18.197
Using MATLAB arrays, find the work done on each path segment and the total work
done over the entire path.
2.14. Constant forces P = 2i – 5j + 6k and Q = -i +2j –k act on a particle. Determine the work
done when the particle is displaced from a point A to a point B, the position vectors of
points A and B being 4i – 3j -2k and 6i + j – 3k, respectively.
2.15. Show that the points (–6, 3, 2), (3, –2, 4), (5, 7, 3) and (–13, 17, –1) are coplanar.
(Hint: Vectors AB, AC, and AD will be coplanar if their scalar triple product AB × AC⋅AD
is zero)
2.16. The electrical power drawn by a single-phase load is given as P = V⋅I⋅cosΦ, where cosΦ
denotes the power factor of the load. The following table gives the average current and
power factors of five different machines in a workshop, designed to operate at different
voltage ratings. Using MATLAB arrays, compute the average power rating of each of
these:
In this problem, if the reactive power consumed is given by the expression Q = V⋅I⋅sinΦ,
then compute the average reactive power demand of each of these machines.
2.17. Rank is an important property of a matrix, used in many mathematical and scientific
applications. The rank of a matrix A is the maximum number of linearly independent
columns of A; or, it is the order of the largest nonsingular matrix contained in A.
Find the rank of the following matrices:
(a) A = [3,2; 6,1; 3,0], (b) B = [2,4,0,8; 1,2,6,3],
(c) C = [3,0,0; 1,2,0; 0,0,1]
(Hint: Use the MATLAB inbuilt function rank)
2.18. If matrix A = [3, 9, 2; 1, 3, 0; 2, 6, 1], verify the following properties:
(a) Rank of A = rank of A'
(b) Rank of A = rank of A'A
(c) Rank of A = rank of AA'
2.19. A ball of mass m = 2 kg has its initial position on the x-y plane as (2, 3, 0). Due to an
external force, it moves parallel to the y-axis with a speed of 5 m/s. Write the three
components of the position vector (r) and the velocity vector (v) of the ball in terms of
MATLAB arrays. Now, if the angular momentum vector P is given as P = m(r × v), then
calculate the following using MATLAB:
(a) Matrix R giving the position vectors in five different rows for t = 0 to 5 s
(b) What is the location of the ball at t = 3.5 s?
(c) Compute the angular momentum vector P. What is its direction?
2.20. Eigenvalues are a special set of scalars associated with a linear system of equations (i.e.,
a matrix equation) that are sometimes also known as characteristic roots, proper values,
or latent roots.
The determination of the eigenvalues and eigenvectors of a system is extremely impor-
tant in physics and engineering, where it is equivalent to matrix diagonalization. Its need
arises in common applications such as stability analysis, the physics of rotating bodies,
and small oscillations of vibrating systems.
An eigenvalue and eigenvector of a square matrix A are a scalar l and a nonzero vector
x that satisfy the equation:
Ax = lx
This can also be written concisely as follows:
(A – lI)x = 0; where I is the identity matrix of suitable size.
The solution to this equation is given as follows:
det(A - lI) = 0
This equation is known as the characteristic equation of A, and the left-hand side is
known as the characteristic polynomial.
Now, let the state space equation of a particular system be given by the following set
of equations:
X = AX + Bu
where
A = [0 1 0 0; 25.92 0 0 0; 0 0 0 1; -2.36 0 0 0] and
B = [0 -0.0732 0 0.0976]'
Find the roots of the characteristic equation of A and also the corresponding eigenvectors
so as to satisfy the condition:
AX = lX
2.21. Find the characteristic roots (eigenvalues) and the characteristic vectors (eigenvectors) of
the following matrices:
(a) A = [8 −6 2; −6 7 −4; 2 −4 3]
(b) B = [−2 2 3; 2 1 −6; –1 −2 0]