Re: Avoiding For Loops [message #45077 is a reply to message #13445] |
Mon, 01 August 2005 14:35  |
Dick Jackson
Messages: 347 Registered: August 1998
|
Senior Member |
|
|
"sudipta" <ssarkar@forestone.com> wrote in message
news:1122923758.653063.102140@f14g2000cwb.googlegroups.com.. .
> Hello Everybody,
> My IDL problem is simple but is very crucial.
. [...]
> So i was wondering if there was a way
> to avoid the for loops and do the RMS computation in one single step?
Hi Sudipta,
Your guess that IDL should be able to do this is correct. Read on! I did a
few iterations of your calculations, printing out the result, then did the
whole works after that. You can save this next section in a .pro file,
compile it and run it. Hope this helps.
=====
;; Make some sample data
data = RandomU(seed,10,14014,10,6)
lfData = RandomU(seed,6)
Print, 'Original Way:'
Print
;; I have reordered the loops with slowest-changing dimension in
;; the outer loop... in IDL, this is the last dimension.
numbands = 6
for k = 0, 1 do begin ;number of fractions (10)
for j = 0, 1 do begin ;number of spectral combinations (14013)
for i = 0,1 do begin ;number of AI (10)
tdata = reform(data(i,j,k,*),numbands,1)
Print, total((tdata - lfdata)^2)
end
Print
end
Print
end
Print, 'Un-loopy way :-) :'
Print
t0 = SysTime(1)
;; Extend the 6 values across all other dimensions
lfData = Reform(lfData,1,1,1,6)
lfDataExt = Rebin(lfData,10,14014,10,6)
;; Calculate RMS in one step
rms = Total((data-lfDataExt)^2, 4)
timeTaken = SysTime(1)-t0
Print, 'Time taken:'+StrTrim(timeTaken, 2)+' seconds.'
Print
;; Print 2x2x2 section for comparison
Print, rms[0:1,0:1,0:1]
END
=====
Printout from above program:
----------------------------
Original Way:
0.358912
1.03072
0.164605
0.782057
0.910758
0.800281
0.591216
1.48899
Un-loopy way :-) :
Time taken:0.29700017 seconds.
0.358912 1.03072
0.164605 0.782057
0.910758 0.800281
0.591216 1.48899
=====
Cheers,
--
-Dick
Dick Jackson / dick@d-jackson.com
D-Jackson Software Consulting / http://www.d-jackson.com
Calgary, Alberta, Canada / +1-403-242-7398 / Fax: 241-7392
|
|
|