Lesson 2: Using Keyword Parameters
In this lesson, you will write a short example of a function that exchanges two columns of a 4-by-4 homogeneous coordinate transformation matrix. The function has one positional parameter, the coordinate transformation matrix, T. The caller can specify one of the keywords XYexch, XZexch, or YZexch, to interchange the XY, XZ, or YZ axes of the matrix. The result of the function is the new coordinate transformation matrix:
To write the transformation function, do the following:
1. Define a function called SWAP that swaps columns of T. If XYEXCH is specified swap columns 0 and 1, XZEXCH swaps 0 and 2, and YZEXCH swaps 1 and 2.
FUNCTION SWAP, T, XYEXCH=XY, XZEXCH=XZ, YZEXCH=YZ
; Check if XY is set and swap columns 0 and 1.
IF KEYWORD_SET(XY) THEN S=[0, 1]
; Check if XZ is set and swap columns 0 and 2.
ELSE IF KEYWORD_SET(XZ) THEN S=[0, 2]
; Check if YZ is set and swap columns 1 and 2.
ELSE IF KEYWORD_SET(YZ) THEN S=[1, 2]
; Code to abort the function because nothing is set.
ELSE RETURN, T
; Copy the matrix to swap and return.
R = T
; Exchange two columns using matrix insertion operators and
; subscript ranges.
R(S(1), 0) = T(S(0), *)
R(S(0), 0) = T(S(1), *)
; Use the following code to return the result.
RETURN, R
; Use END to end the function.
END
Usage examples for the SWAP function would look like the following:
WAVE> Q=SWAP(!P.T, /XYexch)
WAVE> Q=SWAP(Q, /XYexch)
WAVE> Q=SWAP(INVERT(Z), YZexch=1)
WAVE> Q=SWAP(Z, XYexch=I EQ 0, YZexch=I EQ 2)
The last example sets one of the three keywords, according to the value of the variable I.
This function example uses the system function KEYWORD_SET to determine if a keyword parameter has been passed and it is non-zero. This is similar to using the condition:
IF N_ELEMENTS(P) NE 0 THEN IF P THEN ... ...
to test if keywords that have a true/false value are both present and true.
note | Use the PARAM_PRESENT function in conjunction with KEYWORD_SET to test if a keyword was actually used in a function or procedure call. For information on PARAM_PRESENT, see the PV‑WAVE Reference. |