Loops are bad (but are they ``the embodiment of pure evil''?). They slow things down (but, they are not that bad in some cases; for simple applications speed is not an issue and they can be clear to read). How to avoid them can be complex (see links above) but there are a few simple rules.
I think here it's just best to go through,
http://www.dfanning.com/code\_tips/slowloops.htmlno point me cutting and pasting it all in here!
Use ## (matrix multiply i.e. multiplies the rows of the first array by the columns of the second array) OR use # (multiplies the columns of the first array by the rows of the second array, i.e. reverse of a standard matrix multiply) to avoid loops (see example in Other tips and tricks: colorbars and contours on images).
Write functions to always deal with scalars or vectors e.g.
FUNCTION temp_to_theta,temp,pressure,ref_press=ref_press ;+ ;FUNCTION temp_to_theta,temp,pressure,ref_press=ref_press ;JOHN MARSHAM 18/3/2005 ;Takes temperature (K or C), and pressure (any, mbar if ref_press not set) ' ;returns potential temperature (K or C) adjusted to ref_press' ;If ref_press not set uses 1000 mbar ;- if n_params() ne 2 then begin print,'temp_to_theta,temp,pressure,ref_press=ref_press' print,'Takes temperature (K (or C)), and pressure (hPa) ' print,'returns potential temperature (K (or C)) adjusted to ref_press' print,'If ref_press not set uses 1000 mbar' return,-1 endif if not keyword_set(ref_press) then ref_press = 1000. ; this auto-conversion is slightly dodgy but I don't tend to look at ; temperatures below -123 K ! if max(temp) lt 150 then begin temp=temp+273.15 degC=1 print,'converting deg C to K - will convert back' endif else begin temp=temp degC=0 print,'Not converting deg C to K - already K' endelse theta=temp*(ref_press/pressure)^(0.286) if degC eq 1 then theta=theta-273.15 return,theta endwill convert temp to potential temp where temp is a scalar (eg temp=10.) or a vector (temp=[5.,10.,12.]) eg
IDL> print,temp_to_theta(10.,700.) converting deg C to K 40.4085 IDL> print,temp_to_theta([10.,20.],700.) converting deg C to K 40.4085 51.4824 IDL> print,temp_to_theta([10.,20.],[700.,700.]) converting deg C to K 40.4085 51.4824 IDL> print,temp_to_theta([10.,20.],[700.,600.]) converting deg C to K 40.4085 66.1147
For further discussion (`` are they the embodiment of pure evil?'') see http://www.dfanning.com/tips/forloops.html