Contact: zegraph  @  yahoo.com      Last update: June 2020

### Matrix Library

The library is for dealing with row-majored 2D arrays of char, unsigned char, short, unsigned short, int, unsigned int, float, and double.

#### Matrix Creation

 Function Parameters and Type Remarks double([nrow, ncol]) integers Creates a matrix of double type. See example-1. double(a, b, c[, ...]) numbers Creates a matrix of double type and fill it with numbers. See example-1. double(M) matrix Creates a matrix of double type and fill it with numbers in matrix M. See example-1. Note: A matrix of char, unsigned char, short, unsigned short, int unsigned int, and float can be created similarly by functions of char(), uchar(), short(), ushort(), int(), uint(), and float(); respectively. The old function matrix(typename, nrow, ncol) may also be used. See example-1.

#### Matrix Manipulation

 Function Parameters and Type Acceptable Matrix Type Remarks .delete(i[, flag]) integer, string all Deletes the ith column. Deletes the ith row if the optional flag is "r". See example-2. .fill(initial, step) number, number all Fills the matrix with numbers with the first=initial, the second=initial + step, and etc. Note that it will not check over flow. See example-2. .find(v[,i, j]) number, integer, integer all Returns the row and column indices as array (i.e., [irow, icol]) at which the matrix value equals v, which must be integer when the matrix is not float or double type. If the optional i and j parameters are given, the function starts searching from the ith row and the jth column. See example-2. .flip([flag]) string all Flips columns by default. Flips rows if the optional flag is "r". See example-2. .insert(i, src[, flag]) integer, number or matrix, string all Inserts src to the caller before the ith column. If src is a matrix, it must be the same type and has the same number of rows as the caller. Insertion operates on row if the optional flag is "r", in which case src must have the same number of columns as the caller. See example-3. .prod(src) matrix float or double Saves matrix product of the caller and src in the caller. The number of columns of the caller must equal the number of rows of src. See example-3. .ptr() all Returns a array containing matrix pointer in [0], the number of data in [1], and the element size in [2]. See example-2. .replace(idx, src) matrix of int, matrix all Replace values at indices given by idx with values in src, i.e., caller[index[i]] = src[i]; therefore the size of src must be at least the same as that of idx. Values in idx must be zero or positive and be smaller than the size of the caller. See example-3. .resize(nrow, ncol) integer, integer all Resizes the matrix. See example-2. .reshape(nrow, ncol) integer, integer all Reshapes the matrix to nrow by ncol whose product must equal the size of the caller. See example-2. .size() all Returns a array with the number of rows in [0], columns in [1], and total number of data in [2]. See example-2. .sort(i[, flag]) number[, number] all Sorts the matrix according the ith column. If flag > 0, sort in ascending order (default); otherwise in descending order. See example-3. .trans() all Matrix transpose. See example-2. .unique([flag]) [number] all Makes the matrix unique. If flag>0, unique elements are sorted in ascending order (default), otherwise in descending order. See example-3. .index(grid) number or matrix of double double If grid is a number, it returns the index of where caller's value match the grid the best. If the grid is a matrix, it returns a matrix of int-type containing matching indexes.

#### IO

 Function Parameters and Type Acceptable Matrix Type Remarks .csv([ format[, fname[, mode]]]) string, string, string all Prints matrix data to stdout or to the file specified by fname. Comma is inserted between numbers. The default format string is " %d" for signed integer matrix, " %u" for unsigned integer matrix, and " %f" for real type matrix. The default mode is overwrite. Use "a" to set the mode to appending. See example-4. .parse(str) string all Parses numbers in the string. The matrix will be resized according to numbers in the string. See example-4. .import(ptr) user all Imports data from the pointer, which must point to enough number of data of the same type of the caller. See example-4. .print([ format[, fname[, mode]]]) string, string, string all Similar to csv function, but no comma is inserted between numbers. See example-4. .readtext(fname[,nl]) string, integer double Reads data from text file and returns the number of data read. Any rows in the file that have non-numeric characters will be ignored in parsing. The number of items of the first data row determins the number of columns of the caller; and the number of data rows deternines the number of rows. A date/time item is converted to Julian date number. The function skips the first nl number of lines. See example-4.

#### Math

 Function Parameters and Type Acceptable Matrix Type Remarks cos(p), acos(p), cosh(p), sin(p), asin(p), sinh(p), tan(p), atan(p), tanh(p), sqrt(p), exp(p), log(p), log10(p), ceil(p), floor(p), abs(p) matrix all Returns a double matrix filled with cos(p[i]) and etc. See example-5. atan2(p1, p2) matrix or number all Returns a double matrix filled with atan2(p1,p2).p1 or p2 or both can be matrix. See example-6. pow(p1, p2) matrix or number all Returns a double matrix filled with pow(p1,p2). p1 or p2 or both can be matrix. See example-6. .rand([seed]) integer all Fills the matrix with random numbers in [ 0, 1) if the caller is float or double; otherwise, fill the matrix with integers from 0 to the numvber of elements and randomly shuffle the integers. See example-5. .min() all Returns the smallest number in the the matrix. See example-5. .max() all Returns the largest number in the matrix. See example-5. .sum() all Returns the sum of elements in the matrix. See example-5. .mean() all Returns the mean of elements in the matrix. See example-5. .stdev([flag]) boolean all Returns the standard deviation, i.e., sqrt(sum(Ei- mean)/(n-1)), of elements in the matrix. If the optional flag is set ot true, the standard deviation is calculated as sqrt(sum(Ei- mean)/n)See example-5. cal2jul(p) matrix all Returns a double matrix containing Julian date and time converted from Gregorian calendar year, month, day, hour, minute, second in the first three to six columns of p, which must have at least three columns. Missing hour, minute, and second are treated as zero. See example-7. jul2cal(p) matrix all Returns a double matrix with the year, month, day, hour, minute, second in six columns. See example-7.

#### Unary Operators

 Operator Left Operand Right Operand Remark - char, short, int, float, or double Returns the negative of the original. Element wise negate. See example-8. ~ all Returns the transpose of the original. See example-8. ++ all Element wise increment by 1. Underflow and overflow are not checked. See example-8. -- all Element wise decrement by 1. Underflow and overflow are not checked. See example-8.

#### Binary Operators

 Operator Left Operand Right Operand Remark +, -, *, /, % matrix or number matrix or number Returns a matrix. Element wise add, subtract, multiply, divide, or mod. See example-9. +=, -=, *=, /=, %= matrix matrix or number The more efficient equivalent of +, -, *, /, and %. See example-9. ==, !=, >, >=, <, <= matrix or number matrix or number Element wise comparison. Returns a char-type matrix with element of 1 for true and 0 for false. See example-9. &&, || matrix matrix or number Logical and/or comparison. Returns a char-type matrix with element of 1 for true and 0 for false. See example-9. |, & matrix matrix Returns a matrix as the result of vertical/horizontal concatenation of two matrices. See example-9. <<, >> matrix integer Returns a matrix as the result of left/right shift of matrix columns. See example-9. ^ matrix integer Returns a matrix as the result of up-shift of matrix rows. See example-9.

#### Access by Index

 Operator Array Indexes Remark A[i] integer, index range, char matrix, or int matrix Returns matrix value(s). If i is an integer, it returns a number. If i is a char matrix, its size must be the same as A's size; and the returned matrix contains A's values for which the i's vaues are not zero at the corresponding indexes. If i is an int matrix, its values must be smaller than A's size; and the returned matrix contains A's values pick out using i values as the indexes of A. See example-10. A[i,j] integer, index range, char matrix, or int matrix Returns matrix value(s). If i and j are integers, it returns a number; If i is a char matrix, its size must be the same as A's rows; and if i is an int matrix, its values must be smaller than A's rows. The same condition applies to j regarding A's columns. See example-11.

#### Assignment by Index

 Operator Array Index Right Operand Remark A[i]=v integer, index range, char matrix, or int matrix number Sets the number to the matrix. See example-12. A[i]=V index range, char matrix, or int matrix A-type matrix Sets values of V to A. V's size must be the same as reguired by the index range or matrix. See example-13. A[i,j]=v integer, index range, char matrix, or int matrix number Sets the number to A. See example-14. A[i,j]=V integer, index range, char matrix, or int matrix A-type matrix Sets values of V to A. V's size must be the same as reguired by the index range or matrix. See example-15.

#### Numeric

 Function Parameters and Type Acceptable Matrix Type Remarks .area() double Assuming data in the matrix are polygon vertices, the function calculates polygon area. The caller should have at least 3 rows and two columns. The area is positive if the polygon winding is anti-clockwise, and negative otherwise. See example-16. .convolve(G) matrix double Returns a matrix containing the convolution of the caller with G, i.e., sum(Ci*Gj) for i=0 to n and j=0 to m, where m is G's size and n is C's size minus m. .delaunay([flag]) boolean double Finds Delaunay triangles for random points on a plane (If the caller has two columns) or spherical surface (If the caller has three columns). Returns an array with a matrix containing indices of triangles in [0] and a matrix containing convex hull indices in [1]. If the flag is true, the data are supposed to be non-intersect polygon vertices (e.g., coastline of island) and the triangulation is constrained by the polgyon.This function uses the STRIPACK of ACM (http://www.netlib.org/toms/). See example-17. .fft(flag) number double FFT for 1D complex array. The first column of the caller is treated as the real part and the second as the image part. This function uses CCMATH library. The functions returns true for normal exit and or false otherwise. See example-18. .gcdistance(lat, lon) numbers double Return a double matrix containing the great circle distances between (lat,lon) and the calling matrix, which must has two columns with latitude in the first column and longitude in the second. .inside(x, y) numbers double Checks if the point (x, y) is inside the polygon defined by the first two columns of caller (the first as x and the second as y). Returns true or false. See example-16. .interpo1d(gx) matrix double Linear 1D interpolation of the caller to grid gx. Returns a double matrix of the same size as gx. The first column of the caller is treated as x and the second as y. See example-19. .interpo2d(gx, gy) matrix, matrix double Linear 2D interpolation of the caller to grid gx and gy. Data in the caller are treated as on regular grids of 0 to nrow-1 and 0 to ncol-1. Returns a new matrix of double type. See example-19. .interpo2d(gu, gv, gx, gy) matix, matrix, matrix, matrix double Linear 2D interpolation of the caller to grid gx and gy. Data in the caller are treated as on regular grids of gu and gv. Returns a new matrix of double type. See example-19. .invert([flag]) string double In place inversion of a general real matrix. If the optional flag is "ps", the caller must be symmetric. If the optional flag is "ru", the caller is treated as upper right triangular matrix. This function uses CCMATH library. The function returns true for normal exit and or false if the caller is singular. See example-20. .nllm(func, par) string, matrix double Nonlinear multiple parameter estimation of y=f(x, p1, p2, ...) using Levenberg Marquardt least squares fitting by Joachim Wuttke. It returns an array containing the number of try and the standard deviation of difference, i.e., sqrt(sum((y(i)-f(i))^2)/(n-1))). The caller matrix must have at two columns, of which the first will be treated as x and the second as y. The callback function named func will be called with the first input being x matrix and the second being estimated paremeter matrix. It must return evaluated y as a matrix. See example-25. .lfit(X,[E]) matrix double Linear fit of y = a + b*x. The caller should be 1D matrix having the same size as X. It returns coefficients in an array. The optional matrix E should contain uncertainties for the caller. .mlfit(A) matrix double Multi-linear fit of y = a0 + a1*x1 + a2*x2 + ... The caller should be 1D matrix of size m and will contain coefficients on return. The design matrix A should be a m by n matrix with m>n. The first column of A should be all 1.0 and other column should contain data of x1, x2, and etc; and its first n rows will be modified to contain parameter variances. This function uses CCMATH library. It returns the estimated measurement of variance ssq/(m-n), where ssq is the sum of squared fit residuals. See example-24. .svd() double Conducts Simgular Value Decomposition (A = UDV') of the caller using the svduv() function of the CCMATH library. Returns an array with U in [0], D in [1], and V' in [2]. See example-23. .cvsp(a, b, n) numbers double Cross-validation spline interpolation. It returns a n by 2 matrix with the first column being x in the range of a to b and the second being smoothed y. The first column of the caller is treated as x and the second as y. This function uses the FORTRAN code from http://www.netlib.org/toms/642. See example-22. .smooth(n[, f]) numbers double Distance weighted running average smoothing with half-windows size of n points. The weighting factor is 1/(1+((i-i0)^2+(j-j0)^2)^f). The default f-value is 1.0. Valuse less than -1.e32 in the caller are treated as missing values. See example-21. .sgsm(m, n) numbers double Savitzky-Golay smoothing of power m and half filter window width n for 1D series data. Valuse less than -1.e32 in the caller are treated as missing values. The function tries to smooth the caller by polynomial fitting of y=a+bx+cx^2...x^m for every n points.It is required that n>m, m>1, and caller size>2*n+1. The function uses CCMATH library. See example-21.