Skip to main content

5.2) Single Variable Functions


We have seen that IDL uses radians rather than degrees, but what if we want to convert from radians to degrees? We could add the following line of code after every call to cos/sin/tan, etc.

a_deg=a_rad*180./!pi
; Convert radians to degrees

But if you use this many times, it is easy to make a typographical error. It is much better to write this just once as a function and make sure it works, then you can call it whenever you like and it will work every time. Type the following into a file called rad_to_deg.pro:

Function rad_to_deg, input_rad
; Function to convert radians to degrees
output_deg=input_rad*180./!pi
return, output_deg
END

Every function starts with the word "function". This is followed by the name of the function, a comma and the name of the input variable. At the bottom of the function (just before the "END" statement) is a line that begins with "return", followed by a comma and the name of the variable we would like to output when the function is called. In this function, we are using"!pi", this is a system variable which holds the value of pi.