Time for Matrix Initializing
2 次查看(过去 30 天)
显示 更早的评论
Hi!
I create a cell of 700 elements, each of which is a sparse matrix 2000 * 2000 (most of the values will be zero). When I initialize to zero:
for iCell = 1:700 P{iCell } = sparse(zeros(2000, 2000)); end
It takes a non negligible time compared to all the other calculations my program makes in the next lines. Is it normal, given I only create (admittedly big) empty matrices?
Is there a little trick I could use decease the computation time? I tried what is written here: http://stackoverflow.com/questions/14169222/faster-way-to-initilize-arrays-via-empty-matrix-multiplication-matlab
but it didn't work.
Thanks in advance!
0 个评论
采纳的回答
Jan
2013-7-3
Converting the full matrix zeros(2000, 2000) to a sparse matrix wastes time, because the full matrix is created explicitly in each iteration. This would be faster:
P = cell(1, 700); % Pre-allocate the cell array
for iCell = 1:700
P{iCell} = sparse(2000, 2000);
end
Even better you'd define the sparse matrices with the correct number of elements directly, e.g.:
sparse([],[],[], 2000, 2000, 971)
A nicer method, which is unfortunately not faster in the final program, is:
P = cell(1, 700); % Pre-allocate the cell array
P(:) = {sparse(2000, 2000)};
Now the cell elements are shared data copies of the same array. This is faster to initialize, but accessing the matrices will create a deep copy during the program runs, such that the total run-time is longer.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!