Open In App

Sparse Matrices in MATLAB

Last Updated : 28 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Matrices are 2-dimensional arrays that are the most popular data type in MATLAB. A matrix can contain theoretically infinite elements as long as the computer has the required memory. In practice, when dealing with large data, there are scenarios when the majority of data contains zeroes as elements and this results in memory wastage. 

As a resolution, sparse matrices are created. A sparse matrix is a representation of a matrix in which all zero elements are removed and non-zero elements are stored as row, column, and value triplet. 

In this article, we shall see how to create a sparse matrix, convert an existing matrix to a sparse matrix, etc.

Sparse Function Syntax:

Syntax:

s = sparse(matrix)

The above method converts an existing matrix into a sparse matrix. See the following example.

Example 1:

Matlab




% MATLAB code for 7 by 7 identity matrix
identity = eye(7)
  
% Converting identity into a sparse matrix
s = sparse(identity)


Output:

 

Creating an Empty Sparse Matrix:

MATLAB provides the option to create a sparse matrix of all zeroes of a definite size. The same can be done using the sparse command only, this time passing two arguments, one for row size and the other for column size. See the below example.

Example 2:

Matlab




% MATLAB code for 3 by 5 identity matrix
sps = sparse(3,5);
disp(sps)


Output:

This code creates a sparse matrix of all zeroes of size 3×5. 

 

Generating a Sparse Matrix of a Definite Size:

The sparse function also converts values for rows, columns, and values into a sparse matrix of pre-defined length. As can be seen in the code below where three nonzero elements are added to a sparse matrix of size 23 by 23.

Example 3:

Matlab




% MATLAB code for  3 by 5 identity matrix
row = [1 13 23];
column = [5 7 17];
values = [23 31 999];
size = 23;
sps = sparse(row,column,values,size,size);
disp(sps)


Output:

 

Convert a Sparse Matrix to a Full Matrix:

The full () function takes input from a sparse matrix and converts it back into a regular, full-sized matrix. 

Example 4:

Matlab




% MATLAB code for 3 by 5 identity matrix
row = [1 3 5];
column = [5 6 7];
values = [23 31 999];
size = 7;
sps = sparse(row,column,values,size,size);
disp(sps)
  
% Converting to full matrix
matrix = full(sps);
fprintf("Full matrix: \n")
disp(matrix)


Output:

The above code first generated a sparse matrix of size 7×7 and then, converts it back to a full matrix.

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads