I am performing operations on sparse data. When I copy a single row of my sparse matrix, the resulting sparse matrix allocates far more memory than is actually needed. When I copy multiple rows of data from the sparse matrix, MATLAB allocates a segment of memory that is larger than the block of memory taken up by the original sparse matrix. However, when I copy a column from my original sparse matrix, MATLAB allocates the right amount of memory.
The following code illustrates the problem:
A=sprand(100,1000,0.01); %Create a random sparse matrix.
[mA,nA]=size(A);Nbites_A = 8*nzmax(A) + 4*(nzmax(A)+nA+1); %total number of bytes required to store a sparse matrix
B=A(1,:); %Copy one row from A
[mB,nB]=size(B);Nbites_B = 8*nzmax(B) + 4*(nzmax(B)+nB+1); %total number of bytes required to store a copy of one row of a sparse matrix
C=A([1 1 2 2 3 3],:); %Copy six rows from A
[mC,nC]=size(C);Nbites_C = 8*nzmax(C) + 4*(nzmax(C)+nC+1); %total number of bytes required to store a copy of six rows of a sparse matrix
D=A(:,10); %Copy one column from A
[mD,nD]=size(D);Nbites_D = 8*nzmax(D) + 4*(nzmax(D)+nD+1); %total number of bytes required to store a copy of a column of a sparse matrix
whos A B C D
In the above code, I create a sparse matrix A. The variable B is a copy of one row of A. The variable C is a copy of six rows of A. The variable D is a copy of one column of A. The output of WHOS indicates that B and C allocate far more memory than is required to store the elements of the sparse matrix A. Why is MATLAB allocating so much memory for B and C?
Best Answer