help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: specifying matrices before filling with values


From: A S Hodel
Subject: Re: specifying matrices before filling with values
Date: Tue, 12 Nov 2002 20:41:37 -0600


On Tuesday, November 12, 2002, at 08:16  PM, Mike Miller wrote:

Here is a very important issue for efficient computation.  The use of
'for', as above, can sometimes be unavoidable (in other contexts), but
I've noticed something extremely important:  The new matrix ("anomaly"
above) should be created in advance with the desired size. In some work I
was doing just today, I noticed that this code...

for i=1:1000, rowvector = myfunction(rand(X)); Y(i,:)=rowvector; end

...ran very slowly when Y did not exist at the start of the loop. Doing
this...

Y=zeros(1000,4); for i=1:1000, rowvector = myfunction(rand(X)); Y(i,:)=rowvector; end

...instead sped the thing up *massively*!  IIRC, MATLAB also works this
way.  Having to resize the matrix seems to slow things down a *lot*.

This is because, in the first case, each time a new row is created, a new, larger, Y must be allocated from memory, the old Y copied into the new, the old Y deallocated, the new data copied into the new Y, and on to the next loop. In the second case, no memory allocation/deallocation is required at all since the first Y is large enough to hold all of the data.



-------------------------------------------------------------
Octave is freely available under the terms of the GNU GPL.

Octave's home on the web:  http://www.octave.org
How to fund new projects:  http://www.octave.org/funding.html
Subscription information:  http://www.octave.org/archive.html
-------------------------------------------------------------



reply via email to

[Prev in Thread] Current Thread [Next in Thread]