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:

 

Sparse Matrices in MATLAB

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.

Similar Reads

Sparse Function Syntax:

Syntax: s = sparse(matrix)...

Creating an Empty Sparse Matrix:

...

Generating a Sparse Matrix of a Definite Size:

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....

Convert a Sparse Matrix to a Full Matrix:

...