Effacer les filtres
Effacer les filtres

Time for Matrix Initializing

1 vue (au cours des 30 derniers jours)
Martin
Martin le 3 Juil 2013
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!

Réponse acceptée

Jan
Jan le 3 Juil 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.
  1 commentaire
Martin
Martin le 4 Juil 2013
Great Jan, it changes everything. So Matlab had to check every value of zeros(2000, 2000) before making it sparse?
Thanks again.
Martin

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Sparse Matrices dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by