Sparse Matrix Assignment becomes very slow in Matlab

前端 未结 2 1476
伪装坚强ぢ
伪装坚强ぢ 2021-01-20 11:17

I am filling a sparse matrix P (230k,290k) with values coming from a text file which I read line by line, here is the (simplified) code

while ...
                    


        
2条回答
  •  一整个雨季
    2021-01-20 12:12

    There's a sixth input argument to sparse that tells the number of nonzero elements in the matrix. That's used by Matlab to preallocate:

    S = sparse(i,j,s,m,n,nzmax) uses vectors i, j, and s to generate an m-by-n sparse matrix such that S(i(k),j(k)) = s(k), with space allocated for nzmax nonzeros.

    So you could initiallize with

    P = sparse([],[],[],230e3,290e3,nzmax);
    

    You can make a guess about the number of nonzeros (perhaps checking file size?) and use that as nzmax. If it turns you need more nonzero elements in the end, Matlab will preallocate on the fly (slowly).

提交回复
热议问题