This is Info file calc.info, produced by Makeinfo-1.55 from the input file calc.texinfo. This file documents Calc, the GNU Emacs calculator. Copyright (C) 1990, 1991 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided also that the section entitled "GNU General Public License" is included exactly as in the original, and provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that the section entitled "GNU General Public License" may be included in a translation approved by the author instead of in the original English. File: calc.info, Node: Manipulating Vectors, Next: Vector and Matrix Arithmetic, Prev: Extracting Elements, Up: Matrix Functions Manipulating Vectors ==================== The `v l' (`calc-vlength') [`vlen'] command computes the length of a vector. The length of a non-vector is considered to be zero. Note that matrices are just vectors of vectors for the purposes of this command. With the Hyperbolic flag, `H v l' [`mdims'] computes a vector of the dimensions of a vector, matrix, or higher-order object. For example, `mdims([[a,b,c],[d,e,f]])' returns `[2, 3]' since its argument is a 2x3 matrix. The `v f' (`calc-vector-find') [`find'] command searches along a vector for the first element equal to a given target. The target is on the top of the stack; the vector is in the second-to-top position. If a match is found, the result is the index of the matching element. Otherwise, the result is zero. The numeric prefix argument, if given, allows you to select any starting index for the search. The `v a' (`calc-arrange-vector') [`arrange'] command rearranges a vector to have a certain number of columns and rows. The numeric prefix argument specifies the number of columns; if you do not provide an argument, you will be prompted for the number of columns. The vector or matrix on the top of the stack is "flattened" into a plain vector. If the number of columns is nonzero, this vector is then formed into a matrix by taking successive groups of N elements. If the number of columns does not evenly divide the number of elements in the vector, the last row will be short and the result will not be suitable for use as a matrix. For example, with the matrix `[[1, 2], [3, 4]]' on the stack, `v a 4' produces `[[1, 2, 3, 4]]' (a 1x4 matrix), `v a 1' produces `[[1], [2], [3], [4]]' (a 4x1 matrix), `v a 2' produces `[[1, 2], [3, 4]]' (the original 2x2 matrix), `v a 3' produces `[[1, 2, 3], [4]]' (not a matrix), and `v a 0' produces the flattened list `[1, 2, 3, 4]'. The `V S' (`calc-sort') [`sort'] command sorts the elements of a vector into increasing order. Real numbers, real infinities, and constant interval forms come first in this ordering; next come other kinds of numbers, then variables (in alphabetical order), then finally come formulas and other kinds of objects; these are sorted according to a kind of lexicographic ordering with the useful property that one vector is less or greater than another if the first corresponding unequal elements are less or greater, respectively. Since quoted strings are stored by Calc internally as vectors of ASCII character codes (*note Strings::.), this means vectors of strings are also sorted into alphabetical order by this command. The `I V S' [`rsort'] command sorts a vector into decreasing order. The `V G' (`calc-grade') [`grade', `rgrade'] command produces an index table or permutation vector which, if applied to the input vector (as the index of `C-u v r', say), would sort the vector. A permutation vector is just a vector of integers from 1 to N, where each integer occurs exactly once. One application of this is to sort a matrix of data rows using one column as the sort key; extract that column, grade it with `V G', then use the result to reorder the original matrix with `C-u v r'. Another interesting property of the `V G' command is that, if the input is itself a permutation vector, the result will be the inverse of the permutation. The inverse of an index table is a rank table, whose Kth element says where the Kth original vector element will rest when the vector is sorted. To get a rank table, just use `V G V G'. With the Inverse flag, `I V G' produces an index table that would sort the input into decreasing order. Note that `V S' and `V G' use a "stable" sorting algorithm, i.e., any two elements which are equal will not be moved out of their original order. Generally there is no way to tell with `V S', since two elements which are equal look the same, but with `V G' this can be an important issue. In the matrix-of-rows example, suppose you have names and telephone numbers as two columns and you wish to sort by phone number primarily, and by name when the numbers are equal. You can sort the data matrix by names first, and then again by phone numbers. Because the sort is stable, any two rows with equal phone numbers will remain sorted by name even after the second sort. The `V H' (`calc-histogram') [`histogram'] command builds a histogram of a vector of numbers. Vector elements are assumed to be integers or real numbers in the range [0..N) for some "number of bins" N, which is the numeric prefix argument given to the command. The result is a vector of N counts of how many times each value appeared in the original vector. Non-integers in the input are rounded down to integers. Any vector elements outside the specified range are ignored. (You can tell if elements have been ignored by noting that the counts in the result vector don't add up to the length of the input vector.) With the Hyperbolic flag, `H V H' pulls two vectors from the stack. The second-to-top vector is the list of numbers as before. The top vector is an equal-sized list of "weights" to attach to the elements of the data vector. For example, if the first data element is 4.2 and the first weight is 10, then 10 will be added to bin 4 of the result vector. Without the hyperbolic flag, every element has a weight of one. The `v t' (`calc-transpose') [`trn'] command computes the transpose of the matrix at the top of the stack. If the argument is a plain vector, it is treated as a row vector and transposed into a one-column matrix. The `v v' (`calc-reverse-vector') [`vec'] command reverses a vector end-for-end. Given a matrix, it reverses the order of the rows. (To reverse the columns instead, just use `v t v v v t'. The same principle can be used to apply other vector commands to the columns of a matrix.) The `v m' (`calc-mask-vector') [`vmask'] command uses one vector as a mask to extract elements of another vector. The mask is in the second-to-top position; the target vector is on the top of the stack. These vectors must have the same length. The result is the same as the target vector, but with all elements which correspond to zeros in the mask vector deleted. Thus, for example, `vmask([1, 0, 1, 0, 1], [a, b, c, d, e])' produces `[a, c, e]'. *Note Logical Operations::. The `v e' (`calc-expand-vector') [`vexp'] command expands a vector according to another mask vector. The result is a vector the same length as the mask, but with nonzero elements replaced by successive elements from the target vector. The length of the target vector is normally the number of nonzero elements in the mask. If the target vector is longer, its last few elements are lost. If the target vector is shorter, the last few nonzero mask elements are left unreplaced in the result. Thus `vexp([2, 0, 3, 0, 7], [a, b])' produces `[a, 0, b, 0, 7]'. With the Hyperbolic flag, `H v e' takes a filler value from the top of the stack; the mask and target vectors come from the third and second elements of the stack. This filler is used where the mask is zero: `vexp([2, 0, 3, 0, 7], [a, b], z)' produces `[a, z, c, z, 7]'. If the filler value is itself a vector, then successive values are taken from it, so that the effect is to interleave two vectors according to the mask: `vexp([2, 0, 3, 7, 0, 0], [a, b], [x, y])' produces `[a, x, b, 7, y, 0]'. Another variation on the masking idea is to combine `[a, b, c, d, e]' with the mask `[1, 0, 1, 0, 1]' to produce `[a, 0, c, 0, e]'. You can accomplish this with `V M a &', mapping the logical "and" operation across the two vectors. *Note Logical Operations::. Note that the `? :' operation also discussed there allows other types of masking using vectors. File: calc.info, Node: Vector and Matrix Arithmetic, Next: Set Operations, Prev: Manipulating Vectors, Up: Matrix Functions Vector and Matrix Arithmetic ============================ Basic arithmetic operations like addition and multiplication are defined for vectors and matrices as well as for numbers. Division of matrices, in the sense of multiplying by the inverse, is supported. (Division by a matrix actually uses LU-decomposition for greater accuracy and speed.) *Note Basic Arithmetic::. The following functions are applied element-wise if their arguments are vectors or matrices: `change-sign', `conj', `arg', `re', `im', `polar', `rect', `clean', `float', `frac'. *Note Function Index::. The `V J' (`calc-conj-transpose') [`ctrn'] command computes the conjugate transpose of its argument, i.e., `conj(trn(x))'. The `A' (`calc-abs') [`abs'] command computes the Frobenius norm of a vector or matrix argument. This is the square root of the sum of the squares of the absolute values of the elements of the vector or matrix. If the vector is interpreted as a point in two- or three-dimensional space, this is the distance from that point to the origin. The `v n' (`calc-rnorm') [`rnorm'] command computes the row norm, or infinity-norm, of a vector or matrix. For a plain vector, this is the maximum of the absolute values of the elements. For a matrix, this is the maximum of the row-absolute-value-sums, i.e., of the sums of the absolute values of the elements along the various rows. The `V N' (`calc-cnorm') [`cnorm'] command computes the column norm, or one-norm, of a vector or matrix. For a plain vector, this is the sum of the absolute values of the elements. For a matrix, this is the maximum of the column-absolute-value-sums. General `k'-norms for `k' other than one or infinity are not provided. The `V C' (`calc-cross') [`cross'] command computes the right-handed cross product of two vectors, each of which must have exactly three elements. The `&' (`calc-inv') [`inv'] command computes the inverse of a square matrix. If the matrix is singular, the inverse operation is left in symbolic form. Matrix inverses are recorded so that once an inverse (or determinant) of a particular matrix has been computed, the inverse and determinant of the matrix can be recomputed quickly in the future. If the argument to `&' is a plain number `x', this command simply computes `1/x'. This is okay, because the `/' operator also does a matrix inversion when dividing one by a matrix. The `V D' (`calc-mdet') [`det'] command computes the determinant of a square matrix. The `V L' (`calc-mlud') [`lud'] command computes the LU decomposition of a matrix. The result is a list of three matrices which, when multiplied together left-to-right, form the original matrix. The first is a permutation matrix that arises from pivoting in the algorithm, the second is lower-triangular with ones on the diagonal, and the third is upper-triangular. The `V T' (`calc-mtrace') [`tr'] command computes the trace of a square matrix. This is defined as the sum of the diagonal elements of the matrix. File: calc.info, Node: Set Operations, Next: Statistical Operations, Prev: Vector and Matrix Arithmetic, Up: Matrix Functions Set Operations using Vectors ============================ Calc includes several commands which interpret vectors as "sets" of objects. A set is a collection of objects; any given object can appear only once in the set. Calc stores sets as vectors of objects in sorted order. Objects in a Calc set can be any of the usual things, such as numbers, variables, or formulas. Two set elements are considered equal if they are identical, except that numerically equal numbers like the integer 4 and the float 4.0 are considered equal even though they are not "identical." Variables are treated like plain symbols without attached values by the set operations; subtracting the set `[b]' from `[a, b]' always yields the set `[a]' even though if the variables `a' and `b' both equalled 17, you might expect the answer `[]'. If a set contains interval forms, then it is assumed to be a set of real numbers. In this case, all set operations require the elements of the set to be only things that are allowed in intervals: Real numbers, plus and minus infinity, HMS forms, and date forms. If there are variables or other non-real objects present in a real set, all set operations on it will be left in unevaluated form. If the input to a set operation is a plain number or interval form A, it is treated like the one-element vector `[A]'. The result is always a vector, except that if the set consists of a single interval, the interval itself is returned instead. *Note Logical Operations::, for the `in' function which tests if a certain value is a member of a given set. To test if the set `A' is a subset of the set `B', use `vdiff(A, B) = []'. The `V +' (`calc-remove-duplicates') [`rdup'] command converts an arbitrary vector into set notation. It works by sorting the vector as if by `V S', then removing duplicates. (For example, `[a, 5, 4, a, 4.0]' is sorted to `[4, 4.0, 5, a, a]' and then reduced to `[4, 5, a]'). Overlapping intervals are merged as necessary. You rarely need to use `V +' explicitly, since all the other set-based commands apply `V +' to their inputs before using them. The `V V' (`calc-set-union') [`vunion'] command computes the union of two sets. An object is in the union of two sets if and only if it is in either (or both) of the input sets. (You could accomplish the same thing by concatenating the sets with `|', then using `V +'.) The `V ^' (`calc-set-intersect') [`vint'] command computes the intersection of two sets. An object is in the intersection if and only if it is in both of the input sets. Thus if the input sets are disjoint, i.e., if they share no common elements, the result will be the empty vector `[]'. Note that the characters `V' and `^' were chosen to be close to the conventional mathematical notation for set union and intersection. The `V -' (`calc-set-difference') [`vdiff'] command computes the difference between two sets. An object is in the difference `A - B' if and only if it is in `A' but not in `B'. Thus subtracting `[y,z]' from a set will remove the elements `y' and `z' if they are present. You can also think of this as a general "set complement" operator; if `A' is the set of all possible values, then `A - B' is the "complement" of `B'. Obviously this is only practical if the set of all possible values in your problem is small enough to list in a Calc vector (or simple enough to express in a few intervals). The `V X' (`calc-set-xor') [`vxor'] command computes the "exclusive-or," or "symmetric difference" of two sets. An object is in the symmetric difference of two sets if and only if it is in one, but *not* both, of the sets. Objects that occur in both sets "cancel out." The `V ~' (`calc-set-complement') [`vcompl'] command computes the complement of a set with respect to the real numbers. Thus `vcompl(x)' is equivalent to `vdiff([-inf .. inf], x)'. For example, `vcompl([2, (3 .. 4]])' evaluates to `[[-inf .. 2), (2 .. 3], (4 .. inf]]'. The `V F' (`calc-set-floor') [`vfloor'] command reinterprets a set as a set of integers. Any non-integer values, and intervals that do not enclose any integers, are removed. Open intervals are converted to equivalent closed intervals. Successive integers are converted into intervals of integers. For example, the complement of the set `[2, 6, 7, 8]' is messy, but if you wanted the complement with respect to the set of integers you could type `V ~ V F' to get `[[-inf .. 1], [3 .. 5], [9 .. inf]]'. The `V E' (`calc-set-enumerate') [`venum'] command converts a set of integers into an explicit vector. Intervals in the set are expanded out to lists of all integers encompassed by the intervals. This only works for finite sets (i.e., sets which do not involve `-inf' or `inf'). The `V :' (`calc-set-span') [`vspan'] command converts any set of reals into an interval form that encompasses all its elements. The lower limit will be the smallest element in the set; the upper limit will be the largest element. For an empty set, `vspan([])' returns the empty interval `[0 .. 0)'. The `V #' (`calc-set-cardinality') [`vcard'] command counts the number of integers in a set. The result is the length of the vector that would be produced by `V E', although the computation is much more efficient than actually producing that vector. Another representation for sets that may be more appropriate in some cases is binary numbers. If you are dealing with sets of integers in the range 0 to 49, you can use a 50-bit binary number where a particular bit is 1 if the corresponding element is in the set. *Note Binary Functions::, for a list of commands that operate on binary numbers. Note that many of the above set operations have direct equivalents in binary arithmetic: `b o' (`calc-or'), `b a' (`calc-and'), `b d' (`calc-diff'), `b x' (`calc-xor'), and `b n' (`calc-not'), respectively. You can use whatever representation for sets is most convenient to you. The `b u' (`calc-unpack-bits') [`vunpack'] command converts an integer that represents a set in binary into a set in vector/interval notation. For example, `vunpack(67)' returns `[[0 .. 1], 6]'. If the input is negative, the set it represents is semi-infinite: `vunpack(-4) = [2 .. inf)'. Use `V E' afterwards to expand intervals to individual values if you wish. Note that this command uses the `b' (binary) prefix key. The `b p' (`calc-pack-bits') [`vpack'] command converts the other way, from a vector or interval representing a set of nonnegative integers into a binary integer describing the same set. The set may include positive infinity, but must not include any negative numbers. The input is interpreted as a set of integers in the sense of `V F' (`vfloor'). Beware that a simple input like `[100]' can result in a huge integer representation (`2^100', a 31-digit integer, in this case). File: calc.info, Node: Statistical Operations, Next: Reducing and Mapping, Prev: Set Operations, Up: Matrix Functions Statistical Operations on Vectors ================================= The commands in this section take vectors as arguments and compute various statistical measures on the data stored in the vectors. The references used in the definitions of these functions are Bevington's *Data Reduction and Error Analysis for the Physical Sciences*, and *Numerical Recipes* by Press, Flannery, Teukolsky and Vetterling. The statistical commands use the `u' prefix key followed by a shifted letter or other character. *Note Manipulating Vectors::, for a description of `V H' (`calc-histogram'). *Note Curve Fitting::, for the `a F' command for doing least-squares fits to statistical data. *Note Probability Distribution Functions::, for several common probability distribution functions. * Menu: * Single-Variable Statistics:: * Paired-Sample Statistics:: File: calc.info, Node: Single-Variable Statistics, Next: Paired-Sample Statistics, Prev: Statistical Operations, Up: Statistical Operations Single-Variable Statistics -------------------------- These functions do various statistical computations on single vectors. Given a numeric prefix argument, they actually pop N objects from the stack and combine them into a data vector. Each object may be either a number or a vector; if a vector, any sub-vectors inside it are "flattened" as if by `v a 0'; *note Manipulating Vectors::.. By default one object is popped, which (in order to be useful) is usually a vector. If an argument is a variable name, and the value stored in that variable is a vector, then the stored vector is used. This method has the advantage that if your data vector is large, you can avoid the slow process of manipulating it directly on the stack. These functions are left in symbolic form if any of their arguments are not numbers or vectors, e.g., if an argument is a formula, or a non-vector variable. However, formulas embedded within vector arguments are accepted; the result is a symbolic representation of the computation, based on the assumption that the formula does not itself represent a vector. All varieties of numbers such as error forms and interval forms are acceptable. Some of the functions in this section also accept a single error form or interval as an argument. They then describe a property of the normal or uniform (respectively) statistical distribution described by the argument. The arguments are interpreted in the same way as the M argument of the random number function `k r'. In particular, an interval with integer limits is considered an integer distribution, so that `[2 .. 6)' is the same as `[2 .. 5]'. An interval with at least one floating-point limit is a continuous distribution: `[2.0 .. 6.0)' is *not* the same as `[2.0 .. 5.0]'! The `u #' (`calc-vector-count') [`vcount'] command computes the number of data values represented by the inputs. For example, `vcount(1, [2, 3], [[4, 5], [], x, y])' returns 7. If the argument is a single vector with no sub-vectors, this simply computes the length of the vector. The `u +' (`calc-vector-sum') [`vsum'] command computes the sum of the data values. The `u *' (`calc-vector-prod') [`vprod'] command computes the product of the data values. If the input is a single flat vector, these are the same as `V R +' and `V R *' (*note Reducing and Mapping::.). The `u X' (`calc-vector-max') [`vmax'] command computes the maximum of the data values, and the `u N' (`calc-vector-min') [`vmin'] command computes the minimum. If the argument is an interval, this finds the minimum or maximum value in the interval. (Note that `vmax([2..6)) = 5' as described above.) If the argument is an error form, this returns plus or minus infinity. The `u M' (`calc-vector-mean') [`vmean'] command computes the average (arithmetic mean) of the data values. If the inputs are error forms `x +/- s', this is the weighted mean of the `x' values with weights `1 / s^2'. If the inputs are not error forms, this is simply the sum of the values divided by the count of the values. Note that a plain number can be considered an error form with error `s = 0'. If the input to `u M' is a mixture of plain numbers and error forms, the result is the mean of the plain numbers, ignoring all values with non-zero errors. (By the above definitions it's clear that a plain number effectively has an infinite weight, next to which an error form with a finite weight is completely negligible.) This function also works for distributions (error forms or intervals). The mean of an error form `a +/- b' is simply `a'. The mean of an interval is the mean of the minimum and maximum values of the interval. The `I u M' (`calc-vector-mean-error') [`vmeane'] command computes the mean of the data points expressed as an error form. This includes the estimated error associated with the mean. If the inputs are error forms, the error is the square root of the reciprocal of the sum of the reciprocals of the squares of the input errors. (I.e., the variance is the reciprocal of the sum of the reciprocals of the variances.) If the inputs are plain numbers, the error is equal to the standard deviation of the values divided by the square root of the number of values. (This works out to be equivalent to calculating the standard deviation and then assuming each value's error is equal to this standard deviation.) The `H u M' (`calc-vector-median') [`vmedian'] command computes the median of the data values. The values are first sorted into numerical order; the median is the middle value after sorting. (If the number of data values is even, the median is taken to be the average of the two middle values.) The median function is different from the other functions in this section in that the arguments must all be real numbers; variables are not accepted even when nested inside vectors. (Otherwise it is not possible to sort the data values.) If any of the input values are error forms, their error parts are ignored. The median function also accepts distributions. For both normal (error form) and uniform (interval) distributions, the median is the same as the mean. The `H I u M' (`calc-vector-harmonic-mean') [`vhmean'] command computes the harmonic mean of the data values. This is defined as the reciprocal of the arithmetic mean of the reciprocals of the values. The `u G' (`calc-vector-geometric-mean') [`vgmean'] command computes the geometric mean of the data values. This is the Nth root of the product of the values. This is also equal to the `exp' of the arithmetic mean of the logarithms of the data values. The `H u G' [`agmean'] command computes the "arithmetic-geometric mean" of two numbers taken from the stack. This is computed by replacing the two numbers with their arithmetic mean and geometric mean, then repeating until the two values converge. Another commonly used mean, the RMS (root-mean-square), can be computed for a vector of numbers simply by using the `A' command. The `u S' (`calc-vector-sdev') [`vsdev'] command computes the standard deviation of the data values. If the values are error forms, the errors are used as weights just as for `u M'. This is the *sample* standard deviation, whose value is the square root of the sum of the squares of the differences between the values and the mean of the `N' values, divided by `N-1'. This function also applies to distributions. The standard deviation of a single error form is simply the error part. The standard deviation of a continuous interval happens to equal the difference between the limits, divided by `sqrt(12)'. The standard deviation of an integer interval is the same as the standard deviation of a vector of those integers. The `I u S' (`calc-vector-pop-sdev') [`vpsdev'] command computes the *population* standard deviation. It is defined by the same formula as above but dividing by `N' instead of by `N-1'. The population standard deviation is used when the input represents the entire set of data values in the distribution; the sample standard deviation is used when the input represents a sample of the set of all data values, so that the mean computed from the input is itself only an estimate of the true mean. For error forms and continuous intervals, `vpsdev' works exactly like `vsdev'. For integer intervals, it computes the population standard deviation of the equivalent vector of integers. The `H u S' (`calc-vector-variance') [`vvar'] and `H I u S' (`calc-vector-pop-variance') [`vpvar'] commands compute the variance of the data values. The variance is the square of the standard deviation, i.e., the sum of the squares of the deviations of the data values from the mean. (This definition also applies when the argument is a distribution.) The `vflat' algebraic function returns a vector of its arguments, interpreted in the same way as the other functions in this section. For example, `vflat(1, [2, [3, 4]], 5)' returns `[1, 2, 3, 4, 5]'. File: calc.info, Node: Paired-Sample Statistics, Prev: Single-Variable Statistics, Up: Statistical Operations Paired-Sample Statistics ------------------------ The functions in this section take two arguments, which must be vectors of equal size. The vectors are each flattened in the same way as by the single-variable statistical functions. Given a numeric prefix argument of 1, these functions instead take one object from the stack, which must be an Nx2 matrix of data values. Once again, variable names can be used in place of actual vectors and matrices. The `u C' (`calc-vector-covariance') [`vcov'] command computes the sample covariance of two vectors. The covariance of vectors X and Y is the sum of the products of the differences between the elements of X and the mean of X times the differences between the corresponding elements of Y and the mean of Y, all divided by `N-1'. Note that the variance of a vector is just the covariance of the vector with itself. Once again, if the inputs are error forms the errors are used as weight factors. If both X and Y are composed of error forms, the error for a given data point is taken as the square root of the sum of the squares of the two input errors. The `I u C' (`calc-vector-pop-covariance') [`vpcov'] command computes the population covariance, which is the same as the sample covariance computed by `u C' except dividing by `N' instead of `N-1'. The `H u C' (`calc-vector-correlation') [`vcorr'] command computes the linear correlation coefficient of two vectors. This is defined by the covariance of the vectors divided by the product of their standard deviations. (There is no difference between sample or population statistics here.) File: calc.info, Node: Reducing and Mapping, Next: Vector and Matrix Formats, Prev: Statistical Operations, Up: Matrix Functions Reducing and Mapping Vectors ============================ The commands in this section allow for more general operations on the elements of vectors. The simplest of these operations is `V A' (`calc-apply') [`apply'], which applies a given operator to the elements of a vector. For example, applying the hypothetical function `f' to the vector `[1, 2, 3]' would produce the function call `f(1, 2, 3)'. Applying the `+' function to the vector `[a, b]' gives `a + b'. Applying `+' to the vector `[a, b, c]' is an error, since the `+' function expects exactly two arguments. While `V A' is useful in some cases, you will usually find that either `V R' or `V M', described below, is closer to what you want. * Menu: * Specifying Operators:: * Mapping:: * Reducing:: * Nesting and Fixed Points:: * Generalized Products:: File: calc.info, Node: Specifying Operators, Next: Mapping, Prev: Reducing and Mapping, Up: Reducing and Mapping Specifying Operators -------------------- Commands in this section (like `V A') prompt you to press the key corresponding to the desired operator. Press `?' for a partial list of the available operators. Generally, an operator is any key or sequence of keys that would normally take one or more arguments from the stack and replace them with a result. For example, `V A H C' uses the hyperbolic cosine operator, `cosh'. (Since `cosh' expects one argument, `V A H C' requires a vector with a single element as its argument.) You can press `x' at the operator prompt to select any algebraic function by name to use as the operator. This includes functions you have defined yourself using the `Z F' command. (*Note Algebraic Definitions::.) If you give a name for which no function has been defined, the result is left in symbolic form, as in `f(1, 2, 3)'. Calc will prompt for the number of arguments the function takes if it can't figure it out on its own (say, because you named a function that is currently undefined). It is also possible to type a digit key before the function name to specify the number of arguments, e.g., `V M 3 x f RET' calls `f' with three arguments even if it looks like it ought to have only two. This technique may be necessary if the function allows a variable number of arguments. For example, the `v e' [`vexp'] function accepts two or three arguments; if you want to map with the three-argument version, you will have to type `V M 3 v e'. It is also possible to apply any formula to a vector by treating that formula as a function. When prompted for the operator to use, press `'' (the apostrophe) and type your formula as an algebraic entry. You will then be prompted for the argument list, which defaults to a list of all variables that appear in the formula, sorted into alphabetic order. For example, suppose you enter the formula `x + 2y^x'. The default argument list would be `(x y)', which means that if this function is applied to the arguments `[3, 10]' the result will be `3 + 2*10^3'. (If you plan to use a certain formula in this way often, you might consider defining it as a function with `Z F'.) Another way to specify the arguments to the formula you enter is with `$', `$$', and so on. For example, `V A ' $$ + 2$^$$' has the same effect as the previous example. The argument list is automatically taken to be `($$ $)'. (The order of the arguments may seem backwards, but it is analogous to the way normal algebraic entry interacts with the stack.) If you press `$' at the operator prompt, the effect is similar to the apostrophe except that the relevant formula is taken from top-of-stack instead. The actual vector arguments of the `V A $' or related command then start at the second-to-top stack position. You will still be prompted for an argument list. A function can be written without a name using the notation `<#1 - #2>', which means "a function of two arguments that computes the first argument minus the second argument." The symbols `#1' and `#2' are placeholders for the arguments. You can use any names for these placeholders if you wish, by including an argument list followed by a colon: `'. When you type `V A ' $$ + 2$^$$ RET', Calc builds the nameless function `<#1 + 2 #2^#1>' as the function to map across the vectors. When you type `V A ' x + 2y^x RET RET', Calc builds the nameless function `'. In both cases, Calc also writes the nameless function to the Trail so that you can get it back later if you wish. If there is only one argument, you can write `#' in place of `#1'. (Note that `< >' notation is also used for date forms. Calc tells that `' is a nameless function by the presence of `#' signs inside STUFF, or by the fact that STUFF begins with a list of variables followed by a colon.) You can type a nameless function directly to `V A '', or put one on the stack and use it with `V A $'. Calc will not prompt for an argument list in this case, since the nameless function specifies the argument list as well as the function itself. In `V A '', you can omit the `< >' marks if you use `#' notation for the arguments, so that `V A ' #1+#2 RET' is the same as `V A ' <#1+#2> RET', which in turn is the same as `V A ' $$+$ RET'. The internal format for `' is `lambda(x, y, x + y)'. (The word `lambda' derives from Lisp notation and the theory of functions.) The internal format for `<#1 + #2>' is `lambda(ArgA, ArgB, ArgA + ArgB)'. Note that there is no actual Calc function called `lambda'; the whole point is that the `lambda' expression is used in its symbolic form, not evaluated for an answer until it is applied to specific arguments by a command like `V A' or `V M'. (Actually, `lambda' does have one special property: Its arguments are never evaluated; for example, putting `<(2/3) #>' on the stack will not simplify the `2/3' until the nameless function is actually called.) As usual, commands like `V A' have algebraic function name equivalents. For example, `V A k g' with an argument of `v' is equivalent to `apply(gcd, v)'. The first argument specifies the operator name, and is either a variable whose name is the same as the function name, or a nameless function like `<#^3+1>'. Operators that are normally written as algebraic symbols have the names `add', `sub', `mul', `div', `pow', `neg', `mod', and `vconcat'. The `call' function builds a function call out of several arguments: `call(gcd, x, y)' is the same as `apply(gcd, [x, y])', which in turn is the same as `gcd(x, y)'. The first argument of `call', like the other functions described here, may be either a variable naming a function, or a nameless function (`call(<#1+2#2>, x, y)' is the same as `x + 2y'). (Experts will notice that it's not quite proper to use a variable to name a function, since the name `gcd' corresponds to the Lisp variable `var-gcd' but to the Lisp function `calcFunc-gcd'. Calc automatically makes this translation, so you don't have to worry about it.) File: calc.info, Node: Mapping, Next: Reducing, Prev: Specifying Operators, Up: Reducing and Mapping Mapping ------- The `V M' (`calc-map') [`map'] command applies a given operator elementwise to one or more vectors. For example, mapping `A' [`abs'] produces a vector of the absolute values of the elements in the input vector. Mapping `+' pops two vectors from the stack, which must be of equal length, and produces a vector of the pairwise sums of the elements. If either argument is a non-vector, it is duplicated for each element of the other vector. For example, `[1,2,3] 2 V M ^' squares the elements of the specified vector. With the 2 listed first, it would have computed a vector of powers of two. Mapping a user-defined function pops as many arguments from the stack as the function requires. If you give an undefined name, you will be prompted for the number of arguments to use. If any argument to `V M' is a matrix, the operator is normally mapped across all elements of the matrix. For example, given the matrix `[[1, -2, 3], [-4, 5, -6]]', `V M A' takes six absolute values to produce another 3x2 matrix, `[[1, 2, 3], [4, 5, 6]]'. The command `V M _' [`mapr'] (i.e., type an underscore at the operator prompt) maps by rows instead. For example, `V M _ A' views the above matrix as a vector of two 3-element row vectors. It produces a new vector which contains the absolute values of those row vectors, namely `[3.74, 8.77]'. (Recall, the absolute value of a vector is defined as the square root of the sum of the squares of the elements.) Some operators accept vectors and return new vectors; for example, `v v' reverses a vector, so `V M _ v v' would reverse each row of the matrix to get a new matrix, `[[3, -2, 1], [-6, 5, -4]]'. Sometimes a vector of vectors (representing, say, strings, sets, or lists) happens to look like a matrix. If so, remember to use `V M _' if you want to map a function across the whole strings or sets rather than across their individual elements. The command `V M :' [`mapc'] maps by columns. Basically, it transposes the input matrix, maps by rows, and then, if the result is a matrix, transposes again. For example, `V M : A' takes the absolute values of the three columns of the matrix, treating each as a 2-vector, and `V M : v v' reverses the columns to get the matrix `[[-4, 5, -6], [1, -2, 3]]'. (The symbols `_' and `:' were chosen because they had row-like and column-like appearances, and were not already taken by useful operators. Also, they appear shifted on most keyboards so they are easy to type after `V M'.) The `_' and `:' modifiers have no effect on arguments that are not matrices (so if none of the arguments are matrices, they have no effect at all). If some of the arguments are matrices and others are plain numbers, the plain numbers are held constant for all rows of the matrix (so that `2 V M _ ^' squares every row of a matrix; squaring a vector takes a dot product of the vector with itself). If some of the arguments are vectors with the same lengths as the rows (for `V M _') or columns (for `V M :') of the matrix arguments, those vectors are also held constant for every row or column. Sometimes it is useful to specify another mapping command as the operator to use with `V M'. For example, `V M _ V A +' applies `V A +' to each row of the input matrix, which in turn adds the two values on that row. If you give another vector-operator command as the operator for `V M', it automatically uses map-by-rows mode if you don't specify otherwise; thus `V M V A +' is equivalent to `V M _ V A +'. (If you really want to map-by-elements another mapping command, you can use a triple-nested mapping command: `V M V M V A +' means to map `V M V A +' over the rows of the matrix; in turn, `V A +' is mapped over the elements of each row.) Previous versions of Calc had "map across" and "map down" modes that are now considered obsolete; the old "map across" is now simply `V M V A', and "map down" is now `V M : V A'. The algebraic functions `mapa' and `mapd' are still supported, though. Note also that, while the old mapping modes were persistent (once you set the mode, it would apply to later mapping commands until you reset it), the new `:' and `_' modifiers apply only to the current mapping command. The default `V M' always means map-by-elements. *Note Algebraic Manipulation::, for the `a M' command, which is like `V M' but for equations and inequalities instead of vectors. *Note Storing Variables::, for the `s m' command which modifies a variable's stored value using a `V M'-like operator. File: calc.info, Node: Reducing, Next: Nesting and Fixed Points, Prev: Mapping, Up: Reducing and Mapping Reducing -------- The `V R' (`calc-reduce') [`reduce'] command applies a given binary operator across all the elements of a vector. A binary operator is a function such as `+' or `max' which takes two arguments. For example, reducing `+' over a vector computes the sum of the elements of the vector. Reducing `-' computes the first element minus each of the remaining elements. Reducing `max' computes the maximum element and so on. In general, reducing `f' over the vector `[a, b, c, d]' produces `f(f(f(a, b), c), d)'. The `I V R' [`rreduce'] command is similar to `V R' except that works from right to left through the vector. For example, plain `V R -' on the vector `[a, b, c, d]' produces `a - b - c - d' but `I V R -' on the same vector produces `a - (b - (c - d))', or `a - b + c - d'. This "alternating sum" occurs frequently in power series expansions. The `V U' (`calc-accumulate') [`accum'] command does an accumulation operation. Here Calc does the corresponding reduction operation, but instead of producing only the final result, it produces a vector of all the intermediate results. Accumulating `+' over the vector `[a, b, c, d]' produces the vector `[a, a + b, a + b + c, a + b + c + d]'. The `I V U' [`raccum'] command does a right-to-left accumulation. For example, `I V U -' on the vector `[a, b, c, d]' produces the vector `[a - b + c - d, b - c + d, c - d, d]'. As for `V M', `V R' normally reduces a matrix elementwise. For example, given the matrix `[[a, b, c], [d, e, f]]', `V R +' will compute `a + b + c + d + e + f'. You can type `V R _' or `V R :' to modify this behavior. The `V R _' [`reducea'] command reduces "across" the matrix; it reduces each row of the matrix as a vector, then collects the results. Thus `V R _ +' of this matrix would produce `[a + b + c, d + e + f]'. Similarly, `V R :' [`reduced'] reduces down; `V R : +' would produce `[a + d, b + e, c + f]'. There is a third "by rows" mode for reduction that is occasionally useful; `V R =' [`reducer'] simply reduces the operator over the rows of the matrix themselves. Thus `V R = +' on the above matrix would get the same result as `V R : +', since adding two row vectors is equivalent to adding their elements. But `V R = *' would multiply the two rows (to get a single number, their dot product), while `V R : *' would produce a vector of the products of the columns. These three matrix reduction modes work with `V R' and `I V R', but they are not currently supported with `V U' or `I V U'. The obsolete reduce-by-columns function, `reducec', is still supported but there is no way to get it through the `V R' command. The commands `M-# :' and `M-# _' are equivalent to typing `M-# r' to grab a rectangle of data into Calc, and then typing `V R : +' or `V R _ +', respectively, to sum the columns or rows of the matrix. *Note Grabbing From Buffers::. File: calc.info, Node: Nesting and Fixed Points, Next: Generalized Products, Prev: Reducing, Up: Reducing and Mapping Nesting and Fixed Points ------------------------ The `H V R' [`nest'] command applies a function to a given argument repeatedly. It takes two values, `a' and `n', from the stack, where `n' must be an integer. It then applies the function nested `n' times; if the function is `f' and `n' is 3, the result is `f(f(f(a)))'. The number `n' may be negative if Calc knows an inverse for the function `f'; for example, `nest(sin, a, -2)' returns `arcsin(arcsin(a))'. The `H V U' [`anest'] command is an accumulating version of `nest': It returns a vector of `n+1' values, e.g., `[a, f(a), f(f(a)), f(f(f(a)))]'. If `n' is negative and `F' is the inverse of `f', then the result is of the form `[a, F(a), F(F(a)), F(F(F(a)))]'. The `H I V R' [`fixp'] command is like `H V R', except that it takes only an `a' value from the stack; the function is applied until it reaches a "fixed point," i.e., until the result no longer changes. The `H I V U' [`afixp'] command is an accumulating `fixp'. The first element of the return vector will be the initial value `a'; the last element will be the final result that would have been returned by `fixp'. For example, 0.739085 is a fixed point of the cosine function (in radians): `cos(0.739085) = 0.739085'. You can find this value by putting, say, 1.0 on the stack and typing `H I V U C'. (We use the accumulating version so we can see the intermediate results: `[1, 0.540302, 0.857553, 0.65329, ...]'. With a precision of six, this command will take 36 steps to converge to 0.739085.) Newton's method for finding roots is a classic example of iteration to a fixed point. To find the square root of five starting with an initial guess, Newton's method would look for a fixed point of the function `(x + 5/x) / 2'. Putting a guess of 1 on the stack and typing `H I V R ' ($ + 5/$)/2 RET' quickly yields the result 2.23607. This is equivalent to using the `a R' (`calc-find-root') command to find a root of the equation `x^2 = 5'. These examples used numbers for `a' values. Calc keeps applying the function until two successive results are equal to within the current precision. For complex numbers, both the real parts and the imaginary parts must be equal to within the current precision. If `a' is a formula (say, a variable name), then the function is applied until two successive results are exactly the same formula. It is up to you to ensure that the function will eventually converge; if it doesn't, you may have to press `C-g' to stop the Calculator. The algebraic `fixp' function takes two optional arguments, `n' and `tol'. The first is the maximum number of steps to be allowed, and must be either an integer or the symbol `inf' (infinity, the default). The second is a convergence tolerance. If a tolerance is specified, all results during the calculation must be numbers, not formulas, and the iteration stops when the magnitude of the difference between two successive results is less than or equal to the tolerance. (This implies that a tolerance of zero iterates until the results are exactly equal.) Putting it all together, `fixp(<(# + A/#)/2>, B, 20, 1e-10)' computes the square root of `A' given the initial guess `B', stopping when the result is correct within the specified tolerance, or when 20 steps have been taken, whichever is sooner. File: calc.info, Node: Generalized Products, Prev: Nesting and Fixed Points, Up: Reducing and Mapping Generalized Products -------------------- The `V O' (`calc-outer-product') [`outer'] command applies a given binary operator to all possible pairs of elements from two vectors, to produce a matrix. For example, `V O *' with `[a, b]' and `[x, y, z]' on the stack produces a multiplication table: `[[a x, a y, a z], [b x, b y, b z]]'. Element R,C of the result matrix is obtained by applying the operator to element R of the lefthand vector and element C of the righthand vector. The `V I' (`calc-inner-product') [`inner'] command computes the generalized inner product of two vectors or matrices, given a "multiplicative" operator and an "additive" operator. These can each actually be any binary operators; if they are `*' and `+', respectively, the result is a standard matrix multiplication. Element R,C of the result matrix is obtained by mapping the multiplicative operator across row R of the lefthand matrix and column C of the righthand matrix, and then reducing with the additive operator. Just as for the standard `*' command, this can also do a vector-matrix or matrix-vector inner product, or a vector-vector generalized dot product. Since `V I' requires two operators, it prompts twice. In each case, you can use any of the usual methods for entering the operator. If you use `$' twice to take both operator formulas from the stack, the first (multiplicative) operator is taken from the top of the stack and the second (additive) operator is taken from second-to-top.