Open In App

Implement a Sparse Matrix Representation and Operations in Java

A matrix with a high proportion of zero members is called a Sparse Matrix. Memory and computing resources may be conserved by effectively representing and manipulating sparse matrices. Java provides many methods for doing fundamental operations and representing sparse matrices.

In this article, we will learn to sparse matrix representation and operations in Java.



Implementation of a Sparse Matrix Representation

The key idea is to use a data structure that only keeps the non-zero items and their row and column indices to describe a sparse matrix. Typical depictions include:

Program to Sparse Matrix Representation and Operations

Let’s use an array of arrays to represent a sparse matrix and carry out some fundamental operations:






//Java Program to represent a sparse matrix and some fundamental operations
import java.util.HashMap;
  
class SparseMatrix {
    private final int rows;
    private final int cols;
    private final HashMap<Integer, HashMap<Integer, Integer>> matrixElements;
  
    // Constructor to initialize the sparse matrix
    public SparseMatrix(int rows, int cols) {
        this.rows = rows;
        this.cols = cols;
        this.matrixElements = new HashMap<>();
    }
  
    // Function to insert a value into the sparse matrix
    public void insert(int row, int col, int value) {
        if (row >= 0 && row < rows && col >= 0 && col < cols) 
        {
            matrixElements.computeIfAbsent(row, k -> new HashMap<>()).put(col, value);
        
        else 
        {
            System.out.println("Invalid row or column index");
        }
    }
  
    // Function to get the value at a specific position in the sparse matrix
    public int get(int row, int col) 
    {
        return matrixElements.getOrDefault(row, new HashMap<>()).getOrDefault(col, 0);
    }
  
    // Function to print the sparse matrix
    public void print() 
    {
        for (int i = 0; i < rows; i++) 
        {
            for (int j = 0; j < cols; j++) 
            {
                System.out.print(get(i, j) + " ");
            }
            System.out.println();
        }
    }
  
    // Function to add two sparse matrices
    public SparseMatrix add(SparseMatrix otherMatrix) 
    {
        if (this.rows != otherMatrix.rows || this.cols != otherMatrix.cols) 
        {
            System.out.println("Matrix dimensions don't match for addition.");
            return null;
        }
  
        SparseMatrix resultMatrix = new SparseMatrix(rows, cols);
  
        for (int i = 0; i < rows; i++) 
        {
            for (int j = 0; j < cols; j++) 
            {
                int sum = this.get(i, j) + otherMatrix.get(i, j);
                if (sum != 0) {
                    resultMatrix.insert(i, j, sum);
                }
            }
        }
        return resultMatrix;
    }
}
  
public class Main 
{
    public static void main(String[] args) 
    {
        // Example Usage
        SparseMatrix matrix1 = new SparseMatrix(3, 3);
        matrix1.insert(0, 0, 1);
        matrix1.insert(0, 2, 2);
        matrix1.insert(1, 1, 3);
  
        SparseMatrix matrix2 = new SparseMatrix(3, 3);
        matrix2.insert(0, 0, 4);
        matrix2.insert(0, 2, 5);
        matrix2.insert(1, 1, 6);
  
        // Add matrices
        SparseMatrix resultMatrix = matrix1.add(matrix2);
  
        // Print matrices
        System.out.println("Matrix 1:");
        matrix1.print();
  
        System.out.println("\nMatrix 2:");
        matrix2.print();
  
        System.out.println("\nThe Resultant Matrix (Sum of Matrix 1 and Matrix 2): ");
        if (resultMatrix != null) {
            resultMatrix.print();
        }
    }
}

Output
Matrix 1:
1 0 2 
0 3 0 
0 0 0 

Matrix 2:
4 0 5 
0 6 0 
0 0 0 

The Resultant Matrix (Sum of Matrix 1 and Matrix 2): 
5 0 7 
0 9 0 
0 0 0 

Explanation of the above Program:

Complexity of the above Program:

Time Complexity:

  • Insertion: HashMap’s computeIfAbsent yields an average time of O(1).
  • Average retrieval time (HashMap’s get) is O(1).
  • Addition: O(rows * cols) since each element is only iterated through once.

Space Complexity:

  • O(non-zero elements) since the HashMap only contains non-zero items.

Article Tags :