Info

This question is closed. Reopen it to edit or answer.

Why the computational time during initialization to ones matrix is lower than zero matrix when you use preallocation in Matlab?

2 views (last 30 days)
I created two sets of functions, prealloczeros.m and preallocones.m as I wanted to compare the computational time taken by Matlab (Matlab Online R2020a) when you preallocate the matrix as zeros matrix and ones matrix.
The program for both alongwith their computational time is as given below:
function prealloczeros
n = 5000;
A = zeros(n,n);
for ii = 1:n
for jj = 1:n
A(ii,jj) = ii*jj;
end
end
end
>> tic; prealloczeros ; toc
Elapsed time is 0.381329 seconds.
function preallocones
n = 5000;
A = ones(n,n);
for ii = 1:n
for jj = 1:n
A(ii,jj) = ii*jj;
end
end
end
>> tic; preallocones ; toc
Elapsed time is 0.367676 seconds.

Answers (1)

Walter Roberson
Walter Roberson on 6 Sep 2020
Using a better timing test, I confirm the overall result of testing those two routines
N = 25;
t0 = zeros(1,N);
t1 = zeros(1,N);
f0 = @() prealloczeros();
f1 = @() preallocones();
for K = 1 : N; t0(K) = timeit(f0,0); end
for K = 1 : N; t1(K) = timeit(f1,0); end
plot(t0, 'b', 'DisplayName', 'Zeros');
hold on
plot(t1, 'k', 'DisplayName', 'Ones');
hold off
legend show
There is a clear separation in the plots, with the prealloczeros routine clearly belong slower.
However, if you time the zeros and ones routine without the framework, then zeros() is much faster. If you change the double for loop to use 1:n in one of them and just n in the other, then zeros() is much faster (though the ratio depends upon which of the two indices you use.)
Now if you change the assignment subscript order to
A(jj,ii) = ii*jj;
with jj being your inner loop, then you are assigning down columns, which is faster than assigning across rows. The results then are not as clear: the plots overlap each other, but on average zeros() is a little faster than ones().
So, it appears that ones() is not inherently faster than zeros() -- though I agree that at first look your test does suggest that -- your observation of relative timings of those two functions is correct!
But it looks like instead of it being a matter of zeros() versus() ones() themselves, it appears to be an oddity of optimization! zeros() by itself is faster than ones(), and in most arrangements tests as faster, but not in the particular code you tested !

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!