Search code examples
matlabsparse-matrix

Forcing a specific size when using spconvert in Matlab


I am loading a sparse matrix in MATLAB using the command:

A = spconvert(load('mymatrix.txt'));

I know that the dimension of my matrix is 1222 x 1222, but the matrix is loaded as 1220 x 1221. I know that it is impossible for MATLAB to infer the real size of my matrix, when it is saved sparse.

A possible solution for making A the right size, is to include a line in mymatrix.txt with the contents "1222 1222 0". But I have hundreds of matrices, and I do not want to do this in all of them.

How can I make MATLAB change the size of the matrix to a 1222 x 1222?


Solution

  • I found the following solution to the problem, which is simple and short, but not as elegant as I hoped:

    A = spconvert(load('mymatrix.txt'));
    if size(A,1) ~= pSize || size(A,2) ~= pSize
        A(pSize,pSize) = 0;
    end
    

    where pSize is the preferred size of the matrix. So I load the matrix, and if the dimensions are not as I wanted, I insert a 0-element in the lower right corner.