help-octave
[Top][All Lists]
Advanced

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

Re: How do I replace this "for" loop?


From: Tom Holroyd
Subject: Re: How do I replace this "for" loop?
Date: Tue, 31 May 2005 17:34:35 -0400
User-agent: Mozilla Thunderbird 1.0.2-1.3.2 (X11/20050324)

Note that of the two schemes, which one is faster depends on the data.

Using a logical index, as in a(a>4), will be slower than using find if the number of elements that satisfy the condition is small:

octave:20> a=ones(10000,1);
octave:21> a(50) = 5;
octave:22> t0 = cputime; for i=1:10000, i=find(a>4); a(i) = a(i) + 1; end; cputime - t0
ans = 3.8944
octave:23> t0 = cputime; for i=1:10000, i=find(a>4); a(i) = a(i) + 1; end; cputime - t0
ans = 3.9094
octave:24> t0 = cputime; for i=1:10000, a(a>4) = a(a>4) + 1; end; cputime - t0
ans = 5.2132
octave:25> t0 = cputime; for i=1:10000, a(a>4) = a(a>4) + 1; end; cputime - t0
ans = 5.1892

But if the number of elements that satisfy the condition is large, using find will be (in this case much) slower:

octave:26> a=ones(10000,1) * 5;
octave:27> t0 = cputime; for i=1:10000, a(a>4) = a(a>4) + 1; end; cputime - t0
ans = 9.1416
octave:28> t0 = cputime; for i=1:10000, i=find(a>4); a(i) = a(i) + 1; end; cputime - t0
ans = 49.164

--
Dr. Tom Holroyd
"A man of genius makes no mistakes. His errors are volitional and
are the portals of discovery." -- James Joyce



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