0% found this document useful (0 votes)
36 views

M02 - Programming in Matlab - XXXX - CH02

The document discusses MATLAB data types including integers, floating point numbers, complex numbers, constants, text strings, vectors, matrices, Boolean values, and arrays. It describes how to create and access elements of arrays and matrices in MATLAB. Key points are that MATLAB allows matrix operations on all data types, arrays can represent vectors, matrices and higher dimensions, and commands like size and length provide properties of arrays.

Uploaded by

Insignia D.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

M02 - Programming in Matlab - XXXX - CH02

The document discusses MATLAB data types including integers, floating point numbers, complex numbers, constants, text strings, vectors, matrices, Boolean values, and arrays. It describes how to create and access elements of arrays and matrices in MATLAB. Key points are that MATLAB allows matrix operations on all data types, arrays can represent vectors, matrices and higher dimensions, and commands like size and length provide properties of arrays.

Uploaded by

Insignia D.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

2

Matrix
Operations and Applications

After studying this chapter, you should be able to:


 understand different data types in  use array and matrix operators
MATLAB  use matrices in problem solving
 create and manipulate arrays and
matrices

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.

2.2 Data Types in MATLAB


MATLAB provides a user-friendly notation for input and output data. Following are some data
types in MATLAB:
1. Integers: They can be positive or negative numbers such as 1, 2, 3 or −1, −2, −3.
2. Floating point numbers: These are numbers with decimal places such as 3.14159. The
exponent notation can be used to specify the floating point constants. For example,

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 19 1/15/2014 1:29:26 PM


Matrix Operations and Applications  É 20

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:

Table 2.1  Pre-defined constants

MATLAB Symbol Represented Value


Pi The constant p = 3.14159265358
Inf Positive infinity, which results from MATLAB operations
such as 1/0
−Inf Negative infinity, which results from MATLAB operations
such as −1/0
NaN Not a number and results from MATLAB operations
such as 0/0 or inf-inf
i, j Used to represent the imaginary unit of complex numbers

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

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 20 1/15/2014 1:29:26 PM


21 Ñ 
  MATLAB Array

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).

2.3  MATLAB Array


An array is a collection of data values organized into rows and columns. When the array has
only one dimension (either a row or a column), it is known as a vector, while a two or more
dimensional array is known as a matrix.
It is important to note that in MATLAB even a scalar is treated as an array with dimension
1 × 1. A character string is also treated as an array. Observe the following examples:
>> A1 = [1,2,3,4,5] % A1 is a vector
>> A2 = [1 2 3 4 5] % A2 is a vector same as A1
>> B = [1,4,7;2,5,8;3,6,9] % B is a matrix
>> C = 'Sitaram' % C is a string array

By typing the above at the command prompt, MATLAB echoes as follows:


A1 =
1 2 3 4 5
A2 =
1 2 3 4 5
B =
1 4 7
2 5 8
3 6 9
C =
Sitaram
The elements of a vector or a matrix are accessed using the parentheses operator. Inside the
parentheses is the index of the element as follows:
>> A1(2) % indicates second element of array a.
ans =
2
>> B(1,3)
ans =
7

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 21 1/15/2014 1:29:26 PM


Matrix Operations and Applications  É 22

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

>> [m n] = size(B) % returns the number of rows and


% columns in b as separate output
m =
3
n =
3

Time for Practice 2.1


Enter the following code at the MATLAB command prompt:
>>A = rand (3,4)
Contrast the information obtained from the command whos A with that obtained from the
command size (A).

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

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 22 1/15/2014 1:29:26 PM


23 Ñ 
  Creating Vectors and Matrices

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.

2.4  Creating Vectors and Matrices


It is important to know how to create matrices efficiently before you proceed to general applica-
tion of vectors and matrices in solving problems. There are several ways in which matrices can
be created to suite a particular problem.
A common way to create a vector is to place the elements of the vector separated by space in
square brackets [ ] in the following manner:
>> VEC1 = [10 12 0 1 5 8 9 10 20]
VEC1 =
10 12 0 1 5 8 9 10 20

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

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 23 1/15/2014 1:29:26 PM


Matrix Operations and Applications  É 24

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

where s = start or initial value;


d = increment/decrement step;
f = end or final value.

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

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 24 1/15/2014 1:29:26 PM


25 Ñ 
  Creating Vectors and Matrices

>> 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

Time for Practice 2.2


A vector in MATLAB refers to a single dimensional array. Do the following exercises using
MATLAB:
1. Create a vector y having a regular spacing of 0.25 between the values 3 and 11, using
the colon notation ( : ) and then using linspace command.
2. Create a vector z having 20 regularly spaced values starting at -5 and ending at 5, using
the colon notation ( : ) and linspace command.
3. Create a vector u having 50 logarithmically equally spaced values starting at 10 and
ending at 1000.

Time for Practice 2.3


Write a MATLAB code to take the names of two students, truncate them to the length of one
with lesser number of characters, and then compare them to decide which one comes first
in an alphabetical list.

2.4.1  Creating Sub-matrices of a Given Matrix


MATLAB supports several ways of creating and accessing a part of the matrix. One can access
one element, a row, a column, or a sub-matrix. These concepts are illustrated with an example
matrix A, which is created as follows:
>> A = [1 3 5; 2 4 6; 11 9 7; 3 4 5]

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 25 1/15/2014 1:29:26 PM


Matrix Operations and Applications  É 26

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

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 26 1/15/2014 1:29:26 PM


27 Ñ 
  Creating Vectors and Matrices

A(:) returns one long column combining the columns of A as follows:


>> A(:) % returns one long column formed from the
  % columns of A.
ans =
1
2
11
3
3
4
9
4
5
6
7
5
6
7
5

2.4.2  Changing the Elements of a Matrix


Consider matrix A:
>> A = [9 1 7; 2.5 7.5 12; 5 6.2 11]
A =
9.0000 1.0000 7.0000
2.5000 7.5000 12.0000
5.0000 6.2000 11.0000

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:

>> A(3, :) = [7 1 9] % resets the third row


A =
9.0000 1.0000 7.0000
2.5000 7.5000 12.0000
7.0000 1.0000 9.0000

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 27 1/15/2014 1:29:26 PM


Matrix Operations and Applications  É 28

>> A(:, 2) = [5 1 7]' % resets the second column


A =
9.0000 5.0000 7.0000
2.5000 1.0000 12.0000
7.0000 7.0000 9.0000
>> A(:,1) = [1 2]
??? Error

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.

2.4.3  Creating Special Matrices


There are some special commands such as ones, zeros, and eye in MATLAB to create
­special matrices. These are especially useful for initializing all the elements of the matrix to

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 28 1/15/2014 1:29:26 PM


29 Ñ 
  Creating Vectors and Matrices

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

An identity matrix of order 3 × 3 can be created using eye command as follows:


>> C = eye(3)
C =
1 0 0
0 1 0
0 0 1
In many applications (such as learning a neural network), a matrix with random numbers is
required. The command rand generates a matrix with randomly generated numbers chosen from
a uniform distribution in the interval (0.0, 1.0). For example:
>> D = rand(2,4)
D =
0.6038 0.1988 0.7468 0.9318
0.2722 0.0153 0.4451 0.4660
You can also create a vector using any of the aforementioned commands as illustrated by the
following example:
>> X = rand(1,4)
X =
0.8913 0.7621 0.4565 0.0185

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 29 1/15/2014 1:29:26 PM


Matrix Operations and Applications  É 30

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:

>> z = magic(3) % gives the following matrix


z =
8 1 6
3 5 7
4 9 2

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:7, 10] % V is a concatenated vector.


% Note the middle vector is 2:7

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

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 30 1/15/2014 1:29:26 PM


31 Ñ 
  Creating Vectors and Matrices

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:
com­mand? 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

Example 2.3 Example 2.3:


What is the output when you execute the following commands? Accessing
the selected array
>> X = -5 : 2 : 5 elements
>> X(2 : 2 : end)

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 31 1/15/2014 1:29:26 PM


Matrix Operations and Applications  É 32

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.

Time for Practice 2.4


What will be the output of the following commands?
(a) A = [1,2;3,4];
B = [A 2*A]
(b) A(1,:)
(c) B(:,2)
(d) E = [A,B]
(e) F = [A;B]
(f) A([1,2],:)= A([2,1],:)

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 32 1/15/2014 1:29:27 PM


33 Ñ 
 Operators

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

2.5.1  Matrix Operators


Table 2.2 summarizes the matrix operators available in MATLAB:

Table 2.2  Matrix 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

The order of precedence for these operators is as follows:


^ / \ * + −
The order of precedence can be modified by using the parenthesis "( )", which gets the highest
priority. Note that these operators are valid not only for matrices but also for any general vari-
able or expression.
You can apply scalar multiplication, addition, subtraction, and power operators on vectors
and matrices using the operators mentioned in Table 2.2. Consider the following example where
you would like to add 2 to all the elements in vector A:
>> A = [1 2 3 4 5 6 9 8 7]
A =
1 2 3 4 5 6 9 8 7
>> B = A + 2
B =
3 4 5 6 7 8 11 10 9
When a vector or matrix is added with a scalar number, MATLAB interprets that each element
should be incremented by the number. In this case, scalar 2 is added to all the elements of the

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 33 1/15/2014 1:29:27 PM


Matrix Operations and Applications  É 34

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.

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 34 1/15/2014 1:29:27 PM


35 Ñ 
 Operators

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] % create a 3×2 matrix

C =
1 2
3 4
5 6

>> D = C' % D is 2×3 matrix

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

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 35 1/15/2014 1:29:27 PM


Matrix Operations and Applications  É 36

% a simple (un-conjugated) transpose


ans =
2.0000 + 3.0000i 1.0000 + 1.0000i
2.0000    - 3.0000i 1.0000    - 1.0000i
1.0000     0

2.5.2 Matrix Multiplication and Inversion


Matrix multiplication and inversion are applied in many important problems in science and engi-
neering. MATLAB provides optimized functions to do multiplication and matrix inversion. The
operators *, /, \, and so on are useful in matrix operations. Multiplication or inversion of matrices
involves many lines of code in other programming languages. In MATLAB, however, you can do
the same with great ease. Initialize the matrices A and B on your MATLAB desktop as follows
>> A = [1 2; 3 4]
A =
1 2
3 4
>> B = 2 * ones(2)
B =
2 2
2 2

Consider the following matrix multiplication A × B and B × A:


>> A * B
ans =
6 6
14 14

>> B * A
ans =
8 12
8 12

Time for Practice 2.5


Given the matrices
A = [−3, 11; 5, -7]
B = [2, 15; 18, -5]
C = [1, 10; 9, 12]
use MATLAB to verify the following:
(a) The commutative law: A + B + C = B + C + A = C + A + B = A + C + B
(b) The associative law: (A + B) + C = A + (B + C)
(c) The associative law: (AB)C = A(BC)
(d) The distributive law: A(B + C) = AB + AC

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 36 1/15/2014 1:29:27 PM


37 Ñ 
 Operators

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

The matrix elements in D are the same as that in matrix A.


(c) The expression B\C is also the same as C/B in MATLAB language, that is, B\C  =
C*inv(B). The output of the expression B\C will therefore be the same as ques-
tion (b). This is shown here:
>> E = B\C % symbol \ is left division operator.

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 37 1/15/2014 1:29:27 PM


Matrix Operations and Applications  É 38

E =
8.0000 1.0000 6.0000
3.0000 5.0000 7.0000
4.0000 9.0000 2.0000

Time for Practice 2.6


What will be the MATLAB output for the following expressions?
(a) [1 0 7] > = [1 + 2i 5i 7 + 7i ]
(b) (1 + 10i ) < (2 + i )
(c) abs(1 + 10i ) > abs(2 + i )
(d) 'raman' < = 'raghu'
(e) 'Gopal' = = 'GoPal'

2.5.3 Array Operators


Most of the operators discussed in Table 2.2 (such as *, ^, or /), if preceded by a dot (.) result
in an element-by-element operation (also known as an array operation). Accordingly, these
operators are known as array operators. Consider the following examples that illustrate array
operations:
>> X = [1 2 3]
X =
1 2 3
>> Y = [4 5 6]
Y =
4 5 6
>> X .* Y % Element-by-element multiplication
ans =
4 10 18

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.

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 38 1/15/2014 1:29:27 PM


39 Ñ 
 Operators

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

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 39 1/15/2014 1:29:28 PM


Matrix Operations and Applications  É 40

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

5. K = E./F is element-by-element division as follows:


>> K = E./F
K =
0.5000 0.6667
0.7500 0.8000

6. L = E.^F is an element-by-element power (or array power). L is shown here:


>> L = E.^F
L =
1 8
81 1024

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

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 40 1/15/2014 1:29:28 PM


41 Ñ 
 Operators

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

Time for Practice 2.7


Let A, B, C, and D be the following matrices:

 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

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 41 1/15/2014 1:29:28 PM


Matrix Operations and Applications É 42

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'

Time for Practice 2.8


Given the matrices
A = [3, 2, 1 ; 0, −1, 5 ; 1, 2, 3]
B = [3, −1, 2 ; 5, 0, −3 ; 1, 7, 9]
show the following:
(a) A .* B ≠ A* B; but A .* B = B .* A
(b) A*B ≠ B *A; and A ./ B = B .\ A
(c) (AB)' = B 'A' ≠ A'B '; where ' indicates the transpose of the matrix.
(d) A*inv(A) = inv(A)*A = I
(e) (AB)–1 = B –1A–1 ≠ A–1B –1

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

% program to generate a Fibonacci Series


N = 0:9; % Generates a vector

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 42 1/15/2014 1:29:29 PM


43 Ñ 
 Operators

S = 1/sqrt(5)*(((1 + sqrt(5))/2).^N - ((1 - sqrt(5))/2).^N);


%Note the use of array power(.^)with this expression
disp ('Fibonacci Series ='), disp(S)
sum_terms = sum(S)

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.

Time for Practice 2.9


The nth term of a series is given by the following expression:
Tn = (2n -1)/n (n + 1) (n + 2)
Find the first, third, fifth, eleventh, fifteenth, and nineteenth term of this series using a vector.
Find the sum of the first ten terms.

Time for Practice 2.10


The nth term of a series is given by the following expression:

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.

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 43 1/15/2014 1:29:29 PM


Matrix Operations and Applications  É 44

Dot Product and Cross Product of Vectors


Dot and cross products of two or more Cartesian vectors are often used in solving problems in
mathematics, physics, and electromagnetics. The descriptions for MATLAB functions for such
operations are discussed here.

Time for Practice 2.11


Vectors a, b, and c are given in terms of their x, y, and z components as follows:
a = i + 2j + 5k
b = 3i + j + 9k, and
c = 7i + 3j + k
The scalar (dot) and vector (cross) product of two vectors can be found in MATLAB using
the inbuilt functions dot and cross. For the given vectors, verify the following properties of
dot and cross products using MATLAB:
  (i) Dot product properties:
a⋅b = b⋅a;(5a)⋅b = 5(a⋅b);
a⋅(b + c) = a⋅b + a⋅c
(ii) Cross product properties:
a × b = –b × a;
a × (b + c) = a × b + a × c;
(5a) × b = 5(a × b)
Use the following vectors for solving the problem:
a = [1, 2, 5], b = [3, 1, 9] and c = [7, 3, 1]

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

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 44 1/15/2014 1:29:29 PM


45 Ñ 
 Operators

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

Time for Practice 2.12


Show that the three vectors,
A = [2, 6, 8], b = [1, 3, 4], and c = [-0.5, -1.5, -2] are parallel
(Hint: In parallel vectors, the cross product of any combination of two vectors will be a null
vector)

Time for Practice 2.13


Find the angle of cross section of the two vectors whose end points are given by the x-y
coordinates as
Vector 1: (1,2) and (3,5)
Vector 2: (2,3) and (4,-3)
(Hint: The dot product of the two vectors is a⋅b = |a|⋅|b|⋅ cosq ; where q is the angle of cross
section between the two vectors, while |a| and |b| denote their magnitudes.)

2.5.4  Relational Operators


Boolean (or relational) operators are used for decision-making. A positive number (usually 1)
represents TRUE and zero represents FALSE. For example:
>> a = 3; b = 7;
>> c = b > a
c =
1
>> d = a > b
d =
0

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 45 1/15/2014 1:29:29 PM


Matrix Operations and Applications  É 46

The relational operators in MATLAB are given in Table 2.3:


Table 2.3  Relational operators

Symbol Operation Cases Where x = 1 (True) Cases Where x = 0 (False)


< Less than X = 3 < 10 X = 54 < 2
> Greater than X = 'b'>'a' X = 'a'>'b'
< = Less than or equal to x = 5 < = 5 x = 6 <= 5
> = Greater than or equal to x = 10 >= 7 x = 5 >= 7
= = Equal X = 'a'=='a' X = 'a'=='b'
~ = Not equal X = 10 ~= 90 X = 10 ~= 10

Time for Practice 2.14


Find the projection of the vector (i - 2j + k) on (4i - 4j + 7k).
(Hint: The projection of A over B is equal to |A|⋅cosq.)

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'

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 46 1/15/2014 1:29:30 PM


47 Ñ 
 Operators

ans =
0 1 1 0 0

Time for Practice 2.15


Given the matrices:
A = [-3, 11; 5, -7]; B = [2, 15; 18, -5] and C = [1, 10; 9, 12],
Show that:
(A-1)' = (A') -1
(ABC) -1 = C -1B -1A-1

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.

2.5.5  Logical Operators


Relational operators may be combined with logical operators, which are as follows:

Symbol Operation
& And
| Or
~ Not

The order of precedence for these logical operators is as follows:


~ & |
The & operator takes two logical expressions and returns "true" if both expressions are true
and "false" otherwise. The | operator takes two logical expressions and returns "true" if either

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 47 1/15/2014 1:29:30 PM


Matrix Operations and Applications  É 48

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

2.6  Properties of a Matrix


Some of the important numerical values associated with a matrix are its size, determinant value,
and rank, which can be found by using the MATLAB commands size, det, and rank as shown
here:
>> A = [3*eye(2), 2*ones(2); 2*ones(2), 3*eye(2)]
A =
3 0 2 2
0 3 2 2
2 2 3 0
2 2 0 3
>> size(A) % is the pair of numbers [m n]
   % m is number of rows
  % n is columns
ans =
4 4
>> det(A) % is the determinant for a square matrix

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 48 1/15/2014 1:29:30 PM


49 Ñ 
  Replicating Data to Form a Matrix

ans =
-63
>> rank(A) % is the rank of matrix A
ans =
4

2.7  Replicating Data to Form a Matrix


MATLAB provides two functions that can be used to create matrices by replicating some speci-
fied number of times a scalar, a column vector, a row vector, or a matrix. These functions are
useful in 2-D and 3-D plots of a function. The two functions are repmat and meshgrid.
The general syntax for "repmat" is
>> repmat(x,r,c)
where "x" can be a scalar, a vector, or a matrix. The function repmat will produce r × c tiling
of copies of "x". Consider the following example:
>> P = repmat(2.5, 2, 3)
This command results in the following output:
p =
2.5000 2.5000 2.5000
2.5000 2.5000 2.5000

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]

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 49 1/15/2014 1:29:30 PM


Matrix Operations and Applications  É 50

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.

  Programming Tips and Pitfalls


The following tips should be kept in mind while working with arrays and matrices:
1. Use only square brackets [ ] for creating a single or multi-dimensional arrays. On the other
hand, accessing an array element and supplying arguments to any library function requires
the use of parentheses ( ).
2. In creating an array, the colon notation (:) can be used and it can also be used as an index
to access a group of elements of the array, but only integer operands are allowed for colon
operator when used as an index.
3. You should never use ans as a variable name in your programs. MATLAB uses ans as a
default variable name for storing the answer. Any computation in MATLAB could change
the value of this variable unexpectedly.
4. If you name a matrix in capital letters, then trying to access it or performing any operations
on it using small case letters will result in an error. MATLAB is case sensitive. For example,
matrix 'A' will not be accessible through variable 'a'.

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 50 1/15/2014 1:29:30 PM


51 Ñ Exercises

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

2.1. If A = [1 2 3; 1 2 1; 3 1 1] and B = 2+eye (3), then show that:


(a) A*B ≠ B*A, (b) A./B ≠ B./A,
(c) A^2 = A*A, (d) A.*B = B.*A,
(e) (A*B)' = B' * A' (f) 2^A ≠ 2.^A
2.2. Prove that A3 − 4A2 − 3A + 11I = 0, where A = [1 3 2; 2 0 −1; 1 3 2] and I is a unity matrix
and 0 is a null matrix.
2.3. Given a matrix
A = [1, 3, 5, 7; 2, 4, 6, 8; 5, 1, 7, 9; 9, 1, 5, 7]
create the following sub-matrices from the elements of A:
(a) Matrix made of only odd columns of A
(b) Matrix made of only even rows of A
(c) Matrix made of all those elements of A, which belong neither to the even columns nor
to the even rows of the original matrix

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 51 1/15/2014 1:29:30 PM


Matrix Operations and Applications  É 52

(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

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 52 1/15/2014 1:29:31 PM


53 Ñ 
 Exercises

  2.9. A square matrix A is said to be orthogonal, if AA' = A'A = I


If matrix A = [-2/3 1/3 2/3; 2/3, 2/3, 1/3; 1/3, -2/3, 2/3], prove the following:
(a) A is orthogonal.
(b) Since A is orthogonal, A' and A–1 are also orthogonal.
(c) Since A is orthogonal, then determinant of A , that is, |A| = ±1.
2.10. A square matrix U such that U' = U–1 is called a unitary matrix if A = [0 1 + 2i; -1 + 2i 0].
Show that (I – A)*(I + A)–1 is a unitary matrix.
2.11. If A = I + 2j -3k and B = 3i – j + 2k, show that A + B is perpendicular to A – B. Also cal-
culate the angle between 2A + B and A + 2B.
2.12. If A = 4i + 3j + k and B = 2i – j + 2k, find a unit vector N perpendicular to the vectors A
and B such that A, B, and N form a right-handed system. Also find the angle between the
vectors A and B.
(Hint: |A × B| = |A||B|sinJ and the vector (A × B) is perpendicular to both A and B).
2.13. The work done in carrying an object over a distance D with force F is given as the prod-
uct W = F⋅D. The following table gives the data for carrying a wooden block through five
different sections of a certain path, having different friction coefficients:

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:

Machine Voltage (V) 220 110 110 220 75


Average Current (A) 2.5 5 3.75 10 1.75
Average Power Factor 0.85 0.9 0.89 0.73 0.5

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.

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 53 1/15/2014 1:29:31 PM


Matrix Operations and Applications  É 54

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

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 54 1/15/2014 1:29:31 PM


55 Ñ 
 Exercises

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]

M02_PROGRAMMING IN MATLAB_XXXX_CH02.indd 55 1/15/2014 1:29:31 PM

You might also like