在Matlab中稀疏矩阵分配变得非常慢 [英] Sparse Matrix Assignment becomes very slow in Matlab
问题描述
我正在用来自文本文件的值填充稀疏矩阵P(230k,290k),我逐行读取,这是(简化的)代码
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 ...
C = textscan(text_line,'%d','delimiter',',','EmptyValue', 0);
line_number = line_number+1;
P(line_number,:)=C{1};
end
我遇到的问题是,在一开始的时候
the problem I have is that while at the beginning the
P(line_number,:)=C{1};
语句很快,几千行变得非常慢之后,我想是因为Matlab需要找到每次分配的内存空间.有没有一种方法可以用稀疏矩阵预先分配内存?我不这么认为,但也许我错过了一些东西.
statement is fast, after a few thousands lines become exterely slow, I guess because Matlab need to find the memory space to allocate every time. Is there a way to pre-allocate memory with sparse matrixes? I don't think so but maybe I am missing something. Any other advise which can speed up the operation (e.g. having a lot of free RAM can make the difference?)
推荐答案
到目前为止,生成稀疏矩阵的最快方法是同时加载所有值,然后在一次调用S = sparse(i,j,s,m,n)
语法调用sparse
.
By far the fastest way to generate a sparse matrix wihtin matlab is to load all the values in at once, then generate the sparse matrix in one call to sparse
. You have to load the data and arrange it into vectors defining the row and column indices and values for each filled cell. You can then call sparse
using the S = sparse(i,j,s,m,n)
syntax.
这篇关于在Matlab中稀疏矩阵分配变得非常慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!