Provided by: gmt_4.5.11-1build1_amd64

**NAME**

grdmath - Reverse Polish Notation calculator for grid files

**SYNOPSIS**

grdmath[-F] [-Ixinc[unit][=|+][/yinc[unit][=|+]] ] [-M] [-N] [-Rwest/east/south/north[r] ] [-V] [-bi[s|S|d|D[ncol]|c[var1/...]] ] [-fcolinfo]operand[operand]OPERATOR[operand]OPERATOR...=outgrdfile

**DESCRIPTION**

grdmathwill perform operations like add, subtract, multiply, and divide on one or more grid files or constants using Reverse Polish Notation (RPN) syntax (e.g., Hewlett-Packard calculator-style). Arbitrarily complicated expressions may therefore be evaluated; the final result is written to an output grid file. When two grids are on the stack, each element in file A is modified by the corresponding element in file B. However, some operators only require one operand (see below). If no grid files are used in the expression then options-R,-Imust be set (and optionally-F). The expression=outgrdfilecan occur as many times as the depth of the stack allows.operandIfoperandcan be opened as a file it will be read as a grid file. If not a file, it is interpreted as a numerical constant or a special symbol (see below).outgrdfileThe name of a 2-D grid file that will hold the final result. (See GRID FILE FORMATS below).OPERATORSChoose among the following 145 operators. "args" are the number of input and output arguments. Operator args ReturnsABS1 1 abs (A).ACOS1 1 acos (A).ACOSH1 1 acosh (A).ACOT1 1 acot (A).ACSC1 1 acsc (A).ADD2 1 A + B.AND2 1 NaN if A and B == NaN, B if A == NaN, else A.ASEC1 1 asec (A).ASIN1 1 asin (A).ASINH1 1 asinh (A).ATAN1 1 atan (A).ATAN22 1 atan2 (A, B).ATANH1 1 atanh (A).BEI1 1 bei (A).BER1 1 ber (A).CAZ2 1 Cartesian azimuth from grid nodes to stack x,y.CBAZ2 1 Cartesian backazimuth from grid nodes to stack x,y.CDIST2 1 Cartesian distance between grid nodes and stack x,y.CEIL1 1 ceil (A) (smallest integer >= A).CHICRIT2 1 Critical value for chi-squared-distribution, with alpha = A and n = B.CHIDIST2 1 chi-squared-distribution P(chi2,n), with chi2 = A and n = B.CORRCOEFF2 1 Correlation coefficient r(A, B).COS1 1 cos (A) (A in radians).COSD1 1 cos (A) (A in degrees).COSH1 1 cosh (A).COT1 1 cot (A) (A in radians).COTD1 1 cot (A) (A in degrees).CPOISS2 1 Cumulative Poisson distribution F(x,lambda), with x = A and lambda = B.CSC1 1 csc (A) (A in radians).CSCD1 1 csc (A) (A in degrees).CURV1 1 Curvature of A (Laplacian).D2DX21 1 d^2(A)/dx^2 2nd derivative.D2DXY1 1 d^2(A)/dxdy 2nd derivative.D2DY21 1 d^2(A)/dy^2 2nd derivative.D2R1 1 Converts Degrees to Radians.DDX1 1 d(A)/dx Central 1st derivative.DDY1 1 d(A)/dy Central 1st derivative.DILOG1 1 dilog (A).DIV2 1 A / B.DUP1 2 Places duplicate of A on the stack.EQ2 1 1 if A == B, else 0.ERF1 1 Error function erf (A).ERFC1 1 Complementary Error function erfc (A).ERFINV1 1 Inverse error function of A.EXCH2 2 Exchanges A and B on the stack.EXP1 1 exp (A).EXTREMA1 1 Local Extrema: +2/-2 is max/min, +1/-1 is saddle with max/min in x, 0 elsewhere.FACT1 1 A! (A factorial).FCRIT3 1 Critical value for F-distribution, with alpha = A, n1 = B, and n2 = C.FDIST3 1 F-distribution Q(F,n1,n2), with F = A, n1 = B, and n2 = C.FLIPLR1 1 Reverse order of values in each row.FLIPUD1 1 Reverse order of values in each column.FLOOR1 1 floor (A) (greatest integer <= A).FMOD2 1 A % B (remainder after truncated division).GE2 1 1 if A >= B, else 0.GT2 1 1 if A > B, else 0.HYPOT2 1 hypot (A, B) = sqrt (A*A + B*B).I01 1 Modified Bessel function of A (1st kind, order 0).I11 1 Modified Bessel function of A (1st kind, order 1).IN2 1 Modified Bessel function of A (1st kind, order B).INRANGE3 1 1 if B <= A <= C, else 0.INSIDE1 1 1 when inside or on polygon(s) in A, else 0.INV1 1 1 / A.ISNAN1 1 1 if A == NaN, else 0.J01 1 Bessel function of A (1st kind, order 0).J11 1 Bessel function of A (1st kind, order 1).JN2 1 Bessel function of A (1st kind, order B).K01 1 Modified Kelvin function of A (2nd kind, order 0).K11 1 Modified Bessel function of A (2nd kind, order 1).KEI1 1 kei (A).KER1 1 ker (A).KN2 1 Modified Bessel function of A (2nd kind, order B).KURT1 1 Kurtosis of A.LDIST1 1 Compute distance from lines in multi-segment ASCII file A.LE2 1 1 if A <= B, else 0.LMSSCL1 1 LMS scale estimate (LMS STD) of A.LOG1 1 log (A) (natural log).LOG101 1 log10 (A) (base 10).LOG1P1 1 log (1+A) (accurate for small A).LOG21 1 log2 (A) (base 2).LOWER1 1 The lowest (minimum) value of A.LRAND2 1 Laplace random noise with mean A and std. deviation B.LT2 1 1 if A < B, else 0.MAD1 1 Median Absolute Deviation (L1 STD) of A.MAX2 1 Maximum of A and B.MEAN1 1 Mean value of A.MED1 1 Median value of A.MIN2 1 Minimum of A and B.MOD2 1 A mod B (remainder after floored division).MODE1 1 Mode value (Least Median of Squares) of A.MUL2 1 A * B.NAN2 1 NaN if A == B, else A.NEG1 1 -A.NEQ2 1 1 if A != B, else 0.NOT1 1 NaN if A == NaN, 1 if A == 0, else 0.NRAND2 1 Normal, random values with mean A and std. deviation B.OR2 1 NaN if A or B == NaN, else A.PDIST1 1 Compute distance from points in ASCII file A.PLM3 1 Associated Legendre polynomial P(A) degree B order C.PLMg3 1 Normalized associated Legendre polynomial P(A) degree B order C (geophysical convention).POP1 0 Delete top element from the stack.POW2 1 A ^ B.PQUANT2 1 The B'th Quantile (0-100%) of A.PSI1 1 Psi (or Digamma) of A.PV3 1 Legendre function Pv(A) of degree v = real(B) + imag(C).QV3 1 Legendre function Qv(A) of degree v = real(B) + imag(C).R22 1 R2 = A^2 + B^2.R2D1 1 Convert Radians to Degrees.RAND2 1 Uniform random values between A and B.RINT1 1 rint (A) (nearest integer).ROTX2 1 Rotate A by the (constant) shift B in x-direction.ROTY2 1 Rotate A by the (constant) shift B in y-direction.SAZ2 1 Spherical azimuth from grid nodes to stack x,y.SBAZ2 1 Spherical backazimuth from grid nodes to stack x,y.SDIST2 1 Spherical (Great circle) distance (in degrees) between grid nodes and stack lon,lat (A, B).SEC1 1 sec (A) (A in radians).SECD1 1 sec (A) (A in degrees).SIGN1 1 sign (+1 or -1) of A.SIN1 1 sin (A) (A in radians).SINC1 1 sinc (A) (sin (pi*A)/(pi*A)).SIND1 1 sin (A) (A in degrees).SINH1 1 sinh (A).SKEW1 1 Skewness of A.SQR1 1 A^2.SQRT1 1 sqrt (A).STD1 1 Standard deviation of A.STEP1 1 Heaviside step function: H(A).STEPX1 1 Heaviside step function in x: H(x-A).STEPY1 1 Heaviside step function in y: H(y-A).SUB2 1 A - B.TAN1 1 tan (A) (A in radians).TAND1 1 tan (A) (A in degrees).TANH1 1 tanh (A).TCRIT2 1 Critical value for Student's t-distribution, with alpha = A and n = B.TDIST2 1 Student's t-distribution A(t,n), with t = A, and n = B.TN2 1 Chebyshev polynomial Tn(-1<t<+1,n), with t = A, and n = B.UPPER1 1 The highest (maximum) value of A.XOR2 1 0 if A == NaN and B == NaN, NaN if B == NaN, else A.Y01 1 Bessel function of A (2nd kind, order 0).Y11 1 Bessel function of A (2nd kind, order 1).YLM2 2 Re and Im orthonormalized spherical harmonics degree A order B.YLMg2 2 Cos and Sin normalized spherical harmonics degree A order B (geophysical convention).YN2 1 Bessel function of A (2nd kind, order B).ZCRIT1 1 Critical value for the normal-distribution, with alpha = A.ZDIST1 1 Cumulative normal-distribution C(x), with x = A.SYMBOLSThe following symbols have special meaning:PI3.1415926...E2.7182818...EULER0.5772156...XMINMinimum x valueXMAXMaximum x valueXINCx incrementNXThe number of x nodesYMINMinimum y valueYMAXMaximum y valueYINCy incrementNYThe number of y nodesXGrid with x-coordinatesYGrid with y-coordinatesXnGrid with normalized [-1 to +1] x-coordinatesYnGrid with normalized [-1 to +1] y-coordinates

**OPTIONS**

-FForce pixel node registration [Default is gridline registration]. (Node registrations are defined inGMTCookbook Appendix B on grid file formats.) Only used with-R-I.-Ix_inc[and optionallyy_inc] is the grid spacing. Optionally, append a suffix modifier.Geographical(degrees)coordinates: Appendmto indicate arc minutes orcto indicate arc seconds. If one of the unitse,k,i, ornis appended instead, the increment is assumed to be given in meter, km, miles, or nautical miles, respectively, and will be converted to the equivalent degrees longitude at the middle latitude of the region (the conversion depends onELLIPSOID). If /y_incis given but set to 0 it will be reset equal tox_inc; otherwise it will be converted to degrees latitude.Allcoordinates: If=is appended then the corresponding maxx(east) ory(north) may be slightly adjusted to fit exactly the given increment [by default the increment may be adjusted slightly to fit the given domain]. Finally, instead of giving an increment you may specify thenumberofnodesdesired by appending+to the supplied integer argument; the increment is then recalculated from the number of nodes and the domain. The resulting increment value depends on whether you have selected a gridline-registered or pixel-registered grid; see Appendix B for details. Note: if-Rgrdfileis used then grid spacing has already been initialized; use-Ito override the values.-MBy default any derivatives calculated are in z_units/ x(or y)_units. However, the user may choose this option to convert dx,dy in degrees of longitude,latitude into meters using a flat Earth approximation, so that gradients are in z_units/meter.-NTurn off strict domain match checking when multiple grids are manipulated [Default will insist that each grid domain is within 1e-4 * grid_spacing of the domain of the first grid listed].-Rxmin,xmax,ymin, andymaxspecify the Region of interest. For geographic regions, these limits correspond towest,east,south,andnorthand you may specify them in decimal degrees or in [+-]dd:mm[:ss.xxx][W|E|S|N] format. Appendrif lower left and upper right map coordinates are given instead of w/e/s/n. The two shorthands-Rgand-Rdstand for global domain (0/360 and -180/+180 in longitude respectively, with -90/+90 in latitude). Alternatively, specify the name of an existing grid file and the-Rsettings (and grid spacing, if applicable) are copied from the grid. For calendar time coordinates you may either give (a) relative time (relative to the selectedTIME_EPOCHand in the selectedTIME_UNIT; appendtto-JX|x), or (b) absolute time of the form [date]T[clock] (appendTto-JX|x). At least one ofdateandclockmust be present; theTis always required. Thedatestring must be of the form [-]yyyy[-mm[-dd]] (Gregorian calendar) or yyyy[-Www[-d]] (ISO week calendar), while theclockstring must be of the form hh:mm:ss[.xxx]. The use of delimiters and their type and positions must be exactly as indicated (however, input, output and plot formats are customizable; seegmtdefaults).-VSelects verbose mode, which will send progress reports to stderr [Default runs "silently"].-biSelects binary input. Appendsfor single precision [Default isd(double)]. UppercaseSorDwill force byte-swapping. Optionally, appendncol, the number of columns in your binary input file if it exceeds the columns needed by the program. Or appendcif the input file is netCDF. Optionally, appendvar1/var2/...to specify the variables to be read. The binary input option only applies to the data files needed by operatorsLDIST,PDIST, andINSIDE.-fSpecial formatting of input and/or output columns (time or geographical data). Specifyioroto make this apply only to input or output [Default applies to both]. Give one or more columns (or column ranges) separated by commas. AppendT(absolute calendar time),t(relative time in chosenTIME_UNITsinceTIME_EPOCH),x(longitude),y(latitude), orf(floating point) to each column or column range item. Shorthand-f[i|o]gmeans-f[i|o]0x,1y(geographic coordinates).

**NOTES** **ON** **OPERATORS**

(1) The operatorSDISTcalculates spherical distances between the (lon, lat) point on the stack and all node positions in the grid. The grid domain and the (lon, lat) point are expected to be in degrees. Similarly, theSAZandSBAZoperators calculate spherical azimuth and back-azimuths in degrees, respectively. A few operators (PDIST,LDIST, andINSIDE) expects their argument to be a single file with points, lines, or polygons, respectively. Be aware thatLDISTin particular can be slow for large grids and numerous line segments. Note: If the currentELLIPSOIDis not spherical then geodesics are used in the calculations. (2) The operatorPLMcalculates the associated Legendre polynomial of degree L and order M (0 <= M <= L), and its argument is the sine of the latitude.PLMis not normalized and includes the Condon-Shortley phase (-1)^M.PLMgis normalized in the way that is most commonly used in geophysics. The C-S phase can be added by using -M as argument.PLMwill overflow at higher degrees, whereasPLMgis stable until ultra high degrees (at least 3000). (3) The operatorsYLMandYLMgcalculate normalized spherical harmonics for degree L and order M (0 <= M <= L) for all positions in the grid, which is assumed to be in degrees.YLMandYLMgreturn two grids, the real (cosine) and imaginary (sine) component of the complex spherical harmonic. Use thePOPoperator (andEXCH) to get rid of one of them, or save both by giving two consecutive = file.grd calls. The orthonormalized complex harmonicsYLMare most commonly used in physics and seismology. The square ofYLMintegrates to 1 over a sphere. In geophysics,YLMgis normalized to produce unit power when averaging the cosine and sine terms (separately!) over a sphere (i.e., their squares each integrate to 4 pi). The Condon-Shortley phase (-1)^M is not included inYLMorYLMg, but it can be added by using -M as argument. (4) All the derivatives are based on central finite differences, with natural boundary conditions. (5) Files that have the same names as some operators, e.g.,ADD,SIGN,=, etc. should be identified by prepending the current directory (i.e., ./LOG). (6) Piping of files is not allowed. (7) The stack depth limit is hard-wired to 100. (8) All functions expecting a positive radius (e.g.,LOG,KEI, etc.) are passed the absolute value of their argument.

**GRID** **VALUES** **PRECISION**

Regardless of the precision of the input data, GMT programs that create grid files will internally hold the grids in 4-byte floating point arrays. This is done to conserve memory and furthermore most if not all real data can be stored using 4-byte floating point values. Data with higher precision (i.e., double precision values) will lose that precision once GMT operates on the grid or writes out new grids. To limit loss of precision when processing data you should always consider normalizing the data prior to processing.

**GRID** **FILE** **FORMATS**

By defaultGMTwrites out grid as single precision floats in a COARDS-complaint netCDF file format. However,GMTis able to produce grid files in many other commonly used grid file formats and also facilitates so called "packing" of grids, writing out floating point data as 2- or 4-byte integers. To specify the precision, scale and offset, the user should add the suffix=id[/scale/offset[/nan]], whereidis a two-letter identifier of the grid type and precision, andscaleandoffsetare optional scale factor and offset to be applied to all grid values, andnanis the value used to indicate missing data. When reading grids, the format is generally automatically recognized. If not, the same suffix can be added to input grid file names. Seegrdreformat(1) and Section 4.17 of the GMT Technical Reference and Cookbook for more information. When reading a netCDF file that contains multiple grids,GMTwill read, by default, the first 2-dimensional grid that can find in that file. To coaxGMTinto reading another multi-dimensional variable in the grid file, append?varnameto the file name, wherevarnameis the name of the variable. Note that you may need to escape the special meaning of?in your shell program by putting a backslash in front of it, or by placing the filename and suffix between quotes or double quotes. The?varnamesuffix can also be used for output grids to specify a variable name different from the default: "z". Seegrdreformat(1) and Section 4.18 of the GMT Technical Reference and Cookbook for more information, particularly on how to read splices of 3-, 4-, or 5-dimensional grids.

**GEOGRAPHICAL** **AND** **TIME** **COORDINATES**

When the output grid type is netCDF, the coordinates will be labeled "longitude", "latitude", or "time" based on the attributes of the input data or grid (if any) or on the-for-Roptions. For example, both-f0x-f1tand-R90w/90e/0t/3t will result in a longitude/time grid. When the x, y, or z coordinate is time, it will be stored in the grid as relative time since epoch as specified byTIME_UNITandTIME_EPOCHin the .gmtdefaults file or on the command line. In addition, theunitattribute of the time variable will indicate both this unit and epoch.

**EXAMPLES**

To take log10 of the average of 2 files, usegrdmathfile1.grd file2.grdADD0.5MULLOG10=file3.grd Given the file ages.grd, which holds seafloor ages in m.y., use the relation depth(in m) = 2500 + 350 * sqrt (age) to estimate normal seafloor depths:grdmathages.grdSQRT350MUL2500ADD=depths.grd To find the angle a (in degrees) of the largest principal stress from the stress tensor given by the three files s_xx.grd s_yy.grd, and s_xy.grd from the relation tan (2*a) = 2 * s_xy / (s_xx - s_yy), usegrdmath2 s_xy.grdMULs_xx.grd s_yy.grdSUBDIVATAN22DIV=direction.grd To calculate the fully normalized spherical harmonic of degree 8 and order 4 on a 1 by 1 degree world map, using the real amplitude 0.4 and the imaginary amplitude 1.1:grdmath-R0/360/-90/90-I1 8 4YML1.1MULEXCH0.4MULADD= harm.grd To extract the locations of local maxima that exceed 100 mGal in the file faa.grd:grdmathfaa.grdDUPEXTREMA2EQMULDUP100GTMUL0NAN= z.grdgrd2xyzz.grd-S> max.xyz

**REFERENCES**

Abramowitz, M., and I. A. Stegun, 1964,HandbookofMathematicalFunctions, Applied Mathematics Series, vol. 55, Dover, New York. Holmes, S. A., and W. E. Featherstone, 2002, A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions.JournalofGeodesy, 76, 279-299. Press, W. H., S. A. Teukolsky, W. T. Vetterling, and B. P. Flannery, 1992,NumericalRecipes, 2nd edition, Cambridge Univ., New York. Spanier, J., and K. B. Oldman, 1987,AnAtlasofFunctions, Hemisphere Publishing Corp.

**SEE** **ALSO**

GMT(1),gmtmath(1),grd2xyz(1),grdedit(1),grdinfo(1),xyz2grd(1)