Search code examples
matlabsparse-matrix

How to save a sparse matrix to mat file in matlab


I want to save two sparse matrix Y and R to a mat file. However, when I run the following code, I found out that the twomatrices.mat contains two full matrices instead of sparse matrices. Do does .mat file only allow full matrices to be included?

save('twomatrices.mat', 'Y', 'R');

Solution

  • Be sure that you actually create sparse matrices: e.g., the following code snippet works fine and stores the matrices as sparse double matrices:

    n = 5;
    Y = sparse(1:n,1:n,1);
    R = sparse(1:n,1:n,2);
    save('twomatrices.mat', 'Y', 'R');
    
    clear
    load('twomatrices.mat')
    Y
    
    
    Y =
    
       (1,1)        1
       (2,2)        1
       (3,3)        1
       (4,4)        1
       (5,5)        1