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 18:16:56 -0400
User-agent: Mozilla Thunderbird 1.0.2-1.3.2 (X11/20050324)

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:

No, that only affects a constant time.  The logical index version takes constant
time for a given size, whereas the find version takes time proportional to the
number of elements found, plus a small constant.  Of course, as with all
benchmarks, your own app is the best measure, but for the case below, it appears
that find wins when the percentage of elements found is less than about 1% (see
attached graph, produced by moo.m, below).  But the logical version is much,
much faster than find for the other 99%.

I think we've answered the question.  Time to get back to work.  :-)

---8<---
function moo
endfunction

x = .97:.002:1

r1 = [];
for p = x
         r1(end+1) = doit1(p);
end
r2 = [];
for p = x
         r2(end+1) = doit2(p);
end

plot(x, r1)
hold on
plot(x, r2)
hold off

function t = doit1(p)
         N = 2000;
         x = rand(N);
         t0 = cputime;
         idx = find(x>p);
         x(idx) = 2*x(idx);
         t = cputime - t0;
endfunction

function t = doit2(p)
         N = 2000;
         x = rand(N);
         t0 = cputime;
         x = 2*(x>p);
         t = cputime - t0;
endfunction
---8<---
--
Dr. Tom Holroyd
"A man of genius makes no mistakes. His errors are volitional and
are the portals of discovery." -- James Joyce

PNG image


reply via email to

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