The Salty Economist

Things I Should Have Learned in High School
posts - 56, comments - 0, trackbacks - 0

F# Matrix Type

Ok, so I'm poking around arrays in F#, and I come across a type called 'matrix.'  What the devil is this?

You can create a matrix like this:

let aMatrix = matrix [ [ 1.0; 7.0 ];
                       [ 1.0; 3.0 ];
                       [ 1.0; 11.0 ];
                       [ 1.0; 9.0 ];
                       [ 1.0; 6.0 ] ]

Of course, there some bugs.  If I run this in F# Interactive, I get:

"Tests.fs(10,15): error FS0039: The value or constructor 'matrix' is not defined. A construct with this name was found in FSharp.PowerPack.dll, which contains some modules and types that were implicitly referenced in some previous versions of F#. You may need to add an explicit reference to this DLL in order to compile this code."

But, it does work when compiled and run normally.  Go figure.

You can also do this:

let nn,kk = aMatrix.Dimensions

for i = 0 to nn-1 do
     printfn "%10.2f %10.2f %10.2f " aMatrix.[i,0] aMatrix.[i,1] aMatrix.[i,2]

Of course, the dimensions are not the bounds, but the number of elements, so you need to reference the matrix form 0 to nn-1.  You would think that C programmers would at least to concede that zero-based matrices are a terrible idea.  Also be aware that the dimensions are returned as a Tuple. 

What else have got?

Well, we can transpose it.

let bMatrix = aMatrix.Transpose

We can also make a copy:

let cMatrix = aMatrix.Copy

It also turns out that the multiplication operator is overloaded so this works:

let dMatrix = bMatrix * aMatrix 

Cool!!

 

Print | posted on Thursday, July 23, 2009 3:14 PM |

Powered by:
Powered By Subtext Powered By ASP.NET