From help-octave-request at bevo dot che dot wisc dot edu Tue Nov 12 20:16:11 2002 Subject: specifying matrices before filling with values From: Mike Miller To: Hein Zelle cc: Octave Mailing List 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 -------------------------------------------------------------