Time for Matrix Initializing
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Jan
il 3 Lug 2013
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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!