You are on page 1of 2

Computer Programming

Fall 2014
Assignment#2
Submission date: Wednesday October 22, 2014
In this task you would implement the matrix addition and multiplication of sparse
matrices. A matrix is called sparse if most of its entries are 0. One way to save space is to
store only the non-zero values along with their column information. For example
Consider the following sparse matrix
4
0
8
0
0
7
0
0
3
0
0
0
0
0
0
6
Its compact representation is
0
1
0
3

4
7
3
6

Where it represents that in 0th row the first non zero entry is at column 0 and its value is 4
and second entry is at column 2 and its value is 8
In this task your input would be a file which contains two sparse matrices. The first line
of the file would give the dimensions of the matrix and following lines would contain the
non-zero entries of the sparse matrix in each row. Once the entries of a matrix end, the
next line would contain the information about the second matrix in the same format.
Below is a sample file.
4
2
1
1
1
4
2
1
1
1

4
0
1
0
3
4
0
2
0
3

4
7
3
6

2
3
7
2

Its first line shows that matrix has 4 rows and 4 columns. Next 4 lines contain the data of
each row. First entry of each row tells number of non-zero values in the current row. For

example second line of this file tells that the first row has 2 non-zero data values and first
value is 4 at column 0 second value is 8 at column 2. When the data of first matrix ends,
the data of second matrix starts from the very next line in the same file and in the same
format.
Your task is to read these files store the sparse matrices in their compact form and if they
are compatible for addition and/or multiplication, compute the result of addition and
multiplication. In the end output the resultant matrices. Note that the resultant matrices
must also be in their compact representation. For example below is the result of their
addition in its compact form
0
1
0
3

6
7
10
8

2
2

8
3

And result of multiplication in their compact form is


0
2
0
3

29
21
6
12

20

15

Define a struct matrixEntry to store the column number and value of a non-zero matrix
entry. Also define a struct sparseMatrix which has a 2D pointer of type matrixEntry to
store the 2-dimensional dynamic array of matrix entries, the dimensions of matrix and an
integer pointer to store the sizes of non-zero entries in each row. Perform the addition and
multiplication of sparse matrices using the above mentioned structures.

You might also like