Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Sparse Matrix in Data Structure

Last Updated on May 5, 2023 by Prepbytes

A sparse matrix in data structure is an important concept in data structures and algorithms, providing an efficient way to store and process large matrices Sparse matrices are widely used in many fields, including scientific computing, machine learning, and image processing, where large matrices arise frequently.

What is Sparse Matrix in Data Structure?

In computer science, a sparse matrix in the data structure is a matrix that has a large number of zero values compared to its total number of elements. Storing these matrices using a dense array representation would be inefficient in terms of both memory and computation time. To overcome this problem, sparse matrices can be represented using a more efficient data structure that only stores the non-zero elements. This can save memory and computation time for certain types of operations, such as matrix multiplication and inversion, and is an important concept in data structures and algorithms.

Representation of Sparse Matrix in Data Structure

Sparse matrix in data structure can be represented in two ways:

  1. Array representation
  2. Linked list representation
  • Array Representation of Sparse Matrix in Data Structure
    Storing a sparse matrix in a 2D array can result in a lot of memory wastage because zero elements in the matrix do not carry any useful information, yet they occupy memory space. To overcome this limitation and optimize memory usage, we can represent a sparse matrix by only storing its non-zero elements. This approach reduces both traversal time and storage space requirements. By storing only the non-zero elements, we can achieve a more efficient representation of sparse matrices in data structures.

    In the 2D array representation of a sparse matrix, there are typically three fields used to store the relevant information.
    The given below are fields of the array representation of the sparse matrix:

    • Row index field: This field stores the row indices of non-zero elements in the matrix.
    • Column index field: This field stores the column indices of non-zero elements in the matrix.
    • Value field: This field stores the actual values of the non-zero elements in the matrix.

    Implementation of array representation of the sparse matrix in data structure:

    #include <iostream>
    using namespace std;
    
    const int MAX = 100;
    
    int main() {
        int sparse_matrix[4][5] = {  
            {0 , 0 , 6 , 0 , 9 },  
            {0 , 0 , 4 , 6 , 0 },  
            {0 , 0 , 0 , 0 , 0 },  
            {0 , 1 , 2 , 0 , 0 }  
        };
    
        int rows = 4, cols = 5;
        int size = 0;
    
        // count the number of non-zero elements
        for(int i=0; i<rows; i++) {
            for(int j=0; j<cols; j++) {
                if(sparse_matrix[i][j] != 0) {
                    size++;
                }
            }
        }
    
        // initialize arrays to store row, col, and value
        int row[size], col[size], value[size];
        int k = 0;
    
        // store the non-zero elements in arrays
        for(int i=0; i<rows; i++) {
            for(int j=0; j<cols; j++) {
                if(sparse_matrix[i][j] != 0) {
                    row[k] = i;
                    col[k] = j;
                    value[k] = sparse_matrix[i][j];
                    k++;
                }
            }
        }
    
        // display the sparse matrix
        cout << "Array Representation of Sparse Matrix:" << endl;
        cout << "Row\tCol\tValue" << endl;
        for(int i=0; i<size; i++) {
            cout << row[i] << "\t" << col[i] << "\t" << value[i] << endl;
        }
    
        return 0;
    }
    

    Explanation of array representation of the sparse matrix in data structure:
    The array representation of the sparse matrix in the data structure program converts a given matrix into its array representation where the non-zero elements of the matrix are stored in separate arrays for row, column, and value. It first counts the number of non-zero elements in the matrix, then initializes the arrays and stores the non-zero elements in them. Finally, it displays the array representation of the matrix. This program can reduce the storage space required for large matrices with many zero elements.

  • Linked List Representation of Sparse Matrix in Data Structure
    The sparse matrix in data structure can be represented using a linked list data structure, which offers the advantage of lower complexity when inserting or deleting a node compared to an array.

    The linked list representation differs from the array representation in that each node has four fields, which are:

    • Row: It indicates the index of the row where the non-zero element is located.
    • Column: It indicates the index of the column where the non-zero element is located.
    • Value: It represents the value of the non-zero element located at the index (row, column).
    • Pointer to Next node: It stores the memory address of the next node in the linked list.

    Implementation of linked list representation of sparse matrix:

    #include <iostream>
    using namespace std;
    
    class Node {
    public:
        int col;
        int val;
        Node* next;
    };
    
    class SparseMatrix {
    private:
        int m, n; // dimensions of matrix
        Node** rows;
    public:
        SparseMatrix(int rows, int cols) {
            m = rows;
            n = cols;
            this->rows = new Node * [m];
            for (int i = 0; i < m; i++) {
                this->rows[i] = NULL;
            }
        }
        void insert(int i, int j, int val) {
            if (i < 0 || i >= m || j < 0 || j >= n) {
                cout << "Invalid index!" << endl;
                return;
            }
            Node* node = new Node;
            node->col = j;
            node->val = val;
            node->next = NULL;
            if (rows[i] == NULL) {
                rows[i] = node;
            }
            else {
                Node* prev = NULL;
                Node* curr = rows[i];
                while (curr != NULL && curr->col < j) {
                    prev = curr;
                    curr = curr->next;
                }
                if (curr != NULL && curr->col == j) {
                    curr->val = val;
                    delete node;
                }
                else {
                    node->next = curr;
                    if (prev == NULL) {
                        rows[i] = node;
                    }
                    else {
                        prev->next = node;
                    }
                }
            }
        }
        void display() {
            for (int i = 0; i < m; i++) {
                Node* curr = rows[i];
                for (int j = 0; j < n; j++) {
                    if (curr != NULL && curr->col == j) {
                        cout << curr->val << " ";
                        curr = curr->next;
                    }
                    else {
                        cout << "0 ";
                    }
                }
                cout << endl;
            }
        }
        ~SparseMatrix() {
            for (int i = 0; i < m; i++) {
                Node* curr = rows[i];
                while (curr != NULL) {
                    Node* temp = curr;
                    curr = curr->next;
                    delete temp;
                }
            }
            delete[] rows;
        }
    };
    
    int main() {
        SparseMatrix mat(3, 3);
        mat.insert(0, 0, 1);
        mat.insert(0, 1, 0);
        mat.insert(0, 2, 0);
        mat.insert(1, 0, 0);
        mat.insert(1, 1, 2);
        mat.insert(1, 2, 0);
        mat.insert(2, 0, 0);
        mat.insert(2, 1, 0);
        mat.insert(2, 2, 3);
        mat.display();
        return 0;
    }
    

    Explanation of linked list representation of the sparse matrix:
    In the implementation of a linked list representation of a sparse matrix, the Node class represents a node in the linked list for a particular row. The SparseMatrix class contains a dynamic array of pointers to nodes, where each pointer points to the head of the linked list for a particular row. The insert function inserts a new element into the matrix by creating a new Node and inserting it into the appropriate linked list, sorted by column index. The display function prints out the entire matrix by iterating over each row and column and checking the linked list for each row to see if there is a corresponding element

Conclusion
In conclusion, a sparse matrix in data structure is a type of matrix that contains a significant number of zero values. To represent such matrices efficiently, we use a data structure that can store only the non-zero values and their corresponding row and column indices. One popular data structure for representing sparse matrices is the linked list. The linked list representation of a sparse matrix allows for efficient insertion and deletion operations, as well as lower storage requirements compared to dense matrix representations. By using the appropriate data structure, we can optimize the storage and processing of sparse matrices in various applications.

Frequently Asked Questions(FAQs)

Q1. What is the difference between a dense matrix and a sparse matrix?
Ans: A dense matrix is a matrix in which a large proportion of the elements are non-zero, while a sparse matrix is a matrix in which a large proportion of the elements are zero.

Q2. What is the advantage of using a sparse matrix representation over a dense matrix representation?
Ans: The advantage of using a sparse matrix representation is that it can save memory and computation time by only storing the non-zero elements of the matrix. This is especially beneficial for very large matrices with a high proportion of zero elements.

Q3. What are some common operations that can be performed more efficiently on a sparse matrix than on a dense matrix?
Ans: Some common operations that can be performed more efficiently on a sparse matrix include matrix multiplication, matrix inversion, and solving linear equations.

Q4. What are some common data structures used to represent sparse matrices?
Ans: Some common data structures used to represent sparse matrices include the compressed sparse row (CSR) format, compressed sparse column (CSC) format, and linked list format.

Q5. How can I efficiently perform matrix multiplication on a sparse matrix?
Ans: Matrix multiplication on a sparse matrix can be performed efficiently using specialized algorithms, such as the CSR or CSC matrix multiplication algorithms. These algorithms take advantage of the sparse structure of the matrices to reduce the number of arithmetic operations required.

Leave a Reply

Your email address will not be published. Required fields are marked *