help-octave
[Top][All Lists]
Advanced

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

specifying matrices before filling with values


From: Mike Miller
Subject: specifying matrices before filling with values
Date: Tue, 12 Nov 2002 20:16:05 -0600 (CST)

On Wed, 13 Nov 2002, Hein Zelle wrote:

> Unrelated question: is there a way to do the following without using a
> for loop?
>
> a = [1, 2; 3, 4];
> b = mean(a);
>
> for r = 1:2
>   anomaly(r,:) = a(r,:) - b
> endfor


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*.

I'm sure this is one of those well-known things for most of you, but it
may be helpful for those who haven't seen it before. ;-)

Mike



-------------------------------------------------------------
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]