F Sharp And MATLAB
Last changed: -213.199.128.155

.
Summary

Vectors and Matrices

As of version 1.1.5 F# now comes with vector and matrix types. You can also use 1D and 2D arrays directly or build your own abstractions for these types, based on 1D and 2D arrays underneath

MATLAB Expressions in F#

Here is a list of typical expressions in MATLAB and their equivalents in F# using the F# matrix library.

To open the matirx library use

 open Math
 open Math.Matrix
 open Math.Notation
Expression semantic MATLAB expression F# 1.1.10
create an empty matrix/vector x = []; let x = matrix [ [] ]
create a column vector x = [1;2;4]; let x = vector [1.0;2.0;4.0]
create a row vector x = 1 2 4; let x = matrix [[1.; 2.; 4.]]
create a matrix A = [[1 2];[3 4];[5 6]]; let A = matrix [[1.; 2.]; [3.; 4.]; [5.; 6.]]
access an element A(3,1); A.[2,0]
matrix transpose A'; A.Transpose

To use generic matrix types use the same notation and:

 open Math
 open Math.Matrix.Generic
 open Math.Notation.Generic

Using MATLAB for Visualization

It is dead easy to use MATLAB automation from F#. First you need a DLL that gives access to the MATLAB COM objects from .NET. You just use the tlbimp.exe tool in the .NET Framework SDK (also comes with Visual Studio) to create this DLL, e.g.:

 tlbimp "c:\Program Files\MATLAB\R2006a\bin\win32\mlapp.tlb"

Then you can access MATLAB workspaces programatically and from F# Interactive. Here is an example where we use MATLAB to create some nice looking plots:

 #light 


 #r "Interop.MLApp.dll"


 let matlab = new MLApp.MLAppClass () 
 matlab.Execute "x = linspace (0,2*pi,1000); plot (x, sin (x), 'b-', 'LineWidth', 3)"


 open Math


 module Matrix = begin
     let of_array2 (x:float [,]) = Math.Matrix.init (x |> Array2.length1) (x |> Array2.length2) (fun i j -> x.[i,j])
 end


 /// Returns a variable from the MATLAB workspace
 let GetVaraible name = 
     (matlab.GetVariable (name, "base") :?> float [,]) |> Array2.copy |> Matrix.of_array2


 /// Puts a matrix into the MATLAB workspace
 let PutVariable name (data:matrix) = 
     let tmp = Array2.init data.NumRows data.NumCols (fun i j -> data.[i,j])
     matlab.PutWorkspaceData (name, "base", tmp)




 let X = Matrix.init 1 1000 (fun i j -> (float j) / 1000.0)
 let Y = X |> Matrix.map (fun x -> sin (x) * cos (x))
 PutVariable "X1" X
 PutVariable "Y1" Y
 matlab.Execute "plot (X1, Y1, 'r-', 'LineWidth', 2)"


 let A = Matrix.init 300 300 (fun i j -> sin ((float i) / 30.) * cos ((float j) / 20.))
 PutVariable "A" A
 matlab.Execute "surfl (A); shading interp; colormap copper"