A sparse matrix is one where there are many zero elements. For example, a matrix
ID: 3536431 • Letter: A
Question
A sparse matrix is one where there are many zero elements. For example, a matrix A is as
follows:
A = 3 0 4 0 5
0 0 2 0 1
1 0 0 0 2
0 0 0 0 0
Matrix A has 4 rows and 5 columns. Of the 20 places in the matrix, 13 of them are zero. We
represent this matrix as a sorted list of <row, column, value> triples as shown below. The matrix
operations become operations on lists.
row column value
1 1 3
1 3 4
1 5 5
2 3 2
2 5 1
3 1 1
3 5 2
Processing Notes
(i) The list of values should be kept ordered by column within rows.
(ii) The test plan for an array-based implementation should have been based on the shape of
the matrices. A test plan for a list implementation should include cases dealing with the
length of the list (empty, only one item, etc.).
Upload in the URCourses
(i) Source Code (Assignment1PartB.CPP)
(ii) A DataOutPartB.txt file that your program created
(iii) The screen of your test (Assignment1PartBTest.JPG)
Explanation / Answer
#include <iostream>
using namespace std;
int main()
{
int **a,**sp;
// a matirx
// sp sparse matrix
// n -- rows in matrix
// m -- column in matrix
//count -- counting non zero value in matrix
//s -- no of entry in spare matrix
int n,m,i,j,count=0,s=0;
cout <<"Enter the no of rows in matrix ";
cin>>n;
cout <<"Enter the no of column in matrix ";
cin>>m;
//memory allocated for elements of rows.
a = new int *[n];
//memory allocated for elements of each column
for(i = 0 ; i < n ; i++ )
a[i] = new int[m];
for(i = 0 ; i < n ; i++ )
for(j = 0 ; j < m ; j++ )
{
cout<<"Enter a["<< i <<"]["<<j<<"]value : " ;
cin>>a[i][j];
if(a[i][j]!=0)
count++;
}
cout<<" ENTERED MATRIX IS ";
for(i = 0 ; i < n ; i++ )
{
for(j = 0 ; j < m ; j++ )
cout<<a[i][j]<<" ";
cout<<" ";
}
if(count!=0)
{
cout<<" No of item in Sparse matrix : "<<count<<" ";
//memory allocated for sparse matrix.
sp = new int *[count];
//memory allocated for elements of each column
for(i = 0 ; i < count ; i++ )
sp[i] = new int[3];
//SPARSE MATRIX
for(i = 0 ; i < n ; i++ )
{
for(j = 0 ; j < m ; j++ )
{
if(a[i][j]!=0)
{
sp[s][0]=i;
sp[s][1]=j;
sp[s][2]=a[i][j];
s++;
}
}
}
//Display
cout<<" SPARSE MATRIX IS ";
cout<<" ROW COLUMN VALUE ";
for(i = 0 ; i < s ; i++ )
{
for(j = 0 ; j < 3 ; j++ )
cout<<sp[i][j]<<" ";
cout<<" ";
}
}
else
cout<<" Sparse Matrix is Empty ";
//free the allocated memory for matrix
for( int i = 0 ; i < n ; i++ )
delete [] a[i] ;
delete [] a;
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.