Summary: this tutorial demonstrates some of the functionality for matrices and vectors provided by FSharp.Stats.
open FSharp.Stats
let v =
vector [|2.0; 20.0; 1.|]
vector [|2.0; 20.0; 1.0|]
|
let rv =
rowvec [|2.0; 20.0; 1.|]
rowvec [|2.0; 20.0; 1.0|]
|
Addition to every element of vector.
v + 1.
vector [|3.0; 21.0; 2.0|]
|
Addition to every element of row vector.
rv + 1.
rowvec [|3.0; 21.0; 2.0|]
|
Matrices will also be printed with the FSharp.Stats.FSIPrinters.matrix function to get a nice console output.
open FSharp.Stats
// http://fdatamining.blogspot.de/2010/03/matrix-and-linear-algebra-in-f-part-i-f.html
// http://fdatamining.blogspot.de/search/label/linear%20algebra
let A =
matrix [ [ 1.0; 7.0; 2.0 ]
[ 1.0; 3.0; 1.0 ]
[ 2.0; 9.0; 1.0 ] ]
"
0 1 2
_____________________________________
0 | 1.000 7.000 2.000
1 | 1.000 3.000 1.000
2 | 2.000 9.000 1.000
"
|
let B =
matrix [ [ 10.0; 70.0; 20.0 ]
[ 10.0; 30.0; 10.0 ]
[ 20.0; 90.0; 10.0 ] ]
"
0 1 2
_____________________________________
0 | 10.000 70.000 20.000
1 | 10.000 30.000 10.000
2 | 20.000 90.000 10.000
"
|
Get sum of each row.
A
|> Matrix.Generic.mapRows (Seq.sum)
vector [|10.0; 5.0; 12.0|]
|
Create seq of vectors of matrix columns.
A
|> Matrix.mapiCols (fun i r -> r)
rowvec [|vector ...; vector ...; vector ...|]
|
Sum of two matrices.
A + B
"
0 1 2
_____________________________________
0 | 11.000 77.000 22.000
1 | 11.000 33.000 11.000
2 | 22.000 99.000 11.000
"
|
Difference between two matrices.
A - B
"
0 1 2
_____________________________________
0 | -9.00 -63.00 -18.00
1 | -9.00 -27.00 -9.00
2 | -18.00 -81.00 -9.00
"
|
Product of two matrices.
A * B
"
0 1 2
_____________________________________
0 | 120.000 460.000 110.000
1 | 60.000 250.000 60.000
2 | 130.000 500.000 140.000
"
|
Element-wise product of two matrices
A .* B
"
0 1 2
_____________________________________
0 | 10.000 490.000 40.000
1 | 10.000 90.000 10.000
2 | 40.000 810.000 10.000
"
|
Scalar product of a matrix.
A * 2.0
2.0 * A // also ok, gives same result
"
0 1 2
_____________________________________
0 | 2.000 14.000 4.000
1 | 2.000 6.000 2.000
2 | 4.000 18.000 2.000
"
|
Negation of a matrix
-A
"
0 1 2
_____________________________________
0 | -1.00 -7.00 -2.00
1 | -1.00 -3.00 -1.00
2 | -2.00 -9.00 -1.00
"
|
Product of a matrix-vector.
A * v
vector [|144.0; 63.0; 185.0|]
|
Dot product of two matrices.
Matrix.dot A B
Addition to every element of matrix.
A + 1.
"
0 1 2
_____________________________________
0 | 2.000 8.000 3.000
1 | 2.000 4.000 2.000
2 | 3.000 10.000 2.000
"
|