2

/edit: See here for an interesting discussion of the topic. Thanks @Dan


Using a(m,n) = 0 appears to be faster, depending of the size of matrix a, than a = zeros(m,n). Are both variants the same when it comes to pre-allocation before a loop?

Community
  • 1
  • 1
Fred S
  • 1,421
  • 6
  • 21
  • 37
  • You're right, I seem to have searched for the wrong keywords. Thank you. Will edit my main post in a few minutes, I'm on mobile right now. – Fred S Aug 13 '13 at 10:11
  • See also [this](http://undocumentedmatlab.com/blog/preallocation-performance/) for more on preallocation. – horchler Aug 13 '13 at 13:58

2 Answers2

5

They are definately not the same.

Though there are ways to beat the performance of a=zeros(m,n), simply doing a(m,n) = 0 is not a safe way to do it. If any entries in a already exist they will keep existing.

See this for some nice options, also consider doing the loop backwards if you don't mind the risk.

Community
  • 1
  • 1
Dennis Jaheruddin
  • 21,208
  • 8
  • 66
  • 122
  • Looping backwards seems interesting, I will try that. Apart from when `a` already exists, why else would `a(m,n)` not be safe? Am I safe to use `clear a; a(m,n) = 0;` for preallocation (ignoring the fact that using clear makes it slower again)? – Fred S Aug 13 '13 at 11:12
1

I think it depends on your m and n. You can check the time for yourself

tic; b(2000,2000) = 0; toc;
Elapsed time is 0.004719 seconds.
tic; a = zeros(2000,2000); toc;
Elapsed time is 0.004399 seconds.

tic; a = zeros(2,2); toc;
Elapsed time is 0.000030 seconds.
tic; b(2,2) = 0; toc;
Elapsed time is 0.000023 seconds.
Pavan K
  • 4,085
  • 8
  • 41
  • 72
  • Hmm that's a much smaller difference than what I experienced. I may have made a mistake in my benchmark. Will check once I'm back in my office. – Fred S Aug 13 '13 at 09:53
  • 4
    I wouldn't bet the farm on any timings measured in milliseconds on a PC. – High Performance Mark Aug 13 '13 at 09:54
  • 1
    As m and n increase you can see the difference. This is just an example. – Pavan K Aug 13 '13 at 09:55
  • I have indeed found a small mistake in my benchmarks, but I can reproduce what you wrote. It appears to be highly dependent on my matrices size. Dan posted a link to an interesting discussion with more in depth benchmarks. Thank you for your answer, Pavan. – Fred S Aug 13 '13 at 11:18
  • `zeros` may depend on the number of elements *and* for sufficiently large allocations [how many threads](http://www.mathworks.com/help/matlab/ref/maxnumcompthreads.html) Matlab supports on your computer. – horchler Aug 13 '13 at 14:10
  • I think by default it takes advantage of the multithreading unless you turn it off. Anyway I have a i7 CPU 860 @ 2.80GHz × 8! – Pavan K Aug 14 '13 at 09:42