home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-385-Vol-1of3.iso / n / newmat06.zip / NEWMATA.TXT < prev    next >
Text File  |  1992-12-03  |  44KB  |  1,247 lines

  1. //$$ newmata.txt                                   Documentation file
  2.  
  3.  
  4.    Documentation for newmat06, an experimental matrix package in C++.
  5.    ==================================================================
  6.  
  7.  
  8. MATRIX PACKAGE                                           1 December, 1992
  9.  
  10. Copyright (C) 1991,2: R B Davies
  11.  
  12. Permission is granted to use but not to sell.
  13.  
  14.  
  15. Contents
  16. ========
  17.  
  18. General description
  19. Is this the package you need?
  20. Changes
  21. Where you can get a copy of this package
  22. Compiler performance
  23. Example
  24. Detailed documentation
  25.    Customising
  26.    Constructors
  27.    Elements of matrices
  28.    Matrix copy
  29.    Unary operators
  30.    Binary operators
  31.    Combination of a matrix and scalar
  32.    Scalar functions of matrices
  33.    Submatrix operations
  34.    Change dimensions
  35.    Change type
  36.    Multiple matrix solve
  37.    Memory management
  38.    Output
  39.    Accessing matrices of unspecified type
  40.    Cholesky decomposition
  41.    Householder triangularisation
  42.    Singular Value Decomposition
  43.    Eigenvalues
  44.    Sorting
  45.    Fast Fourier Transform
  46.    Interface to Numerical Recipes in C
  47.    Exceptions
  48.    Clean up following an exception
  49. List of files
  50. Problem report form
  51.  
  52.  
  53. ---------------------------------------------------------------------------
  54.  
  55.  
  56. General description
  57. ===================
  58.  
  59. The package is intented for scientists and engineers who need to
  60. manipulate a variety of types of matrices using standard matrix
  61. operations. Emphasis is on the kind of operations needed in statistical
  62. calculations such as least squares, linear equation solve and
  63. eigenvalues.
  64.  
  65. It supports matrix types
  66.  
  67.     Matrix                       (rectangular matrix)
  68.     nricMatrix                   (variant of rectangular matrix)
  69.     UpperTriangularMatrix
  70.     LowerTriangularMatrix
  71.     DiagonalMatrix
  72.     SymmetricMatrix
  73.     BandMatrix
  74.     UpperBandMatrix              (upper triangular band matrix)
  75.     LowerBandMatrix              (lower triangular band matrix)
  76.     SymmetricBandMatrix
  77.     RowVector                    (derived from Matrix)
  78.     ColumnVector                 (derived from Matrix).
  79.  
  80. Only one element type (float or double) is supported.
  81.  
  82. The package includes the operations *, +, -, inverse, transpose,
  83. conversion between types, submatrix, determinant, Cholesky
  84. decomposition, Householder triangularisation, singular value
  85. decomposition, eigenvalues of a symmetric matrix, sorting, fast fourier
  86. transform, printing and an interface with "Numerical Recipes in C".
  87.  
  88. It is intended for matrices in the range 4 x 4 to the maximum size your
  89. machine will accomodate in a single array. That is 90 x 90 (125 x 125
  90. for triangular matrices) in machines that have 8192 doubles as the
  91. maximum size of an array. It will work for very small matrices but
  92. becomes rather inefficient.
  93.  
  94. A two-stage approach to evaluating matrix expressions is used to improve
  95. efficiency and reduce use of temporary storage.
  96.  
  97. The package is designed for version 2 or 3 of C++. It works with Borland
  98. C++ on a PC and AT&T C++ (2.1 & 3) and Gnu C++ (2.2) on a Sun. It works
  99. with some problems with Zortech C++ (version 3).
  100.  
  101.  
  102. ---------------------------------------------------------------------------
  103.  
  104.  
  105. Is this the package you need?
  106. =============================
  107.  
  108. Do you
  109.  
  110. 1.   need matrix operators such as * and + defined as operators so you
  111.      can write things like
  112.  
  113.         X  = A * (B + C);
  114.  
  115. 2.   need a variety of types of matrices
  116.  
  117. 3.   need only one element type (float or double)
  118.  
  119. 4.   work with matrices in the range 4x4 to 90x90
  120.  
  121. 5.   tolerate a large package
  122.  
  123.  
  124. Then maybe this is the right package for you. 
  125.  
  126. If you don't need (1) then there may be better options. Likewise if you
  127. don't need (2) there may be better options. If you require "not (5)"
  128. then this is not the package for you.
  129.  
  130.  
  131. If you need (2) and "not (3)" and have some spare money, then maybe you
  132. should look at M++ from Dyad or the Rogue Wave matrix package.
  133.  
  134.  
  135. If you need not (4); that is very large matrices that will need to be
  136. stored on disk, there is a package YAMP on CompuServe under the Borland
  137. C++ library that might be of interest.
  138.  
  139.  
  140. Details of some other free C or C++ matrix packages follow - extracted
  141. from the list assembled by ajayshah@usc.edu.
  142.  
  143. Name: SPARSE
  144. Where: in sparse on Netlib
  145. Description: library for LU factorisation for large sparse matrices 
  146. Author: Ken Kundert, Alberto Sangiovanni-Vincentelli,
  147.      sparse@ic.berkeley.edu
  148.  
  149. Name: matrix.tar.Z
  150. Where: in ftp-raimund/pub/src/Math on nestroy.wu-wien.ac.at
  151.      (137.208.3.4)
  152. Author: Paul Schmidt, TI
  153. Description: Small matrix library, including SOR, WLS
  154.  
  155. Name: matrix04.zip
  156. Where: in mirrors/msdos/c on wuarchive.wustl.edu
  157. Description: Small matrix toolbox
  158.  
  159. Name: Matrix.tar.Z
  160. Where: in pub ftp.cs.ucla.edu
  161. Description: The C++ Matrix class, including a matrix implementation of
  162.      the backward error propagation (backprop) algorithm for training
  163.      multi-layer, feed-forward artificial neural networks
  164. Author: E. Robert (Bob) Tisdale, edwin@cs.ucla.edu
  165.  
  166. Name: meschach
  167. Where: in c/meschach on netlib
  168. Systems: Unix, PC
  169. Description: a library for matrix computation; more functionality than
  170.      Linpack; nonstandard matrices
  171. Author: David E. Stewart, des@thrain.anu.edu.au
  172. Version: 1.0, Feb 1992
  173.  
  174. Name: nlmdl
  175. Where: in pub/arg/nlmdl at ccvr1.cc.ncsu.edu (128.109.212.20)
  176. Language: C++
  177. Systems: Unix, MS-DOS (Turbo C++)
  178. Description: a library for estimation of nonlinear models
  179. Author: A. Ronald Gallant, arg@ccvr1.cc.ncsu.edu
  180. Comments: nonlinear maximisation, estimation, includes a real matrix
  181.      class
  182. Version: January 1991
  183.  
  184.  
  185.  
  186. ---------------------------------------------------------------------------
  187.  
  188.  
  189. Changes
  190. =======
  191.  
  192. Newmat06 - December 1992:
  193.  
  194. Added band matrices; 'real' changed to 'Real' (to avoid potential
  195. conflict in complex class); Inject doesn't check for no loss of
  196. information;  fixes for AT&T C++ version 3.0; real(A) becomes
  197. A.AsScalar(); CopyToMatrix becomes AsMatrix, etc; .c() is no longer
  198. required (to be deleted in next version); option for version 2.1 or
  199. later. Suffix for include files changed to .h; BOOL changed to Boolean
  200. (BOOL doesn't work in g++ v 2.0); modfications to allow for compilers
  201. that destroy temporaries very quickly; (Gnu users - see the section of
  202. compiler performance). Added CleanUp, LinearEquationSolver, primitive
  203. version of exceptions.
  204.  
  205.  
  206. Newmat05 - June 1992:
  207.  
  208. For private release only 
  209.  
  210.  
  211. Newmat04 - December 1991:
  212.  
  213. Fix problem with G++1.40, some extra documentation
  214.  
  215.  
  216. Newmat03 - November 1991:
  217.  
  218. Col and Cols become Column and Columns. Added Sort, SVD, Jacobi,
  219. Eigenvalues, FFT, real conversion of 1x1 matrix, "Numerical Recipes in
  220. C" interface, output operations, various scalar functions. Improved
  221. return from functions. Reorganised setting options in "include.hxx".
  222.  
  223.  
  224. Newmat02 - July 1991:
  225.  
  226. Version with matrix row/column operations and numerous additional
  227. functions.
  228.  
  229.  
  230. Matrix - October 1990:
  231.  
  232. Early version of package.
  233.  
  234.  
  235. ---------------------------------------------------------------------------
  236.  
  237.  
  238. How to get a copy of this package
  239. =================================
  240.  
  241. I am putting copies on Compuserve (Borland library, zip format),
  242. SIMTEL20 (MsDos library, zip format), comp.sources.misc on Internet
  243. (shar format).
  244.  
  245.  
  246. ---------------------------------------------------------------------------
  247.  
  248.  
  249. Compiler performance
  250. ====================
  251.  
  252. I have tested this package on a number of compilers. Here are the levels
  253. of success with this package. In most cases I have chosen code that
  254. works under all the compilers I have access to, but I have had to
  255. include some specific work-arounds for some compilers. For the MsDos
  256. versions, I use a 486dx computer running MsDos 5. The unix versions are
  257. on a Sun Sparc station or a Silicon Graphics or a HP unix workstation.
  258. Thanks to Victoria University and Industrial Research Ltd for access to
  259. the Unix machines.
  260.  
  261. A series of #defines at the beginning of "include.h" customises the
  262. package for the compiler you are using. Turbo, Borland, Gnu and Zortech
  263. are recognised automatically, otherwise you have to set the appropriate
  264. #define statement. Activate the option for version 2.1 if you are using
  265. version 2.1 of C++ or later.
  266.  
  267. Borland C++ 3.1: Recently, this has been my main development platform,
  268. so naturally almost everything works with this compiler. Make sure you
  269. have the compiler option "treat enums as ints" set. There was a problem
  270. with the library utility in version 2.0 which is now fixed. You will
  271. need to use the large model. If you are not debugging, turn off the
  272. options that collect debugging information.
  273.  
  274. Zortech C++ 3.0: "const" doesn't work correctly with this compiler, so
  275. the package skips all of the statements Zortech can't handle. Zortech
  276. leaves rubbish on the heap. I don't know whether this is my programming
  277. error or a Zortech error or additional printer buffers. Deactivate the
  278. option for version 2.1 in include.h. Does not support IO manipulators.
  279. Otherwise the package mostly works, but not completely.
  280.  
  281. Glockenspiel C++ (2.00a for MsDos loading into Microsoft C 5.1): I
  282. haven't tested the latest version of my package with Glockenspiel. I had
  283. to #define the matrix names to shorter names to avoid ambiguities and
  284. had quite a bit of difficulty stopping the compiles from running out of
  285. space and not exceeding Microsoft's block nesting limit. A couple of my
  286. test statements produced statements too complex for Microsoft, but
  287. basically the package worked. This was my original development platform
  288. and I still use .cxx as my file name extensions for the C++ files.
  289.  
  290. Sun AT&T C++ 2.1;3.0: This works fine. Except aggregates are not
  291. supported in 2.1 and setjmp.h generated a warning message. Neither
  292. compiler would compile when I set DO_FREE_CHECK (see my file
  293. newmatc.txt).
  294.  
  295. Gnu G++ 2.2:  This mostly works. You can't use expressions like
  296. Matrix(X*Y) in the middle of an expression and (Matrix)(X*Y) is
  297. unreliable. If you write a function returning a matrix, you MUST use the
  298. ReturnMatrix method described in this documentation. This is because g++
  299. destroys temporaries occuring in an expression too soon for the two
  300. stage way of evaluating expressions that newmat uses. Gnu 2.2 does seem
  301. to leave some rubbish on the stack. I suspect this is a printer buffer
  302. so it may not be a bug. There were a number of warning messages from the
  303. compiler about my "unconstanting" constants; but I think this was just
  304. gnu being over-sensitive.
  305.  
  306. JPI: Their second release worked on a previous version of this package
  307. provided you disabled the smart link option - it isn't smart enough. I
  308. haven't tested the latest version of this package.
  309.  
  310.  
  311. ---------------------------------------------------------------------------
  312.  
  313. Example
  314. =======
  315.  
  316. An example is given in  example.cxx .  This gives a simple linear
  317. regression example using four different algorithms. The correct output
  318. is given in example.txt. The program carries out a check that no memory
  319. is left allocated on the heap when it terminates. The file  example.mak
  320. is a make file for compiling example.cxx under gnu g++. Use the gnu make
  321. facility. You can probably adapt for the compiler you are using.
  322.  
  323.  ---------------------------------------------------------------------
  324. | Don't forget to remove references to  newmat9.cxx  in the make file |
  325. | if you are using a compiler that does not support the standard io   |
  326. | manipulators.                                                       |
  327.  ---------------------------------------------------------------------
  328.  
  329. ---------------------------------------------------------------------------
  330.  
  331.  
  332. Detailed Documentation
  333. ======================
  334.  
  335. Copyright (C) 1989,1990,1991,1992: R B Davies
  336.  
  337. Permission is granted to use but not to sell.
  338.  
  339.    --------------------------------------------------------------
  340.   | Please understand that this is a test version; there may     |
  341.   | still be bugs and errors. Use at your own risk. I take no    |
  342.   | responsibility for any errors or omissions in this package   |
  343.   | or for any misfortune that may befall you or others as a     |
  344.   | result of its use.                                           |
  345.    --------------------------------------------------------------
  346.  
  347. Please report bugs to me at
  348.  
  349.     robertd@kauri.vuw.ac.nz
  350.  
  351. or
  352.  
  353.     Compuserve 72777,656
  354.  
  355. When reporting a bug please tell me which C++ compiler you are using (if
  356. known), and what version. Also give me details of your computer (if
  357. known). Tell me where you downloaded your version of my package from and
  358. its version number (eg newmat03 or newmat04). (There may be very minor
  359. differences between versions at different sites). Note any changes you
  360. have made to my code. If at all possible give me a piece of code
  361. illustrating the bug.
  362.  
  363. Please do report bugs to me.
  364.  
  365.  
  366. The matrix inverse routine and the sort routines are adapted from
  367. "Numerical Recipes in C" by Press, Flannery, Teukolsky, Vetterling,
  368. published by the Cambridge University Press.
  369.  
  370. Other code is adapted from routines in "Handbook for Automatic
  371. Computation, Vol II, Linear Algebra" by Wilkinson and Reinsch, published
  372. by Springer Verlag. 
  373.  
  374.  
  375. Customising
  376. -----------
  377.  
  378. I use .h as the suffix of definition files and .cxx as the suffix of
  379. C++ source files. This does not cause any problems with the compilers I
  380. use except that Borland and Turbo need to be told to accept any suffix
  381. as meaning a C++ file rather than a C file.
  382.  
  383. Use the large model when you are using a PC. Do not "outline" inline
  384. functions.
  385.  
  386. Each file accessing the matrix package needs to have file newmat.h 
  387. #included  at the beginning. Files using matrix applications (Cholesky
  388. decomposition, Householder triangularisation etc) need newmatap.h
  389. instead (or as well). If you need the output functions you will also
  390. need newmatio.h.
  391.  
  392. The file  include.h  sets the options for the compiler. If you are using
  393. a compiler different from one I have worked with you may have to set up
  394. a new section in  include.h  appropriate for your compiler.
  395.  
  396. Borland, Turbo, Gnu and Zortech are recognised automatically. If you
  397. using Glockenspiel on a PC, AT&T activate the appropriate statement at
  398. the beginning of include.h.
  399.  
  400. Activate the appropriate statement to make the element type float or
  401. double.
  402.  
  403. If you are using version 2.1 or later of C++ make sure Version21 is
  404. #defined, otherwise make sure it is not #defined.
  405.  
  406. The file (newmat9.cxx) containing the output routines can be used only
  407. with libraries that support the AT&T input/output routines including
  408. manipulators. It cannot be used with Zortech or Gnu.
  409.  
  410. You will need to compile all the *.cxx files except example.cxx and the
  411. tmt*.cxx files to to get the complete package. The tmt*.cxx files are
  412. used for testing and example.cxx is an example. The files tmt.mak and
  413. example.mak are "make" files for unix systems. Edit in the correct name
  414. of compiler. This "make" file worked for me with the default "make" on
  415. the HP unix workstation and the Sun sparc station and gmake on the
  416. Silicon Graphics. With Borland, its pretty quick just to load all the
  417. files in the interactive environment by pointing and clicking.
  418.  
  419.  
  420. Constructors
  421. ------------
  422.  
  423. To construct an m x n matrix, A, (m and n are integers) use
  424.  
  425.     Matrix A(m,n);
  426.  
  427. The UpperTriangularMatrix, LowerTriangularMatrix, SymmetricMatrix and
  428. DiagonalMatrix types are square. To construct an n x n matrix use,
  429. for example
  430.  
  431.     UpperTriangularMatrix U(n);
  432.  
  433. Band matrices need to include bandwidth information in their
  434. constructors.
  435.  
  436.     BandMatrix BM(n, lower, upper);
  437.     UpperBandMatrix UB(n, upper);
  438.     LowerBandMatrix LB(n, lower);
  439.     SymmetrixBandMatrix SB(n, lower);
  440.  
  441. The integers upper and lower are the number of non-zero diagonals above
  442. and below the diagonal (excluding the diagonal) respectively.
  443.  
  444. The RowVector and ColumnVector types take just one argument in their
  445. constructors:
  446.  
  447.     RowVector RV(n);
  448.  
  449. You can also construct vectors and matrices without specifying the
  450. dimension. For example
  451.  
  452.     Matrix A;
  453.  
  454. In this case the dimension must be set by an assignment statement or a
  455. re-dimension statement.
  456.  
  457. You can also use a constructor to set a matrix equal to another matrix
  458. or matrix expression.
  459.  
  460.     Matrix A = U;
  461.  
  462.     Matrix A = U * L;
  463.  
  464. Only conversions that don't lose information are supported - eg you
  465. cannot convert an upper triangular matrix into a diagonal matrix using =.
  466.  
  467.  
  468. Elements of matrices
  469. --------------------
  470.  
  471. Elements are accessed by expressions of the form A(i,j) where i and j
  472. run from 1 to the appropriate dimension. Access elements of vectors with
  473. just one argument. Diagonal matrices can accept one or two subscripts.
  474.  
  475. This is different from the earliest version of the package in which the
  476. subscripts ran from 0 to one less than the appropriate dimension. Use
  477. A.element(i,j) if you want this earlier convention.
  478.  
  479. A(i,j) and A.element(i,j) can appear on either side of an = sign.
  480.  
  481.  
  482. Matrix copy
  483. -----------
  484.  
  485. The operator = is used for copying matrices, converting matrices, or
  486. evaluating expressions. For example
  487.  
  488.     A = B;  A = L;  A = L * U;
  489.  
  490. Only conversions that don't lose information are supported. The
  491. dimensions of the matrix on the left hand side are adjusted to those of
  492. the matrix or expression on the right hand side. Elements on the right
  493. hand side which are not present on the left hand side are set to zero.
  494.  
  495. The operator << can be used in place of = where it is permissible for
  496. information to be lost.
  497.  
  498. For example
  499.  
  500.     SymmetricMatrix S; Matrix A;
  501.     ......
  502.     S << A.t() * A;
  503.  
  504. is acceptable whereas
  505.  
  506.     S = A.t() * A;                            // error
  507.  
  508. will cause a runtime error since the package does not (yet) recognise
  509. A.t()*A as symmetric.
  510.  
  511. Note that you can not use << with constructors. For example
  512.  
  513.     SymmetricMatrix S << A.t() * A;           // error
  514.  
  515. does not work.
  516.  
  517. Also note that << cannot be used to load values from a full matrix into
  518. a band matrix, since it will be unable to determine the bandwidth of the
  519. band matrix.
  520.  
  521. A third copy routine is used in a similar role to =. Use
  522.  
  523.     A.Inject(D);
  524.  
  525. to copy the elements of D to the corresponding elements of A but leave
  526. the elements of A unchanged if there is no corresponding element of D
  527. (the = operator would set them to 0). This is useful, for example, for
  528. setting the diagonal elements of a matrix without disturbing the rest of
  529. the matrix. Unlike = and <<, Inject does not reset the dimensions of A,
  530. which must match those of D. Inject does not test for no loss of
  531. information.
  532.  
  533. You cannot replace D by a matrix expression. The effect of Inject(D)
  534. depends on the type of D. If D is an expression it might not be obvious
  535. to the user what type it would have. So I thought it best to disallow
  536. expressions.
  537.  
  538. Inject can be used for loading values from a regular matrix into a band
  539. matrix. (Don't forget to zero any elements of the left hand side that
  540. will not be set by the loading operation).
  541.  
  542. Both << and Inject can be used with submatrix expressions on the left
  543. hand side. See the section on submatrices.
  544.  
  545. To set the elements of a matrix to a scalar use operator =
  546.  
  547.     Real r; Matrix A(m,n);
  548.     ......
  549.     Matrix A(m,n); A = r;
  550.  
  551. You can load the elements of a matrix from an array:
  552.  
  553.     Matrix A(3,2);
  554.     Real a[] = { 11,12,21,22,31,33 };
  555.     A << a;
  556.  
  557. This construction cannot check that the numbers of elements match
  558. correctly. This version of << can be used with submatrices on the left
  559. hand side.
  560.  
  561.  
  562. Unary operators
  563. ---------------
  564.  
  565. The package supports unary operations
  566.  
  567.     change sign of elements            -A
  568.     transpose                          A.t()
  569.     inverse (of square matrix A)       A.i()
  570.  
  571.  
  572. Binary operations
  573. -----------------
  574.  
  575. The package supports binary operations
  576.  
  577.     matrix addition                    A+B
  578.     matrix subtraction                 A-B
  579.     matrix multiplication              A*B
  580.     equation solve (square matrix A)   A.i()*B
  581.  
  582. In the last case the inverse is not calculated.
  583.  
  584. Notes:
  585.  
  586. If you are doing repeated multiplication. For example A*B*C, use
  587. brackets to force the order to minimize the number of operations. If C
  588. is a column vector and A is not a vector, then it will usually reduce
  589. the number of operations to use A*(B*C) .
  590.  
  591. The package does not recognise B*A.i() as an equation solve. It is
  592. probably better to use (A.t().i()*B.t()).t() .
  593.  
  594.  
  595. Combination of a matrix and scalar
  596. ----------------------------------
  597.  
  598. The following expression multiplies the elements of a matrix A by a
  599. scalar f:  A * f; Likewise one can divide the elements of a matrix A by
  600. a scalar f:  A / f;
  601.  
  602. The expressions  A + f and A - f add or subtract a rectangular matrix of
  603. the same dimension as A with elements equal to f to or from the matrix
  604. A.
  605.  
  606. In each case the matrix must be the first term in the expression.
  607. Expressions such  f + A  or  f * A  are not recognised.
  608.  
  609.  
  610. Scalar functions of matrices
  611. ----------------------------
  612.             
  613.     int m = A.Nrows();                    // number of rows
  614.     int n = A.Ncols();                    // number of columns
  615.     Real ssq = A.SumSquare();             // sum of squares of elements
  616.     Real sav = A.SumAbsoluteValue();      // sum of absolute values
  617.     Real mav = A.MaximumAbsoluteValue();  // maximum of absolute values
  618.     Real norm = A.Norm1();                // maximum of sum of absolute
  619.                                              values of elements of a column
  620.     Real norm = A.NormInfinity();         // maximum of sum of absolute
  621.                                              values of elements of a row
  622.     Real t = A.Trace();                   // trace
  623.     LogandSign ld = A.LogDeterminant();   // log of determinant
  624.     Boolean z = A.IsZero();               // test all elements zero
  625.     MatrixType mt = A.Type();             // type of matrix
  626.     Real* s = Store();                    // pointer to array of elements
  627.     int l = Storage();                    // length of array of elements
  628.  
  629. A.LogDeterminant() returns a value of type LogandSign. If ld is of type 
  630. LogAndSign  use
  631.  
  632.     ld.Value()    to get the value of the determinant
  633.     ld.Sign()     to get the sign of the determinant (values 1, 0, -1)
  634.     ld.LogValue() to get the log of the absolute value.
  635.  
  636. A.IsZero() returns Boolean value TRUE if the matrix A has all elements
  637. equal to 0.0.
  638.  
  639. MatrixType mt = A.Type() returns the type of a matrix. Use (char*)mt to
  640. get a string  (UT, LT, Rect, Sym, Diag, RowV, ColV, Crout, BndLU)
  641. showing the type.
  642.  
  643. SumSquare(A), SumAbsoluteValue(A), MaximumAbsoluteValue(A), Trace(A),
  644. LogDeterminant(A), Norm1(A), NormInfinity(A)  can be used in place of
  645. A.SumSquare(), A.SumAbsoluteValue(), A.MaximumAbsoluteValue(),
  646. A.Trace(), A.LogDeterminant(), A.Norm1(), A.NormInfinity().
  647.  
  648.  
  649. Submatrix operations
  650. --------------------
  651.  
  652. A.SubMatrix(fr,lr,fc,lc)
  653.  
  654. This selects a submatrix from A. the arguments  fr,lr,fc,lc  are the
  655. first row, last row, first column, last column of the submatrix with the
  656. numbering beginning at 1. This may be used in any matrix expression or
  657. on the left hand side of << or Inject. Inject does not check no
  658. information loss. You can also use the construction
  659.  
  660.     Real c; .... A.SubMatrix(fr,lr,fc,lc) << c;
  661.  
  662. to set a submatrix equal to a constant.
  663.  
  664. The follwing are variants of SubMatrix:
  665.  
  666.     A.SymSubMatrix(f,l)             //   This assumes fr=fc and lr=lc.
  667.     A.Rows(f,l)                     //   select rows
  668.     A.Row(f)                        //   select single row
  669.     A.Columns(f,l)                  //   select columns
  670.     A.Column(f)                     //   select single column
  671.  
  672. In each case f and l mean the first and last row or column to be
  673. selected (starting at 1).
  674.  
  675. If SubMatrix or its variant occurs on the right hand side of an = or <<
  676. or within an expression its type is as follows
  677.  
  678.     A.Submatrix(fr,lr,fc,lc):           If A is RowVector or
  679.                                         ColumnVector then same type
  680.                                         otherwise type Matrix
  681.     A.SymSubMatrix(f,l):                Same type as A
  682.     A.Rows(f,l):                        Type Matrix
  683.     A.Row(f):                           Type RowVector
  684.     A.Columns(f,l):                     Type Matrix
  685.     A.Column(f):                        Type ColumnVector
  686.  
  687.  
  688. If SubMatrix or its variant appears on the left hand side of  << , think
  689. of its type being Matrix. Thus L.Row(1) where L is LowerTriangularMatrix
  690. expects  L.Ncols()  elements even though it will use only one of them.
  691.  
  692.  
  693. Change dimensions
  694. -----------------
  695.  
  696. The following operations change the dimensions of a matrix. The values
  697. of the elements are lost.
  698.  
  699.     A.ReDimension(nrows,ncols);     // for type Matrix or nricMatrix
  700.     A.ReDimension(n);               // for all other types, except Band
  701.     A.ReDimension(n,lower,upper);   // for BandMatrix
  702.     A.ReDimension(n,lower);         // for LowerBandMatrix
  703.     A.ReDimension(n,upper);         // for UpperBandMatrix
  704.     A.ReDimension(n,lower);         // for SymmetricBandMatrix
  705.  
  706. Use   A.CleanUp()  to set the dimensions of A to zero and release all
  707. the heap memory.
  708.  
  709.  
  710. Change type
  711. -----------
  712.  
  713. The following functions interpret the elements of a matrix
  714. (stored row by row) to be a vector or matrix of a different type. Actual
  715. copying is usually avoided where these occur as part of a more
  716. complicated expression.
  717.  
  718.     A.AsRow()
  719.     A.AsColumn()
  720.     A.AsDiagonal()
  721.     A.AsMatrix(nrows,ncols)
  722.     A.AsScalar()
  723.  
  724. The expression A.AsScalar() is used to convert a 1 x 1 matrix to a
  725. scalar.
  726.  
  727.  
  728. Multiple matrix solve
  729. ---------------------
  730.  
  731. If A is a square or symmetric matrix use
  732.  
  733.     CroutMatrix X = A;                // carries out LU decomposition
  734.     Matrix AP = X.i()*P; Matrix AQ = X.i()*Q;
  735.     LogAndSign ld = X.LogDeterminant();
  736.  
  737. rather than
  738.  
  739.     Matrix AP = A.i()*P; Matrix AQ = A.i()*Q;
  740.     LogAndSign ld = A.LogDeterminant();
  741.  
  742. since each operation will repeat the LU decomposition.
  743.  
  744. If A is a BandMatrix or a SymmetricBandMatrix begin with
  745.  
  746.     BandLUMatrix X = A;               // carries out LU decomposition
  747.  
  748. A CroutMatrix or a BandLUMatrix can't be manipulated or copied. Use
  749. references as an alternative to copying.
  750.  
  751. Alternatively use
  752.  
  753.     LinearEquationSolver X = A;
  754.  
  755. This will choose the most appropiate decomposition of A. That is, the
  756. band form if A is banded; the Crout decomposition if A is square or
  757. symmetric and no decomposition if A is triangular or diagonal. If you
  758. want to use the LinearEquationSolver #include newmatap.h.
  759.  
  760.  
  761. Memory management
  762. -----------------
  763.  
  764. The package does not support delayed copy. Several strategies are
  765. required to prevent unnecessary matrix copies.
  766.  
  767. Where a matrix is called as a function argument use a constant
  768. reference. For example
  769.  
  770.     YourFunction(const Matrix& A)
  771.  
  772. rather than
  773.  
  774.     YourFunction(Matrix A)
  775.  
  776.  
  777. Skip the rest of this section on your first reading.
  778.  
  779.  --------------------------------------------------------------------- 
  780. |  Gnu g++ users please read on; if you are returning matrix values   |
  781. |  from a function, then you must use the ReturnMatrix construct.     |
  782.  ---------------------------------------------------------------------
  783.  
  784. A second place where it is desirable to avoid unnecessary copies is when
  785. a function is returning a matrix. Matrices can be returned from a
  786. function with the return command as you would expect. However these may
  787. incur one and possibly two copyings of the matrix. To avoid this use the
  788. following instructions.
  789.  
  790. Make your function of type  ReturnMatrix . Then precede the return
  791. statement with a Release statement (or a ReleaseAndDelete statement if
  792. the matrix was created with new). For example
  793.  
  794.  
  795.     ReturnMatrix MakeAMatrix()
  796.     {
  797.        Matrix A;
  798.        ......
  799.        A.Release(); return A;
  800.     }
  801.  
  802. or
  803.  
  804.     ReturnMatrix MakeAMatrix()
  805.     {
  806.        Matrix* m = new Matrix;
  807.        ......
  808.        m->ReleaseAndDelete(); return *m;
  809.     }
  810.  
  811.  
  812. If you are using AT&T C++ you may wish to replace  return A; by
  813. return (ReturnMatrix)A;  to avoid a warning message.
  814.  
  815.  
  816.  --------------------------------------------------------------------- 
  817. | Do not forget to make the function of type ReturnMatrix; otherwise  |
  818. | you may get incomprehensible run-time errors.                       |
  819.  --------------------------------------------------------------------- 
  820.  
  821. You can also use .Release() or ->ReleaseAndDelete() to allow a matrix
  822. expression to recycle space. Suppose you call
  823.  
  824.     A.Release();
  825.  
  826. just before A is used just once in an expression. Then the memory used
  827. by A is either returned to the system or reused in the expression. In
  828. either case, A's memory is destroyed. This procedure can be used to
  829. improve efficiency and reduce the use of memory.
  830.  
  831. Use ->ReleaseAndDelete for matrices created by new if you want to
  832. completely delete the matrix after it is accessed.
  833.  
  834.  
  835. Output
  836. ------
  837.  
  838. To print a matrix use an expression like
  839.  
  840.     Matrix A;
  841.     ......
  842.     cout << setw(10) << setprecision(5) << A;
  843.  
  844. This will work only with systems that support the AT&T input/output
  845. routines including manipulators.
  846.  
  847.  
  848. Accessing matrices of unspecified type
  849. --------------------------------------
  850.  
  851. Skip this section on your first reading.
  852.  
  853. Suppose you wish to write a function which accesses a matrix of unknown
  854. type including expressions (eg A*B). Then use a layout similar to the
  855. following:
  856.  
  857.    void YourFunction(BaseMatrix& X)
  858.    {
  859.       GeneralMatrix* gm = X.Evaluate();   // evaluate an expression
  860.                                           // if necessary
  861.       ........                            // operations on *gm
  862.       gm->tDelete();                      // delete *gm if a temporary
  863.    }
  864.  
  865. See, as an example, the definitions of operator<< in newmat9.cxx.
  866.  
  867. Under certain circumstances; particularly where X is to be used just
  868. once in an expression you can leave out the Evaluate() statement and the
  869. corresponding tDelete(). Just use X in the expression.
  870.  
  871. If you know YourFunction will never have to handle a formula as its
  872. argument you could also use
  873.  
  874.    void YourFunction(const GeneralMatrix& X)
  875.    {
  876.       ........                            // operations on X
  877.    }
  878.  
  879.  
  880. Cholesky decomposition
  881. ----------------------
  882.  
  883. Suppose S is symmetric and positive definite. Then there exists a unique
  884. lower triangular matrix L such that L * L.t() = S. To calculate this use
  885.  
  886.     SymmetricMatrix S;
  887.     ......
  888.     LowerTriangularMatrix L = Cholesky(S);
  889.  
  890. If S is a symmetric band matrix then L is a band matrix and an
  891. alternative procedure is provied for carrying out the decomposition:
  892.  
  893.     SymmetricBandMatrix S;
  894.     ......
  895.     LowerBandMatrix L = Cholesky(S);
  896.  
  897.  
  898. Householder triangularisation
  899. -----------------------------
  900.  
  901. Start with matrix
  902.  
  903.        / X    0 \      s
  904.        \ Y    0 /      t
  905.  
  906.          n    s
  907.  
  908. The Householder triangularisation post multiplies by an orthogonal
  909. matrix Q such that the matrix becomes
  910.  
  911.        / 0    L \      s
  912.        \ Z    M /      t
  913.  
  914.          n    s
  915.  
  916. where L is lower triangular. Note that X is the transpose of the matrix
  917. sometimes considered in this context.
  918.  
  919. This is good for solving least squares problems: choose b (matrix or row
  920. vector) to minimize the sum of the squares of the elements of
  921.  
  922.          Y - b*X
  923.  
  924. Then choose b = M * L.i();
  925.  
  926. Two routines are provided:
  927.  
  928.     HHDecompose(X, L);
  929.  
  930. replaces X by orthogonal columns and forms L.
  931.  
  932.     HHDecompose(X, Y, M);
  933.  
  934. uses X from the first routine, replaces Y by Z and forms M.
  935.  
  936.  
  937. Singular Value Decomposition
  938. ----------------------------
  939.  
  940. The singular value decomposition of an m x n matrix A ( where m >= n) is
  941. a decomposition
  942.  
  943.     A  = U * D * V.t()
  944.  
  945. where U is m x n with  U.t() * U  equalling the identity, D is an n x n
  946. diagonal matrix and V is an n x n orthogonal matrix.
  947.  
  948. Singular value decompositions are useful for understanding the structure
  949. of ill-conditioned matrices, solving least squares problems, and for
  950. finding the eigenvalues of A.t() * A.
  951.  
  952. To calculate the singular value decomposition of A (with m >= n) use one
  953. of
  954.  
  955.     SVD(A, D, U, V);                  // U (= A is OK)
  956.     SVD(A, D);
  957.     SVD(A, D, U);                     // U (= A is OK)
  958.     SVD(A, D, U, FALSE);              // U (can = A) for workspace only
  959.     SVD(A, D, U, V, FALSE);           // U (can = A) for workspace only
  960.  
  961. The values of A are not changed unless A is also inserted as the third
  962. argument.
  963.  
  964.  
  965. Eigenvalues
  966. -----------
  967.  
  968. An eigenvalue decomposition of a symmetric matrix A is a decomposition
  969.  
  970.     A  = V * D * V.t()
  971.  
  972. where V is an orthogonal matrix and D is a diagonal matrix.
  973.  
  974. Eigenvalue analyses are used in a wide variety of engineering,
  975. statistical and other mathematical analyses.
  976.  
  977. The package includes two algorithms: Jacobi and Householder. The first
  978. is extremely reliable but much slower than the second.
  979.  
  980. The code is adapted from routines in "Handbook for Automatic
  981. Computation, Vol II, Linear Algebra" by Wilkinson and Reinsch, published
  982. by Springer Verlag. 
  983.  
  984.  
  985.     Jacobi(A,D,S,V);                  // A, S symmetric; S is workspace,
  986.                                       //    S = A is OK
  987.     Jacobi(A,D);                      // A symmetric
  988.     Jacobi(A,D,S);                    // A, S symmetric; S is workspace,
  989.                                       //    S = A is OK
  990.     Jacobi(A,D,V);                    // A symmetric
  991.  
  992.     EigenValues(A,D);                 // A symmetric
  993.     EigenValues(A,D,S);               // A, S symmetric; S is for back
  994.                                       //    transforming, S = A is OK
  995.     EigenValues(A,D,V);               // A symmetric
  996.  
  997.  
  998. Sorting
  999. -------
  1000.  
  1001. To sort the values in a matrix or vector, A, (in general this operation
  1002. makes sense only for vectors and diagonal matrices) use
  1003.  
  1004.     SortAscending(A);
  1005.  
  1006. or
  1007.  
  1008.     SortDescending(A);
  1009.  
  1010. I use the Shell-sort algorithm. This is a medium speed algorithm, you
  1011. might want to replace it with something faster if speed is critical and
  1012. your matrices are large.
  1013.  
  1014.  
  1015. Fast Fourier Transform
  1016. ----------------------
  1017.  
  1018. FFT(CV1, CV2, CV3, CV4);       // CV3=CV1 and CV4=CV2 is OK
  1019.  
  1020. where CV1, CV2, CV3, CV4 are column vectors. CV1 and CV2 are the real
  1021. and imaginary input vectors; CV3 and CV4 are the real and imaginary
  1022. output vectors. The lengths of CV1 and CV2 must be equal and should be
  1023. the product of numbers less than about 10 for fast execution.
  1024.  
  1025.  
  1026. Interface to Numerical Recipes in C
  1027. -----------------------------------
  1028.  
  1029. This package can be used with the vectors and matrices defined in
  1030. "Numerical Recipes in C". You need to edit the routines in Numerical
  1031. Recipes so that the elements are of the same type as used in this
  1032. package. Eg replace float by double, vector by dvector and matrix by
  1033. dmatrix, etc. You will also need to edit the function definitions to use
  1034. the version acceptable to your compiler. Then enclose the code from
  1035. Numerical Recipes in  extern "C" { ... }. You will also need to include
  1036. the matrix and vector utility routines.
  1037.  
  1038. Then any vector in Numerical Recipes with subscripts starting from 1 in
  1039. a function call can be accessed by a RowVector, ColumnVector or
  1040. DiagonalMatrix in the present package. Similarly any matrix with
  1041. subscripts starting from 1 can be accessed by an  nricMatrix  in the
  1042. present package. The class nricMatrix is derived from Matrix and can be
  1043. used in place of Matrix. In each case, if you wish to refer to a
  1044. RowVector, ColumnVector, DiagonalMatrix or nricMatrix X in an function
  1045. from Numerical Recipes, use X.nric() in the function call.
  1046.  
  1047. Numerical Recipes cannot change the dimensions of a matrix or vector. So
  1048. matrices or vectors must be correctly dimensioned before a Numerical
  1049. Recipes routine is called.
  1050.  
  1051. For example
  1052.  
  1053.    SymmetricMatrix B(44);
  1054.    .....                             // load values into B
  1055.    nricMatrix BX = B;                // copy values to an nricMatrix
  1056.    DiagonalMatrix D(44);             // Matrices for output
  1057.    nricMatrix V(44,44);              //    correctly dimensioned
  1058.    int nrot;
  1059.    jacobi(BX.nric(),44,D.nric(),V.nric(),&nrot);
  1060.                                      // jacobi from NRIC
  1061.    cout << D;                        // print eigenvalues
  1062.  
  1063.  
  1064. Exceptions
  1065. ----------
  1066.  
  1067. This package includes a partial implementation of exceptions. I used
  1068. Carlos Vidal's article in the September 1992 C Users Journal as a
  1069. starting point.
  1070.  
  1071. Newmat does a partial clean up of memory following throwing an exception
  1072. - see the next section. However, the present version will leave a little
  1073. heap memory unrecovered under some circumstances. I would not expect
  1074. this to be a problem in most circumstances, but it is something that
  1075. needs to be sorted out.
  1076.  
  1077. The functions/macros I define are Try, Throw, Catch, CatchAll and
  1078. CatchAndThrow. Try, Throw, Catch and CatchAll correspond to try, throw,
  1079. catch and catch(...) in the C++ standard. A list of Catch clauses must
  1080. be terminated by either CatchAll or CatchAndThrow but not both. Throw
  1081. takes an Exception as an argument or takes no argument (for passing on
  1082. an exception). I do not have a version of Throw for specifying which
  1083. exceptions a function might throw. Catch takes an exception class name
  1084. as an argument; CatchAll and CatchAndThrow don't have any arguments.
  1085. Try, Catch and CatchAll must be followed by blocks enclosed in curly
  1086. brackets.
  1087.  
  1088. All Exceptions must be derived from a class, Exception, defined in
  1089. newmat and can contain only static variables. See the examples in newmat
  1090. if you want to define additional exceptions.
  1091.  
  1092. I have defined 5 clases of exceptions for users (there are others but I
  1093. suggest you stick to these ones):
  1094.  
  1095.    SpaceException                 Insufficient space on the heap
  1096.    ProgramException               Errors such as out of range index or
  1097.                                   incompatible matrix types or
  1098.                                   dimensions
  1099.    ConvergenceException           Iterative process does not converge
  1100.    DataException                  Errors such as attempting to invert a
  1101.                                   singular matrix
  1102.    InternalException              Probably a programming error in newmat
  1103.  
  1104. For each of these exception classes, I have defined a member function
  1105. void SetAction(int). If you call SetAction(1), and a corresponding
  1106. exception occurs, you will get an error message. If there is a Catch
  1107. clause for that exception, execution will be passed to that clause,
  1108. otherwise the program will exit. If you call SetAction(0) you will get
  1109. the same response, except that there will be no error message. If you
  1110. call SetAction(-1), you will get the error message but the program will
  1111. always exit.
  1112.  
  1113. I have defined a class Tracer that is intended to help locate the place
  1114. where an error has occurred. At the beginning of a function I suggest
  1115. you include a statement like
  1116.  
  1117.    Tracer tr("name");
  1118.  
  1119. where name is the name of the function. This name will be printed as
  1120. part of the error message, if an exception occurs in that function, or
  1121. in a function called from that function. You can change the name as you
  1122. proceed through a function with the ReName function
  1123.  
  1124.    tr.ReName("new name");
  1125.  
  1126. if, for example, you want to track progress through the function.
  1127.  
  1128.  
  1129. Clean up following an exception
  1130. -------------------------------
  1131.  
  1132. The exception mechanisms in newmat are based on the C functions setjmp
  1133. and longjmp. These functions do not call destructors so can lead to
  1134. garbage being left on the heap. (I refer to memory allocated by "new" as
  1135. heap memory). For example, when you call
  1136.  
  1137. Matrix A(20,30);
  1138.  
  1139. a small amount of space is used on the stack containing the row and
  1140. column dimensions of the matrix and 600 doubles are allocated on the
  1141. heap for the actual values of the matrix. At the end of the block in
  1142. which A is declared, the destructor for A is called and the 600
  1143. doubles are freed. The locations on the stack are freed as part of the
  1144. normal operations of the stack. If you leave the block using a longjmp
  1145. command those 600 doubles will not be freed and will occupy space until
  1146. the program terminates.
  1147.  
  1148. To overcome this problem newmat keeps a list of all the currently
  1149. declared matrices and its exception mechanism will return heap memory
  1150. when you do a Throw and Catch.
  1151.  
  1152. However it will not return heap memory from objects from other packages.
  1153. If you want the mechanism to work with another class you will have to do
  1154. three things:
  1155.  
  1156. 1: derive your class from class Janitor defined in except.h;
  1157.  
  1158. 2: define a function void CleanUp() in that class to return all heap
  1159.    memory;
  1160.  
  1161. 3: include the following lines in the class definition
  1162.  
  1163.       public:
  1164.          void* operator new(size_t size)
  1165.          { do_not_link=TRUE; void* t = ::operator new(size); return t; }
  1166.  
  1167.  
  1168.  
  1169.  
  1170.  
  1171.  
  1172. ---------------------------------------------------------------------------
  1173.  
  1174.  
  1175. List of files
  1176. =============
  1177.  
  1178. README          readme file
  1179. NEWMATA  TXT    documentation file
  1180. NEWMATB  TXT    notes on the package design
  1181. NEWMATC  TXT    notes on testing the package
  1182.  
  1183. BOOLEAN  H      boolean class definition
  1184. CONTROLW H      control word definition file
  1185. EXCEPT   H      general exception handler definitions
  1186. INCLUDE  H      details of include files and options
  1187. NEWMAT   H      main matrix class definition file
  1188. NEWMATAP H      applications definition file
  1189. NEWMATIO H      input/output definition file
  1190. NEWMATRC H      row/column functions definition files
  1191. NEWMATRM H      rectangular matrix access definition files
  1192. PRECISIO H      numerical precision constants
  1193.  
  1194. BANDMAT  CXX    band matrix routines
  1195. CHOLESKY CXX    Cholesky decomposition
  1196. ERROR    CXX    general error handler
  1197. EVALUE   CXX    eigenvalues and eigenvector calculation
  1198. FFT      CXX    fast Fourier transform
  1199. HHOLDER  CXX    Householder triangularisation
  1200. JACOBI   CXX    eigenvalues by the Jacobi method
  1201. NEWMAT1  CXX    type manipulation routines
  1202. NEWMAT2  CXX    row and column manipulation functions
  1203. NEWMAT3  CXX    row and column access functions
  1204. NEWMAT4  CXX    constructors, redimension, utilities
  1205. NEWMAT5  CXX    transpose, evaluate, matrix functions
  1206. NEWMAT6  CXX    operators, element access
  1207. NEWMAT7  CXX    invert, solve, binary operations
  1208. NEWMAT8  CXX    LU decomposition, scalar functions
  1209. NEWMAT9  CXX    output routines
  1210. NEWMATEX CXX    matrix exception handler
  1211. NEWMATRM CXX    rectangular matrix access functions
  1212. SORT     CXX    sorting functions
  1213. SUBMAT   CXX    submatrix functions
  1214. SVD      CXX    singular value decomposition
  1215.  
  1216. EXAMPLE  CXX    example of use of package
  1217. EXAMPLE  TXT    output from example
  1218. EXAMPLE  MAK    make file for example
  1219.  
  1220. ---------------------------------------------------------------------------
  1221.  
  1222.                    Matrix package problem report form
  1223.                    ----------------------------------
  1224.  
  1225. Version: ...............newmat06
  1226. Date of release: .......December 1st, 1992
  1227. Primary site: ..........
  1228. Downloaded from: .......
  1229. Your email address: ....
  1230. Today's date: ..........
  1231. Your machine: ..........
  1232. Operating system: ......
  1233. Compiler & version: ....
  1234. Describe the problem - attach examples if possible:
  1235.  
  1236.  
  1237.  
  1238.  
  1239.  
  1240.  
  1241.  
  1242.  
  1243.  
  1244. Email to  robertd@kauri.vuw.ac.nz  or  Compuserve 72777,656 
  1245.  
  1246. -------------------------------------------------------------------------------
  1247.