Matlab from text file to sparse matrix.

Viewed 529

I have a huge text file in the following format:

1   2
1   3
1   10
1   11
1   20
1   376
1   665255
2   4
2   126
2   134
2   242
2   247

First column is the x coordinate while second column is the y coordinate. It indicates that if I had to construct a Matrix

M = zeros(N, N);
M(1, 2) = 1;
M(1, 3) = 1;
.
.
M(2, 247) = 1;

This text file is huge and can't be brought to main memory at once. I must read it line by line. And save it in a sparse matrix.

So I need the following function:

function mat = generate( path )
    fid = fopen(path);
    tline = fgetl(fid);
    % initialize an empty sparse matrix. (I know I assigned Mat(1, 1) = 1)
    mat = sparse(1);
    while ischar(tline)
        tline = fgetl(fid);
        if ischar(tline)
            C = strsplit(tline);
        end
        mat(C{1}, C{2}) = 1;
    end
    fclose(fid);
end

But unfortunately besides the first row it just puts trash in my sparse mat. Demo:

1 7
1 9
2 4
2 9

If I print the sparse mat I get:

   (1,1)        1
  (50,52)       1
  (49,57)       1
  (50,57)       1

Any suggestions ?

1 Answers
Related