SESS 4 Matrices
SESS 4 Matrices
Matrices
4
At the end of this chapter, you will be able to understand what matrices are and will learn
to perform various operations on them.
SCOPE
4.1 Introduction
4.3 Implementation
4.3.1 Static Implementation
4.3.2 Dynamic Representation
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 115
Matrices
4.1 Introduction
Data is very often represented in tabular form. The simplest way to represent tables is to
use two-dimensional arrays. Addition, multiplication, subtraction etc. are the various
operations that can be performed on tables. The inbuilt data type of arrays does not
support any of these operations for a two dimensional arrays. So one of the options is that
we write programs, which perform the above operations, but if these operations are to be
performed very often then it is better to customize the representation. This will save
space as well as time for us. This customized representation is known as matrix.
An m x n matrix is a table with m rows and n columns, where m and n are known as the
dimensions of the matrix. There are various applications where matrices can be used. We
will see some of them in this chapter. Matrices are built using two-dimensional arrays in
the static representation and using linked list in the dynamic representation. The diagram
below will explain the representation of matrix as a mathematical model.
(a) (b)
Fig 4.1
3 x 3 matrix (a) 3 x3 matrix ‘a’ (b) position of each element in ‘a’.
In the figure 4.1, there are three rows (horizontal) and three columns (vertical). Number
of rows is represented as ‘m’ and columns as ‘n’. They are placed in the right hand corner
of the matrix. The elements are placed within the two square brackets. The element in the
first row and the first column is represented as a11; a12 represents the element in the first
row and second column and so on.
1 2
a = 4 5
7 8
3x2
Fig 4.2
3 x 2 matrix
In fig 4.2 there are three rows and two columns represented as 3 x 2.
Chapter 4
116 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
In matrices, the rows and columns start from 1. In ‘C’ the array index starts from zero,
this difference is to be considered when implementing matrices. Every element is
addressed using its row and column position numbers. For example, in fig 4.2 element 8
is placed at third row and second columns.
Let us consider an example and understand how matrices can be useful. There are five
cities connected to each other by air route. The fare from one city to another is
determined based on the distance between the two cities. It is necessary to access the
distance table very often at the ticketing counter. One of the best solutions is to represent
the distance table as a matrix. The representation is as shown in fig 4.3. The five cities
Mumbai (Mu), Delhi (De), Madras (Ma), Calcutta (Ca) and Bangalore (Ba) are
represented along the rows and columns. This makes our matrix a 5 x 5 matrix i.e. with 5
rows and 5 columns.
Cities Mu De Ca Ma Ba
Fig 4.3
Distance table 5 x 5 matrix Distmat (approximate estimation of distances).
In this matrix, both rows and columns feature the five cities. Suppose we want to find the
distance between Mumbai and Delhi. We search for Mumbai in rows; it is at the first
position. Next we search for Delhi in the columns; it is the second member. The distance
between Mumbai and Delhi is 1500, because Distmat[1][2] = 1500.
Let us consider another example where it would be essential to represent data in a tabular
form. We want to represent the sales of three companies for a period of five years. For
this purpose, we will require a 3 x 5 matrix. The companies will be represented as the
rows and the years as columns. The matrix representation will look as shown below.
ABC 10 40 10 30 20
XYZ 25 20 10 40 20
PQR 15 35 20 25 30 3x5
Fig 4.4
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 117
Matrices
Value Definition:
Operations:
Function: To add two matrices a and b. Matrix a has m1 rows and n1 columns and b has
m2 rows and n2 columns.
Precondition: m1 = = m2 and n1 = = n2. The number of rows and columns of both the
matrices are same.
Postcondition: Sum of matrices a and b. The resulting matrix will have m1 rows and n1
columns.
(2) sub(a[m1][n1],b[m2][n2])
Function: To subtract two matrices a and b. Matrix a has m1 rows and n1 columns and b
has m2 rows and n2 columns.
Precondition: m1 = = m2 and n1 = = n2. The number of rows and columns of both the
matrices are same.
Postcondition: Subtraction of matrix b from a. The resulting matrix has m1 rows and n1
columns.
Chapter 4
118 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
(3) transpose(a[m][n])
Function: To interchange the values of rows and columns in the given matrix. The input
matrix has m rows and n columns.
Postcondition: Matrix a[n][m] will be the resulting matrix. The matrix will be of n rows
and m columns.
(4) multiply(a[m1][n1],b[m2][n2])
Function: To multiply the matrices a and b. Matrix ‘a’ has m1 rows, n1 columns and ‘b’
has m2 rows and n2 columns.
Precondition: n1 = = m2. The number of columns of the first matrix is equal to the
number of rows of the second matrix.
4.3 Implementation
int a[3][4];
The above matrix will hold integer type values. Dimensions of the array have to be
explicitly mentioned before the compilation process. Due to this, the rows and columns
are fixed throughout the execution. Any operation done beyond these dimensions will
lead to erroneous results. It is possible to use less number of rows and columns; in this
case, the unused locations will still be a part of the matrix. So proper care should be taken
about the values they hold. It is always desirable to initialize them to zero.
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 119
Matrices
Fig 4.5
Array representation (int a[3,4].)
As seen above the index starts from zero, but in matrix it starts from one. This difference
has to be resolved during programming. There will be twelve integer spaces allotted to
this matrix. It will consume 12 * 2 = 24 bytes. We can use twelve or less spaces but not
more than twelve under any circumstances.
Now we will try to implement matrices. In this process we will implement the various
operations and store the data as tables.
Function:
Brief:
Program:
/*This program creates an m x n matrix and prints it. It uses the static approach to
implement the matrix. Each matrix is stored in a two dimensional array */
/* The function initialize is used to initialize all the values of the given matrix to zero. It
does not return anything and requires an array of m x n to be passed as a parameter. The
array passed as a parameter is initialized to zero. As we know in the static representation
of the matrix the memory is allocated at compile time. It is not essential to use all the
Chapter 4
120 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
locations, hence to avoid any undesirable effects it is essential to initialize all the
locations to zero */
void initialize(int a[m][n])
{
int i=0,j=0;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
a[i][j] = 0;
}
/*This function prints all the values of a given matrix to the screen. The function printm
does not return anything and requires a matrix of size m x n as its parameter. */
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(" %d",a[i][j]);
printf("\n");
}
}
/*This function is used to enter the user values into a given matrix. The function inpm
does not return anything and requires a m x n matrix as a parameter. The user values are
entered into the matrix passes as a parameter */
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
printf("\nenter the value for %d row and %d col",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
void main()
{
int a[m][n],b[m][n];
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 121
Matrices
initialize(a);
initialize(b);
/* User enters the first matrix ‘a’ using the inpm() function */
/* User enters the second matrix ‘b’ using the inpm() function */
Analysis
In all the functions i.e. initialize(), inpm() and printm() there are two for loops,
one for the rows(m) and the other for the columns(n). The statements present in the for
loop are executed n * m times each. Hence, we can say that they are all of O(mn)
complexity. O (mn) gives the upper boundaries of the space and time required. It means
the program will require at the maximum (m x n x memory required by the data type of
the matrix) bytes of memory and the loop will be executed at the maximum m x n times.
Function
Brief
In this function two matrices are added and the output is stored in a third matrix. The
functions like initialize(), inpm() and printm() are common to all of them. So
we will give the new function and the modified main program.
The sum of two matrices is possible only if both of them have the same dimensions i.e.
the same number of rows and the same number of columns. Sum of two matrices can be
expressed as follows:
Chapter 4
122 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
The elements in the matrix a and b having the same row and column position are added
and stored at the same position in the resultant matrix c.
Program
/*This function add the two given matrices and stores the result in a matrix. It returns
nothing and three m x n matrices are taken as parameters. The first two matrices a and b
are the input matrices and third matrix c is the resultant matrix. The addition is
performed on static implementation of matrices */
void main()
{
int a[m][n],b[m][n],c[m][n];
initialize(a);
initialize(b);
initialize(c);
/* input the first matrix using inpm() and print the function using
printm() function*/
/* input the second matrix using inpm() and print the function using
printm() function*/
/*The two matrices are added and the result is stored in the
resultant matrix */
addition(a,b,c);
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 123
Matrices
Example
Analysis
In the add function we find that there are two for loops and a single statement in
between them. So again the complexity turns out to be O(mn). As explained earlier, it
gives the upper bound for the space and time requirements.
Function
To subtract the two given matrices and store it in the resultant matrix.
Brief
This function is similar to the previous one. The operation changes from addition to
subtraction. The expression for subtraction will be
Chapter 4
124 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
The rule for subtraction is same as addition and states that the two matrices to be
subtracted should be of the same dimension. We have given the subtraction method. In
the main program you are suppose to replace the addition function by the subtraction
function.
Program
/*This function subtracts the two given matrices and stores the result in a matrix. It
returns nothing and three m x n matrices are taken as parameters. The first two matrices
a and b are the input matrices and third matrix c is the resultant matrix. The subtraction
is performed on static implementation of matrices */
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j] = a[i][j] - b[i][j];
}
Analysis
Again there are two for loops and one statement for subtraction. So the complexity turns
out to be O(mn). The description is similar to the previous functions.
Example
The subtraction of the two matrices a and b is carried out as shown below:
a11 a12 a13 b11 b12 b13
a–b = 2 3 4
4 5 6 3x3
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 125
Matrices
Function
To multiply the given two matrices and store the resultant matrix.
Brief
In this we will multiply two matrices and store the resultant matrix in the third one. The
expression for matrix multiplication is given as follows:
n
c[i][j] = ∑ a [ i ] [ k ] * b [ k ] [ j ] , 1 <= I <= m1, 1 <= j <= n2
K=1
Program
/*This function multiplies the two given matrices and stores the result in a matrix. It
returns nothing and three m x n matrices are taken as parameters. The first two matrices
a and b are the input matrices and third matrix c is the resultant matrix. The
multiplication is performed on static implementation of matrices */
Example
Chapter 4
126 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
a*b= 32 32 32
50 50 50 3 x 3
Analysis
In the above function there are three for loops. The first loop is equal to the number of
rows of the first matrix while the next two loops equal to the number of columns of the
second matrix. In the above example we have defined all the matrices to be of 3 x 3
dimension hence the resultant matrix is also of 3 x 3 dimension. If ‘a’ is a 3 x 2 matrix
and ‘b’ is 2 x 5 matrix then the resultant multiplied matrix will be a 3 x 5 matrix. The
complexity turns out to be O(m*n*n) i.e. O(mn2).
Function
To form the transpose of the given matrix, store it and print it.
Brief
In this the given matrix is transposed i.e. the elements of rows and columns are
interchanged. The expression for transposed matrix is as follows:
Program
/* This function forms the transpose of the given matrix. The function returns nothing and
two matrices are passed as parameters. The first matrix a is the input matrix and the
second matrix b will store the transpose matrix. */
}
/* the main program starts here */
void main()
{
int a[m][n],b[m][n];
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 127
Matrices
initialize(a);
initialize(b);
/* input the matrix from the user using inpm() function and */
tran(a,b);
printf("\n the transposed matrix is:\n");
printm(b);
}
Example
3 6 9 3 x 3
Analysis
There are two for loops present in the trans() function, hence the complexity is O(mn).
We have seen the static implementation. One of the major disadvantages is that the
number of rows and columns are to be determined during the design time. The memory is
allocated at the compile time. So one has to take into account the maximum number of
rows and columns required during the execution. It is not possible to increase the number
of rows and columns during execution. If maximum number of rows and columns are
allotted to the program, then there are chances that a fairly large amount of memory will
be allocated to the program, but not used at all. This approach will not be the best one
when there is a large difference between the minimum and maximum requirement of
rows and columns. Here we can use linked list and form a matrix as per our requirement.
In the linked representation pointers will link all the rows and columns to each other.
There will be three types of nodes viz. list head node, row head node and column node.
The list head node will point to the first row head node of the matrix. Each matrix has a
single list head node. The row head node is the node placed at the starting of a row and
the elements are stored in the column node. All these nodes and the overall representation
Chapter 4
128 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
of the matrix are shown in the figures given below. Each element will be placed in a
column node along with the column number and a pointer to the next column node. There
will be a head node for each row that will contain the row number and two pointers; one
of them will point to the first element of the row while the other will point to the head
node of the next row. List head node will contain the total number of rows, columns and
pointer to the first row head node. Each column node is accessed through row head node.
There is no vertical link between the column nodes. The structures and visual
representation of nodes is as follows:
struct listhead
{
/*trow hold the total number of rows in the matrix */
int trow;
int tcol;
Fig 4.6
List head node
struct rowhead
{
/* rno stores the row number */
int rno;
Fig 4.7
Row head node
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 129
Matrices
struct colnode
{
/* cno stores the column number of the particular node */
int cno;
int value;
Fig 4.8
Column node
The above nodes are used to form the linked representation of the matrix. We will
implement a 3 x 2 matrix using the above nodes. The values held by the various nodes are
as follows:
trow = 3, tcol = 2, point will contain the address of the first row head node. The
values are a[1][1] = 43, a[1][2] = 29, a[2][1] = 23, a[2][2] = 87, a[3][1]
= 56, a[3][2] = 86.
3 2 point
Fig 4.9
Linked representation of a 3 x 2 matrix
By now you must be very clear how a matrix is represented in linked list format. Now let
us see how the various operations are implemented using this representation.
Chapter 4
130 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
Function
To create a matrix and print it. The implementation should use the dynamic allocation
method.
Brief
There are two functions used in this program, crmat () to create the matrix and print()
to display the matrix. Four parameters are passed to the crmat () function, the list head
pointer, the number of rows and columns and an integer flag which decides whether the
input is taken from the user or the matrix is initialized to zero. The first step is to create
the linked list of row heads. At this time the column pointer nextc is made NULL. In the
next step the column nodes are added one by one. If the flag is zero then the input is
taken from the user else the matrix is initialized to zero. The print() function uses two
temporary pointers to navigate the linked representation. Display is done column by
column. The program is given below.
/* This program will create and print a matrix. It implements matrix using the concept of
dynamic allocation*/
# include <stdio.h>
# include <stdlib.h>
# include <malloc.h>
/* the colnode structure holds the values of the individual elements. The cno field stores
the column’s number the element belongs to. Value field stores the actual user input. The
next pointer points to another colnode. This pointer forms the linked list of the colnodes
*/
typedef struct colnode
{
int cno;
int value;
struct colnode *next;
}col;
/* The structure rowhead is present at the beginning of each row . The field rno contains
the row number. The field nextc is a pointer, which points to the first colnode of that row.
It joins the rowhead nodes to the elements. The pointer nextr points to the next rowhead
node of the matrix. This pointer forms the linked list of all the rowhead nodes*/
typedef struct rowhead
{
int rno;
struct rowhead *nextr;
struct colnode *nextc;
}row;
/* The listhead node is present at the top of the matrix. Each matrix has only one listhead
node. The field trow contains the value of the maximum number of rows present in the
matrix. The field tcol stores the value of the maximum number of columns the matrix can
have. The pointer point points to the first rowhead node. */
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 131
Matrices
head *mat1;
/* The function crmat () creates the matrix using the dynamic allocation method. This
function returns a pointer of the type list head node. There are four parameters passed to
the matrix. The first is a list head pointer, the matrix created will have this as the listhead
pointer. The integer values i1 and j1 provide the function the maximum number of rows
and columns of the matrix. The variable k acts as a flag. If it is set to 0 then the user will
enter the values else the function will create the matrix and initialize it to zero. */
head *crmat(head *mat1,int i1,int j1,int k)
{
row *rtemp,*loc=NULL;
col *ctemp,*cloc = NULL;
int i=0,j=0;
/* The list head node is allocated memory and all the fields are assigned relevant
values. The fields trow and tcol are assigned the maximum number of rows and columns.
The pointer point is assigned a null value.*/
mat1 = (head *)malloc(sizeof(head));
mat1->trow = i1;
mat1->tcol = j1;
mat1->point = NULL;
/* This part creates a linked list of row heads. The number of rows is equal to the number
of maximum rows allocated to the matrix in the listhead node. The various fields of the
rowhead node are also assigned proper values. The field rno holds the row number for
the particular rowhead node. Both the pointers are initialized to null. */
for(i=0;i<mat1->trow;i++)
{
rtemp = (row *)malloc(sizeof(row));
rtemp->rno = i+1;
if(loc == NULL)
{
mat1->point = rtemp;
loc = rtemp;
}
else
{
loc->nextr=rtemp;
loc = loc->nextr;
Chapter 4
132 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
}
rtemp->nextr= NULL;
rtemp->nextc= NULL;
rtemp = NULL;
}
/* This part of the program creates the column nodes and attaches them at their proper
position. This node stores the actual values of the matrix. */
loc = mat1->point;
for(i=0;i<mat1->trow;i++)
{
for(j=0;j<mat1->tcol;j++)
{
ctemp = (col *)malloc(sizeof(col));
if(k= =0)
{
printf("\nenter the value for%d row and %d col",i+1,j+1);
scanf("%d",&ctemp->value);
}else
ctemp->value = 0;
/* The function prints the matrix headed by the given listhead node */
void print(head *mat1)
{
int i=0,j=0;
row *r;
col *c;
r = mat1->point;
c = r->nextc;
for(i=0;i<mat1->trow;i++)
{
for(j=0;j<mat1->tcol;j++)
{
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 133
Matrices
printf(" %d",c->value);
c = c->next;
}
r = r->nextr;
c = r->nextc;
printf("\n");
}
}
/* The main program begins here. All the different functions stated above are used in this
function. The user enters the maximum number of rows and columns. Then crmat ()
function creates the matrix and print() function prints it.*/
void main()
{
int i,j;
printf("\nenter the values for the first matrix");
printf("\nhow many rows");
scanf("%d",&i);
printf("how many coloumns");
scanf("%d",&j);
mat1 = crmat(mat1,i,j,0);
print(mat1);
printf("\nenter the values for the second matrix");
printf("\nhow many rows");
scanf("%d",&i);
printf("how many coloumns");
scanf("%d",&j);
mat2 = crmat(mat2,i,j,0);
print(mat2);
}
Analysis
In this program in the crmat() function there are two loops. The first for loop is
executed m times. The second loop executes for mn times. Hence the complexity is O(mn).
Function
Brief
In this function two matrices are multiplied and the result is stored in the third matrix.
The process is same as in the static representation. Only the function of multiplication is
given below. The students can accordingly change the main program.
/* This function multiplies the two given matrices and stores the output in another matrix.
It returns nothing and requires three listhead pointers as parameters. The first two
listhead pointers point to the input matrices and the result is stored in the matrix pointed
to by the third pointer. */
Chapter 4
134 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
/* Check the condition for matrix multiplication. The method followed to multiply the
matrix is same as in the static implementation*/
if(a->tcol == b->trow )
{
rloc1 = a->point;
rloc2 = b->point;
rloc3 = c->point;
for(i=0;i<a->trow;i++)
{
cloc1 = rloc1->nextc;
cloc2 = rloc2 -> nextc;
cloc3 = rloc3 -> nextc;
for(j=0;j<b->tcol;j++)
{
for(k=0;k<a->tcol;k++)
{
for(l=0;l<j;l++)
cloc2 = cloc2 -> next;
cloc3->value = cloc3->value + cloc2->value * cloc1->value;
cloc1 = cloc1->next;
rloc2 = rloc2->nextr;
cloc2 = rloc2->nextc;
}
cloc1 = rloc1 -> nextc;
rloc2 = b->point;
cloc2 = rloc2 -> nextc;
cloc3 = cloc3 -> next;
}
rloc1 = rloc1->nextr;
rloc2 = b->point;
rloc3 = rloc3 -> nextr;
}
}
else
printf("the matrices cannot be multiplied”);
}
Analysis
The complexity will be O(mnn), it is similar to the static representation.
Function
To add two matrices represented in the linked list format.
Brief
This function adds the two matrices. The process is similar to static representation.
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 135
Matrices
Program
/* The program adds two matrices. It returns nothing and requires two parameters. Both
the parameters are listhead pointers, which point to the input matrices. The output matrix
is not stored in this case, it is directly printed to the screen. Changes can be made to the
function by the students, if they want to store the matrix. */
/* Check the condition for addition. The dimensions of both the matrices should be same.
Addition is carried out in the same way as in the static implementation */
for(i=0;i<a->trow;i++)
{
cloc1 = rloc1->nextc;
cloc2 = rloc2 -> nextc;
for(j=0;j<a->tcol;j++)
{
printf(" %d",cloc1->value + cloc2->value);
cloc1 = cloc1 -> next;
cloc2 = cloc2 -> next;
}
rloc1 = rloc1->nextr;
rloc2 = rloc2 ->nextr;
printf("\n");
}
}
else
printf("the matrices cannot be added");
}
Analysis
The complexity is O(mn). The other operations like subtraction and transpose can be
implemented similarly. The complexity does not change due to change of representation.
But linked implementation does provide the facility to select the number of rows and
columns during the execution.
The basic disadvantage of static representation is that memory has to be allocated during
the compile time itself. Hence the maximum memory is allocated. This can lead to
wastage of memory if all the locations are not used. In linked representation the memory
is allocated during execution time. The pointers, which are used to keep track of the
Chapter 4
136 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
nodes, require two byte memory each. Hence additional memory is required for the
linked representation.
If the number of rows and columns are not very large then the memory required by the
linked representation is more than the static representation. Hence we can conclude that
in case of less or fixed number of rows and columns it is preferable to use the static
representation. If the requirement of rows and columns varies and if the difference
between the minimum and maximum is very large then the linked representation can be
used.
Examples
In this section, we will consider some problems where matrices can be used as the data
structure to represent the data.
(1) We want to store the grades obtained by fifty students in five subjects. So we will
need a matrix of 50 x 5 for this purpose. The grades will be single alphabets like ‘A’,
‘B’ etc. Hence the element to be stored is of character type. Here we know the fixed
number of rows and columns so the static representation will be more efficient in terms
of memory. The important operations to be performed are to store and retrieve the data.
The students can be represented along the row and the subjects along the column.
student1
student2
student3
student50
Fig 4.10
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 137
Matrices
(2) Another example can be that of the supermarket survey. A certain supermarket wants
the data about their customers and the products that they buy. Neither the number of
customers nor the products that the customers can buy is fixed.
Let the row indicate the customer and the columns the product they buy. This will make
the products to be bought as fixed. So the number of columns will not increase or
decrease. However, the rows depend on the customers, hence they will surely vary. Here
we will certainly think of the linked list approach. The data is collected from five
different branches of the supermarket in the town.
The data is collected and analyzed daily. We have columns for all the products, but it is
not necessary that every customer should buy all the products. Infact on an average a
customer buys only 10% of the entire product range. The items that a customer does not
buy will be marked as zero. Here we can clearly see that most of the locations will be
marked as zero and will be non-informative.
In the next section, we will study another method of representing matrices which will
help us to remove this non-informative part.
The analysis is done so as to find out the demand for each product in the town. The data
is collected as different matrices in the five stores of the town. This data can be merged
together by adding the five matrices. The added matrix will give the demand for each
product in the town. Thus, addition and subtraction operations can be useful for such type
of problems.
(3) Till now we have seen applications illustrating the need of matrices and
demonstrating the use of operations like addition and subtraction. In this particular
example we will see how multiplication and transpose can be useful. A particular firm
has the following data regarding their machinery:
• A table representing the machines and the different parts used in them.
• A table representing the parts and the quantity of smaller parts used to build them.
Looking at the problem one can figure out that there will be two matrices as shown
below.
part1 part2 part3
machine1
2 1 4
machine2 1 5 3
machine3 1 1 1
3x3
Chapter 4
138 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
spart1 2 3 1
spart2 4 1 1
2x 3
The matrix in fig 4.11(b) indicates the number of smaller parts used to make the larger
parts of the machines.
Now the problem is to calculate the total number of parts required to make a particular
machine. Here we can find it by multiplying the two matrices. The first matrix is a 3 x
3 matrix while the second matrix is 2 x 3 matrix. According to the rules of matrix
multiplication the number of columns of the first matrix should be equal to the number
of rows of the second matrix. The above matrices do not satisfy the conditions. Now we
can use transpose function on the second matrix to make it a 3 x 2 matrix. After this
multiply the first and the transposed matrix to get the desired result.
machine1 part1 2 4
2 1 4
machine2 1 5 3 X part2 3 1
machine3 1 1 1 part3 1 1
3x 3 3x 2
The resultant matrix, which gives the total number of parts in the machine, is as follows:
tpart1 tpart2
machine1 11 13
machine2 20 12
machine 3 6 6
3x2
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 139
Matrices
Fig 4.12
Matrix representing the total number of parts.
4.4 Sparse Matrices
In the section 4.3.3, while studying the example to calculate the demand of products of a
supermarket we came across the matrix where the maximum entries where zero and
non-informative. It will not make any difference even if these entries are deleted. But
our representation did not allow us to do so. A matrix with many zero entries is known
as sparse matrix. There is no particular definition for the word many used in the
definition, but one does get the concept of sparse matrix.
As in the supermarket example suppose there were 100 products, if a customer buys on
an average 10 products then one can say that 90 locations per row are filled with zero.
This happens because in the representation we have seen so far, it is essential that every
row and column position have a value entered against it.
Let us consider a sparse matrix and represent it in both the ways. The matrix has three
rows, six columns and four nonzero values. In the normal representation we are suppose
to store all the twelve values of the matrix. This is shown in figure 4.13 (a).
But as shown in the fig 4.13(b) the sparse representation will have only four values
stored in it. The first array slot i.e. a[0][0] will have the maximum number of rows,
a[0][1] will have the maximum number of columns and a[0][2] will have the total
number of nonzero values present in the matrix. From the next slot onwards the actual
nonzero value are stored along with the row and column position they belong to.
As stated earlier all the values are placed in the list so that the rows are placed in
increasing order and for each row the columns are also in ascending order. This type of
ordering will help us while performing the various operations like addition and
multiplication.
1 0 0 21 0 0
a=
0 3 0 0 0 0
6 0 0 0 0 0
3x6
Chapter 4
140 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
a[0] 3 6 4
a[1] 1 1 1
a[2] 1 4 21
a[3] 2 2 3
a[4] 3 1 6
This representation will occupy 15 * 2 = 30 bytes, while the normal representation will
occupy 18 * 2 = 36 bytes. This difference will be more visible when there are more
number of rows and columns.
Now we will implement the sparse matrices. Again we will represent them in two
different ways: static and dynamic. In the static representation we will be using arrays
and for dynamic representation we will use linked list. In the static implementation we
will see how to create a matrix and then implement a function to find out the transpose of
the matrix. There are many other operations, which we have implemented in before. One
can try to implement them using the sparse matrix representation also. The basic
operations will remain the same but due to change in the representation the
implementation will also change.
Function
To create and print a sparse matrix. This is the static representation version using arrays.
Brief
In this function we will use a two dimensional array where the first dimension will be
equal to the number of non zero elements and the second dimension will be equal to
three(row, column and value). The user will input all the nonzero values along with the
row and column position for each matrix. This program also checks that the list is entered
in an ordered manner.
Program
/* This program creates a sparse matrix and prints it. It uses arrays to implement it.
Static allocation method is used. */
# include<stdio.h>
# include<stdlib.h>
# include<malloc.h>
int a[20][3];
/* This program creates the sparse matrix. It returns nothing and takes an array as
parameter. */
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 141
Matrices
/* The first row contains the information about the total number of rows, columns and
non-zero elements. The user enters this information. */
/* This part takes the information about non-zero elements one by one */
for(i=1;i<=a[0][2];i++)
{
printf("\nenter the row number");
scanf("%d",&r);
printf("\n enter the col number");
scanf("%d",&c);
if(r>j)
k=0;
if(r>=j && c >= k)
{
printf("\nenter the %d element",i+1);
scanf("%d",&a[i][2]);
a[i][0] = r;
a[i][1]= c;
}
else
{
printf("\nenter the valid format....rows / columns invalid");
getchar();
exit(0);
}
}
}
/* This function prints the given matrix. It returns nothing and requires an array to be
passed as a parameter. */
Chapter 4
142 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
void main()
{
crsmat(a);
print(a);
}
Analysis
In the crsmat() function there is a for loop which executes for n times where n is equal
to the number of maximum non zero elements present in the matrix. Hence the
complexity will be O(non zero terms).
Function
To form the transpose of a sparse matrix represented as an array.
Brief
In transpose of a matrix we are suppose to interchange the row and column position of
the element in the matrix. In our representation we have all the rows and columns in
ascending order. So we will find out elements in the first column and place them in the
first row of the transposed matrix, then the second column and so on. This way the
transposed matrix will also be in the ordered form.
If we interchange the elements from row to column then we will not be able to find out
the exact position of the element. For example if the first element in the 1 row and the 2
column with value 29(1,2,29) and the second element is (2,1,-2) then the first element
will become (2,1,29) and second element will be (1,2,-2).
According to our rules rows should be in ascending order, hence the second element
should occupy the first position in the transposed matrix, but if we transform according to
rows it will take the second position and hence we will have to reshuffle the elements.
But if the transformation is done as per columns then the elements will be in their
respective positions.
Program
/* This function finds the transpose of the given matrix. It returns nothing and requires
two arrays to be passed as parameters.*/
/* The maximum number of rows will be equal to the maximum number of columns in the
original matrix */
b[0][0] = a[0][1];
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 143
Matrices
/*The maximum number of columns will be equal to the maximum number of rows of the
original matrix */
b[0][1] = a[0][0];
for (i=1;i<=a[0][1];i++)
{
for(j=0;j<a[0][2];j++)
{
if(a[j][1] == i)
{
b[k][0] = a[j][1];
b[k][1] = a[j][0];
b[k][2] = a[j][2];
k=k+1;
}
}
}
}
Analysis
The computing time for the above algorithm is O(columns * number of non zero
terms). In the linked representation we will use the same nodes and method as in the
normal linked representation. In this case, we will input all the non-zero values only. We
will represent the matrix of fig 4.13, the representation will look as shown below.
The various values will be as follows:
trow = 3, tcol = 6, point will contain the address of the first row head node. The
values are a[1][1] = 1, a[1][4] = 21, a[2][2] = 3, a[3][1] = 6.
3 6 point
Fig 4.14
Linked representation of a sparse 3 x 2 matrix
Chapter 4
144 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
The main difference of this and the previous representation is that only nonzero values
have been stored in the list. This reduces the number of nodes. Rest everything remains
the same. The rows and columns are placed in ascending order.
Function
Brief
This program works in the similar fashion as the linked list representation works.
Program
# include <stdio.h>
# include <stdlib.h>
# include <malloc.h>
/* The colnode structure holds the values of the individual elements. The cno field stores
the column’s number the element belongs to. Value field stores the actual user input. The
next pointer points to another colnode. This pointer forms the linked list of the colnodes
*/
/* The structure rowhead is present at the beginning of each row. The field rno contains
the row number. The field nextc is a pointer that points to the first colnode of that row. It
joins the rowhead nodes to the elements. The pointer nextr points to the next rowhead
node of the matrix. This pointer forms the linked list of all the rowhead nodes*/
/* The listhead node is present at the top of the matrix. Each matrix has only one listhead
node. The field trow contains the value of the maximum number of rows present in the
matrix. The field tcol stores the value of the maximum number of columns the matrix can
have. The pointer point points to the first rowhead node. */
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 145
Matrices
head *mat1;
/* This function creates a sparse matrix using the dynamic allocation method. */
void crmat()
{
row *rtemp,*loc=NULL;
col *ctemp,*cloc = NULL;
int i=0,j=0,no,k=0;
/* This part of the program allocates memory to the listhead node and initializes the
other fields.*/
for(i=0;i<mat1->trow;i++)
{
rtemp = (row *)malloc(sizeof(row));
rtemp->rno = i+1;
if(loc == NULL)
{
mat1->point = rtemp;
loc = rtemp;
}
else
{
loc->nextr=rtemp;
loc = loc->nextr;
}
rtemp->nextr= NULL;
rtemp->nextc= NULL;
rtemp = NULL;
}
/* This part of the program allocates memory to the colnodes and links them at the
proper position */
loc = NULL;
loc = mat1->point;
Chapter 4
146 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
for(i=0;i<mat1->trow;i++)
{
printf("\nenter how many nodes are present in the %d row",i+1);
scanf("%d",&no);
for(j=0;j<no;j++)
{
ctemp->next = NULL;
if(cloc == NULL)
{
loc ->nextc = ctemp;
cloc = ctemp;
}
else
{
cloc->next = ctemp;
cloc = cloc->next;
}
}
cloc = NULL;
loc = loc-> nextr;
}
}
void print()
{
int i=0,j=0;
row *r;
col *c;
r = mat1->point;
c= r->nextc;
for(i=0;i< mat1->trow;i++)
{
while(c!=NULL)
{
printf("row:%d ,col: %d ,value: %d",i+1,c->cno,c->value);
c = c->next;
}
r = r->nextr;
c = r->nextc;
printf("\n");
}
}
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 147
Matrices
void main()
{
crmat();
print();
Analysis
This program has complexity O(number of rows * number of non zero elements)
i.e. O(m * number of non zero elements).
Thus sparse matrices can be represented using the static and dynamic forms. All the
operations can be implemented for the sparse matrices. As the matrix is represented in a
more compact format, implementation of the operations is more complicated and will
take more time. We find that there is a trade off between time, complexity and space. If
memory is saved using the sparse matrix then time is consumed and complexity of the
programs increase.
Examples
A square matrix has the same number of rows and columns. Some special square
matrices reflect the properties of a sparse matrix. We will see a few types of matrices,
which can be called, as sparse matrices.
A matrix ‘m’ is said to be diagonal if m(i,j) = 0 for i != j. All the elements other
than the diagonal are zero as shown in the fig 4.15.
2 0 0 0
0 1 0 0
a=
0 0 4 0
0 0 0 6 4x4
Fig 4.15
Diagonal matrix
In this matrix there are total sixteen elements and only four of them are non-zero. Such
types of matrices certainly require more memory if all the values are stored. Hence,
sparse representation is a better solution for them.
Chapter 4
148 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
A matrix ‘m’ is lower triangular if m(i,j) = 0 for i < j. (Refer figure 4.16), we can see
that the non-zero elements form a triangle in the lower part.
2 0 0 0
5 1 0 0
a=
5 3 4 0
4 2 7 0 4x4
Fig 4.16
Lower Triangular matrix
In this type of matrix, there are atleast six elements having the value zero.
A matrix ‘m’ is an Upper triangular if m(i,j) = 0 for i > j. (Refer figure 4.17). We can
see that the non-zero elements form a triangle in the lower part.
2 1 3 0
0 9 3 8
a=
0 0 2 3
0 0 0 0 4x4
Fig 4.17
Upper Triangular matrix
In this type of matrix, there are atleast six elements having the value zero.
These type of matrices are said to be sparse matrices. Any problem statement generating
such type of matrices can be represented using the above methods.
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 149
Matrices
SELF ASSESSMENT
Chapter 4
150 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
SUMMARY
♦ A m x n matrix is a table with m rows and n columns, where m and n are known as the
dimensions of the matrix.
♦ The various operations which can be performed on the matrices are addition,
subtraction, multiplication and transpose.
♦ The sum of two matrices is possible only if both have same dimensions i.e. the same
number of rows and the same number of columns. Sum of two matrices can be
expressed as follows :
n
c[i][j] = ∑a [ i ] [ k ] * b [ k ] [ j ] , 1 <= I <= m1, 1 <= j <= n2
K=1
♦ In transpose of a matrix the elements of rows and columns are interchanged. The
expression for transposed matrix is as follows:
♦ If a matrix has very less numbers of non zero values then the matrix is said to be a
sparse matrix. In this type of matrix it is not necessary to store all the values, only non
zero values are stored in the format (row, column ,value). Each element is uniquely
characterized by its row and column position.
♦ The examples of sparse matrices are diagonal matrix, upper triangular matrix and
lower triangular matrix.
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 151
Matrices
LAB EXERCISE
1) Draw a magic square of the given size (m x m). In a magic square the sum of each
rows and columns is the same. The square matrix size i.e. m should be odd numbered.
For example a 3 x 3 matrix or a 7 x 7 matrix, a 4 x 4 matrix is not allowed.
Procedure:
a) Start.
c) decrement row by one (row --) and increment column by one (column ++).
d) if (row is invalid and column is valid) then place element at row = m and column
will remain the same.
else
if (row is valid and column is invalid) then place the element at column = 0 and row
= 0.
else
if (row is invalid and column is invalid) then place the element at row = row + 2
and column = column – 1.
else
if (row is valid and column is valid and the position is already occupied ) then
place the element at row = row + 2 and column = column – 1.
e) if all the positions are filled then exit else goto step c
f) End.
Example a 3 x 3 matrix
sum
8 1 6 15
3 5 7 15
4 9 2 15
Sum 15 15 15
2) An insect is placed on a given square, in the middle of a tile floor in the rectangular
room of size nxm tiles. The insect wanders randomly from tile to tile throughout the
room. He moves from the present tile to any of the eight tiles surrounding him(unless
he is against the wall) with equal probability, how long will it take for the insect to
touch every tile of the floor at least once? This problem is tough to solve
mathematically. Computer can solve it easily. The technique is known as simulation.
We can simulate the problem as follows.
Chapter 4
152 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority
Matrices
The room with n x m tiles can be represented as a two dimensional array of n x m. All
the cells of this array are initialized to 0 in the beginning. The position of the insect on
the floor is represented by the co-ordinates (i, j).
Imove[1] = -1 jmove[1] = 1
Imove[2] = 0 jmove[2] = 1
Imove[3] = 1 jmove[3] = 1
Imove[4] = 1 jmove[4] = 0
Imove[5] = 0 jmove[5] = -1
Imove[6] = -1 jmove[6] = -1
Imove[7] = -1 jmove[7] = -1
Imove[8] = -1 jmove[8] = 0
Insect cannot move outside the room so that co ordinates which lead up a wall must be
ignored and a new combination must be performed.
Each time the square is entered the count for that square is entered the count for that
square is incremented, the non-zero entry shows the number of times the insect has
landed on that square so far. When every square is entered at least once the experiment is
complete.
Keep an iteration limit. The maximum number of squares the bug may enter during the
experiment. This assures that the program is not hanged.
Chapter 4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. 153