MATLAB: sparse matrices in matlab anamoly?

In summary, a sparse matrix in MATLAB is a type of matrix that contains a large number of zeros and is represented by only storing the non-zero elements and their corresponding indices. Sparse matrices can be created using the sparse() function and can significantly improve computation time and memory usage in MATLAB. They can be converted back to full matrices using the full() function. However, using sparse matrices in MATLAB may lead to slower execution times due to additional computational steps required to access and manipulate their elements compared to full matrices.
  • #1
manjuvenamma
102
0
In MATLAB, Why is sparse(rand(4)) not same as sprand(4)? Is it not supposed to be? What is the reason? Please see the interaction in MATLAB pasted below.

sprand(4)

ans =

(1,1) 0.8147

>> rand(4)

ans =

0.9058 0.0975 0.9649 0.4854
0.1270 0.2785 0.1576 0.8003
0.9134 0.5469 0.9706 0.1419
0.6324 0.9575 0.9572 0.4218

>> sparse(ans)

ans =

(1,1) 0.9058
(2,1) 0.1270
(3,1) 0.9134
(4,1) 0.6324
(1,2) 0.0975
(2,2) 0.2785
(3,2) 0.5469
(4,2) 0.9575
(1,3) 0.9649
(2,3) 0.1576
(3,3) 0.9706
(4,3) 0.9572
(1,4) 0.4854
(2,4) 0.8003
(3,4) 0.1419
(4,4) 0.4218
 
Physics news on Phys.org
  • #2
You haven't understood the meaning of sparse matrices. Sparse matrices store only those values that are NOT zero. Thereby, they decrease memory allocation. Your rand(4) function call didn't return any 0 value, so using sparse function on the answer has no affect.
https://in.mathworks.com/help/matlab/ref/sparse.html
 

1. What is a sparse matrix in MATLAB?

A sparse matrix in MATLAB is a type of matrix that contains a large number of zeros. It is represented by only storing the non-zero elements and their corresponding indices, thus saving memory and computation time.

2. How are sparse matrices created in MATLAB?

Sparse matrices can be created in MATLAB using the sparse() function. This function takes in the non-zero elements, their indices, and the size of the matrix as inputs and returns a sparse matrix.

3. How do sparse matrices affect computation in MATLAB?

Sparse matrices can significantly improve computation time and memory usage in MATLAB, especially for large matrices with a high number of zeros. This is because MATLAB has built-in algorithms that are optimized for handling sparse matrices.

4. Can sparse matrices be converted back to full matrices in MATLAB?

Yes, sparse matrices can be converted back to full matrices in MATLAB using the full() function. This function converts the sparse matrix to a full matrix by filling in the zeros with their corresponding values.

5. Are there any disadvantages to using sparse matrices in MATLAB?

The main disadvantage of using sparse matrices in MATLAB is that they require additional computational steps to access and manipulate their elements compared to full matrices. This can lead to slower execution times in certain cases.

Back
Top