[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: How do I replace this "for" loop?
From: |
Keith Goodman |
Subject: |
Re: How do I replace this "for" loop? |
Date: |
Tue, 31 May 2005 14:50:30 -0700 |
On 5/31/05, Tom Holroyd <address@hidden> wrote:
> 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
>
I think that's because you penalize the without-find method by
calculating a>4 twice. If you only calculated a>4 once, the
without-find method is faster:
>> a=ones(10000,1);
>> a(50) = 5;
>> t0 = cputime; for i=1:10000, i=find(a>4); a(i) = a(i) + 1; end;cputime-t0
ans = 2.7026
>> t0 = cputime; for i=1:10000, i=find(a>4); a(i) = a(i) + 1; end;cputime-t0
ans = 2.7046
>>
>> t0 = cputime; for i=1:10000, a(a>4) = a(a>4) + 1; end; cputime - t0
ans = 2.8696
>> t0 = cputime; for i=1:10000, a(a>4) = a(a>4) + 1; end; cputime - t0
ans = 2.8566
>>
>> t0 = cputime; for i=1:10000, i=a>4; a(i) = a(i) + 1; end; cputime - t0
ans = 2.2857
>> t0 = cputime; for i=1:10000, i=a>4; a(i) = a(i) + 1; end; cputime - t0
ans = 2.2967
>>
-------------------------------------------------------------
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
-------------------------------------------------------------