I have written a small loop in matlab to generate a random NxN matrix. The loop is
tic
for i=1:10000
u=rand(1,10000);
tau(i,:)=d.*(u(1,:)-0.5);
end
toc
I first tried the loop routine only once,
u=rand(1,10000);
tau=d.*(u(1,:)-0.5);
which gave me tau in 0.000169 seconds. I assumed that the loop then would take about 1.69s. It didn’t, it took 555.018280s with the fans going wild.
Is there
a) a reason why the speed is not linearly related to the number of iterations?
b) a reason to why it takes so much longer to do the routine many times
c) a way to speed this one up (I actually would like to generate larger matrices), for instance a better loop or way to give me, say, a 1’000’000×1’000’000 matrix of the same kind?
You have firstly to pre-allocate your matrix
tau, i.e.otherwise matlab will continuously re-allocate it in regions where there is sufficiently free memory (=> find a region with sufficiently free space + hard copy).
In general, you would achieve better performance vectorizing the whole process:
EDIT: Above all, listen to the wise advice of Rody in the comment below. (In any case, I suppose that
rand(a,b)would run a little faster thanaserial executions ofrand(1,b)).