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?

2
  • 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. Commented Aug 13, 2013 at 10:11
  • See also this for more on preallocation. Commented Aug 13, 2013 at 13:58

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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)?
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. 

6 Comments

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.
I wouldn't bet the farm on any timings measured in milliseconds on a PC.
As m and n increase you can see the difference. This is just an example.
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.
zeros may depend on the number of elements and for sufficiently large allocations how many threads Matlab supports on your computer.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.