CamlFloat Tutorial
The simplest commands for creating matrices are zeros m n (as above), ones m n
and the more general consts x m n. The last of these creates an m by n matrix, all of whose entries
have the value x and includes the first two as special cases.
# consts 4.5 2 3;;
4.5 4.5 4.5
4.5 4.5 4.5
- : Nla.DBlop.matrix =
The following lines show how to generate an identity matrix and a random matrix.
# eye 3 3;; 1 0 0 0 1 0 0 0 1 - : Nla.DBlop.matrix = # randomMatrix 3 3;; 0.17 -0.18 -0.019 -0.72 -0.37 -0.12 -0.34 -0.75 -0.3 - : Nla.DBlop.matrix =
One of the most useful methods of building consists of defining a matrix via a function.
That is, we first define a function f: i j -> A(i,j) and then instruct camlFloat
to use this function as the definition of our matrix.
Consider generating the Hilbert matrix defined by the formula
. We code this as
# let hilbertFormula i j = 1. /. float_of_int (i+j-1) ;;
val hilbertFormula : int -> int -> float = <fun>
and then use fun2mat to generate our matrix.
# fun2mat hilbertFormula 4 4;;
1 0.5 0.33 0.25
0.5 0.33 0.25 0.2
0.33 0.25 0.2 0.17
0.25 0.2 0.17 0.14
- : Nla.DBlop.matrix =
The inner cast by float_of_int in the hilbertFormula is needed to calculate a float from
the integer indeces of the matrix.
Individual entries of a matrix are accessed with the operator $@. The sytax here is
that the (i, j) element of A is accessed by A $@ (i, j). Each
entry is of type Nla.DBlop.t, but this is just camlFloat's way of
dealing with doubles so the entries can be treated as doubles.
# let b = fun2mat hilbertFormula 3 3 ;; 1 0.5 0.33 0.5 0.33 0.25 0.33 0.25 0.2 val b : Nla.DBlop.matrix = # let b22 = b $@ (2,2) ;; val b22 : Nla.DBlop.t = 0.333333333333333315 # b22 +. 3.0 ;; - : float = 3.33333333333333348
Two functions which are not really used to construct matrices but which should be mentioned are
noOfRows and noOfCols. These are used pretty much as you would expect.
# let g = eye 5 6 ;; 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 val g : Nla.DBlop.matrix = # noOfRows g ;; - : int = 5 # noOfCols g ;; - : int = 6
::: back :::