source resource:/tcl/pkg/jtcllib/library/amath/amath.tcl

#### Vectors and matrices can be created either from Tcl lists:

#A 2 row by 3 column matrix: set m {{1 2 3} {4 5 6}} #A 3 element vector set v {1 2 3}

#### or by using the matrix command.

# matrix create -rows numberOfRows -col numberOfCols ?-var varName? ?-identity? ?-randn sdevValue? ?-complex? set m [matrix create -rows 5 -cols 4 -randn 0.3] # or matrix create -rows 5 -cols 4 -randn 0.3 -var musing the 2nd form ensures that, in interactive use, the contents of the matrix will not be converted to a string and displayed in the console, a bad situation for a really large matrix.

### The = command

This command works much like Tcl's built-in expression command (and is in fact derived from it). The "expr" and "=" commands essentially provide a domain-specific language inside of Tcl for performing math. Some aspects of "=" were inspired by the Tcl Expr PatchThere are four main differences that the "=" command has compared to "expr".- There is no need to use braces around the arguments.
- Variables do not need to be prefixed with a "$".
- Variables can be math or vector objects
- There are additional functions available.

set y [expr {$a*$x + $b}]whereas with the "=" command it would be:

set y [= a*x + b]Since the arguments to the "=" command can be vectors or matrices one can often eliminate one or more levels of loops in calculations. So using the above equations to calculate the y coordinates for a series of x coordinates in Tcl would be something like:

set xValues {1 2 3 4 5 6} set yValues [list] foreach x $xValues { set y [expr {$a*$x+$b}] lappend yValues $y }with the "=" command it can be expressed as:

set x {1 2 3 4 5 6} set y [= a*x+b]

#### More examples

source resource:/tcl/pkg/jtcllib/library/amath/amath.tcl # create vector from Tcl list set a {1 2 3} # Do math on vector (gets converted internally to an Apache Commons RealVector] set b [= a*4] set c [= a+b] # Create matrix with ::amath::matrix command set myMat [matrix create -rows 3 -cols 3] # Create a matrix and do some linear algebra (singular value decomposition) set m {{1 2} {3 4}} set m [= tr(m)] lassign [svd $m] u s v set vt [= tr(v)] set usvt [= u*s*vt] set diffM [= m-usvt] set diffNorm [norm $diffM] puts $diffNorm # Use math function on matrix set mlog [= log(m)] # Element-wise multiplication ( .* operator) set mElemSq [= m.*m] puts $mElemSq # use mset command and colon notation to set all elements of the first column to 5 mset m(:,0) 5 # create a complex value and do some math set xc {3+4i} set yc [= 4*xc] puts $yc