2
votes

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?

3

3 Answers

2
votes

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.

1
votes

Sorry, this post is more a pair of clarifying questions than it is an answer.

First, is the issue with the 'load' command or with 'spconvert'? As in, if you do

B = load('mymatrix.txt') 

is B the size you expect? If not, then you can use 'textread' or 'fread' to write a function that creates the matrix of the right size before inputting into 'spconvert'.

Second, you say that you are loading several matrices. Is the issue consistent among all the matrices you are loading. As in, does the matrix always end up being two rows less and one column less than you expect?

1
votes

I had the same problem, and this is the solution I came across:

nRows = 1222;
nCols = 1222;
A = spconvert(load('mymatrix.txt'));

[i,j,s] = find(A);
A = sparse(i,j,s,nRows,nCols);

It's an adaptation of one of the examples here.