F# Matrix Transpose, Multiply

Well, I have finally decided to write some econometrics routines in F#.  I first did this type of stuff in FORTRAN when I was a grad student, so I figured I'd try to see if I could still figure it all out.

But, first things first.

We need routines to Transpose a matrix and to Multiply two matrices.

My transpose method is this:

--------------------------------------------------------------
//
//  Let's make up some data
//

let n = 6
let k = 3

//  Create data array - n x k

let x0 = Array2D.zeroCreate<float> n k

x0.[0,0] <- 1.0
x0.[1,0] <- 1.0
x0.[2,0] <- 1.0
x0.[3,0] <- 1.0
x0.[4,0] <- 1.0
x0.[5,0] <- 1.0

x0.[0,1] <- 22.0
x0.[1,1] <- 4.0
x0.[2,1] <- 13.0
x0.[3,1] <- 3.0
x0.[4,1] <- 9.0
x0.[5,1] <- -3.0

x0.[0,2] <- 12.0
x0.[1,2] <- 14.0
x0.[2,2] <- 19.0
x0.[3,2] <- 9.0
x0.[4,2] <- 13.0
x0.[5,2] <- 23.0

//---------------------------------------------------
// Transpose a Matrix
// Takes matrix x and returns the transpose as xp
// NEWLY UPDATED VERSION 8/12/2009
//---------------------------------------------------

let rec transposeACol(x : float [,] ) (xp : float [,] ) (i : int) (j : int) =
    match j with
    | -1 -> xp
    | _ -> xp.[j, i] <- x.[i, j]
           //printfn "i: %i j: %i x: %10.5f" i j (if i >=0 && j >=0 then x.[i, j] else -1.0)
           //let userresp = Console.ReadLine()
           let xp = transposeACol x xp i (j-1)
           xp
          
let rec transpose (x : float [,] ) (xp : float [,] ) (i : int) (j : int) =
    match i with
    | -1 -> xp
    | _  -> let xp = transposeACol x xp i j 
            let xp = transpose x xp (i-1) j
            xp

// Create a shell array, k x n
let zero_xp = Array2D.zeroCreate<float> k n

//-----------------------------------------
// Create X Prime
//-----------------------------------------
//
// Handle the fact that matrices are zero based: use n-1, k-1 as starting points
//

let xp = transpose x0 zero_xp (n-1) (k-1)

//
//Print xp
//
// Print it out
for i = 0 to k - 1 do
     printfn "%10.2f %10.2f %10.2f %10.2f %10.2f %10.2f" xp.[i,0] xp.[i,1] xp.[i,2] xp.[i,3] xp.[i,4] xp.[i,5]

--------------------------------------------------------------

The method transpose is a recursive method that starts at the top for both n and k and works down to zero, flipping the elements as it goes.  You send it a blank array and it returns the transpose.  I know I could have done this with a couple of for..do loops, but I wanted to practice writing recursive functions in F#.

Note the Array function Array2D.zeroCreate<float> k n.  This function creates a two dimensional array (floating point) with k rows and n columns.  It is prefilled with zeros.  The array is zero-based.  There is also a method Array.create that allows you to specify the initial value (instead of zero).

 So we run the code, and here's what we get:

      1.00       1.00       1.00       1.00       1.00       1.00
     22.00       4.00      13.00       3.00       9.00      -3.00
     12.00      14.00      19.00       9.00      13.00      23.00

The next thing we need to code is a matrix multiplication routine.

If you aren't familiar with matrix multiplication, here is Wikipedia's page: http://en.wikipedia.org/wiki/Matrix_multiplication

The idea here is that you have a matrix that is dimensioned n x k and you want to multiply it bay a matrix of dimension k x m.  The two k's must be the same.  The resulting matrix is dimensioned n x m.

So, for example, if we have two matrices xp (2 x 4) and x (4 x 2), the resulting matrix (xpx) will have be dimensioned 2 x 2 and the i,jth item will be:

xpx[i, j] = (xp[i,0] * x[0,j]) + (xp[i,1] * x[1,j]) + (xp[i,2] * x[2,j]) + (xp[i,3] * x[3,j])

So here's my code:

-----------------------------------------------------------------------------

let accum (x1 : float) (x2 : float) (ac : float) =
    ac + (x1 * x2)

let rec xply (xp : float [,] ) (x : float [,] ) (j0 : int) (j1 : int) (i : int) (cell_accum : float) =
    match i with
    | 0 -> accum xp.[j0, i] x.[i, j1]  cell_accum
    | _  -> xply xp x j0 j1 (i-1) (accum xp.[j0, i] x.[i, j1]  cell_accum)
       

//------------------------------------------------
// Multiply two Matrices:  [n,k] x [k,m] = [k, k]
//------------------------------------------------
// j0 is the strating iterator for the row
// j1 is the starting iterator for the column
// k is the size of k -> stays fixed
// m is the column count of the second array
// It is used to reset j1 as we work down the rows
let rec xMultiply (xp : float [,] ) (x : float [,] ) (xpx : float [,] )(j0 : int) (j1 : int) (k : int) (m : int) =

    match j0 with
    | -1 -> xpx
    | _ -> match j1 with
        | -1 -> xMultiply xp x xpx (j0-1) m k m
        | _  -> let tmp = xply xp x j0 j1 k 0.0
                xpx.[j0, j1] <- tmp
                printfn "xpx j0: %i j1 %i = %10.5f" j0 j1 xpx.[j0, j1]
                xMultiply xp x xpx j0 (j1-1) k m


//------------------------------------------------
// Multiply two Matrics:  [n,k] x [k,m] = [n, m]
//------------------------------------------------
let matMult (xp : float [,] ) (x : float [,] ) (xpx : float [,] ) =
    let n = xp.GetUpperBound 0
    let k = xp.GetUpperBound 1
    let m = x.GetUpperBound 1
    xMultiply xp x xpx n m k m


//-----------------------------------------
// Create X Prime X
//-----------------------------------------

let zero_xpx = Array2D.zeroCreate<float> k k
//let xpx = matMult xp x0 zero_xpx


-----------------------------------------------------------------------------

The routine goes as follows:

The function accum, just takes two values, multiplies them, and adds then to an accumulator value (ac) that is passed in.  Obviously the accumulator value would be initialized at 0.0

The function xply iterates over a row (row j0)  in the left matrix and a column (j1) in the right matrix. calling accum to accumulate the result.

Note that in the xply function, this line

    | _  -> xply xp x j0 j1 (i-1) (accum xp.[j0, i] x.[i, j1]  cell_accum)

could be written in two lines as:

    | _  -> let tmp = accum xp.[j0, i] x.[i, j1]  cell_accum
            xply xp x j0 j1 (i-1) tmp

but the former is somewhat more 'elegant.'  The return value from xply is the value for one cell (j0, j1) the resultant matrix from the multiplication operation.

The function xMultiply is a recursive function that iterates over all the cells in the matrix, calling xply each time to fill in a cell.  It has two matching levels, one outer level that iterates over the rows; one inner level that iterates over the rows in a given column.

The top level function  matMult just takes the two input matrices (left & right) and a empty output matrix as inputs.  Note the method GetUpperBound i.  This method returns the upper bound for a matrix for the dimension you pass in.  In a 2D array, The 0th dimension is for the rows, the 1st dimension is for the columns.  This is a very handy function because it means the user does not have to pass in the dimensions of the matrices to be multiplied.

The out of the matrix multiplication is:

  6.00      48.00      90.00
 48.00     768.00     642.00
 90.00     642.00    1480.00

 

 

Print | posted @ Wednesday, July 22, 2009 2:17 PM

Comments on this entry:

Gravatar # Your content is really useful
by dress at 7/15/2010 2:26 AM

and casual dresses on this site
discount Prom dresses
discount wedding dresses
a series of discount Wedding Dresses, Including Wedding gowns, Evening gowns, Wedding Dress, Bridal gowns and Bridal Dress
wedding dresses
  
Gravatar # re: F# Matrix Transpose, Multiply
by deexu at 7/16/2010 1:38 AM

great range of Ed Hardy products. Ed Hardy Women's Ellerise Lowrise Sneaker · Ed Hardy Women's
ed hardy jeans, ed hardy hoody, ed hardy shirt, ed hardy clothing, ed hardy cap, ed glasses, ed belts,
women fashion shoes, men's clothes. helping .perhaps you will like
Ed Hardy
Ed Hardy shoes
Ed Hardy shirts
Ed Hardy clothes
Ed Hardy clothing
Ed Hardy shoes
Don Ed Hardy is an American tattoo collector raised in Southern California
Ed Hardy Clothing,Christian Audigier,Ed Hardy Shoes,Ed Hardy Swimwear,Ed Hardy Hat,
ED Hardy Caps
Ed Hardy Sunglasses
Ed Hardy Wallets
EdHardy
Gucci outlet store online, numerous cheap Gucci bags, handbags, wallets, purses, totes, shoes on sale,
cheap prices and authentic qualities
gucci handbags
gucci jewelryREHTRHJOIJ
  
Gravatar # shi
by fiwedding at 7/23/2010 3:16 AM

supply in stock and custom lace front wigs, full lace wigs, lace wigs, human hair wigs,
remy lace front wigs, cheap wigs, cheap, buy, celebrity
full lace wigs
lace wigs
lace wigs sale
lace front wigs
synthetic front lace wigs
A Famous Dresses Shop which sell directly Wedding Dresses, Evening Dress, Bridesmaid Dresses,Prom dresses
cheap wedding dresses
cheap evening dresses
cheap prom dresses
cheap evening dresses
cheap prom dresses
Elegant evening dresses are always associated with the brides and their bridesmaids.Shopping for evening dresses and your wedding dress in stylish bridal ...
  
Gravatar # re: F# Matrix Transpose, Multiply
by ckangel3 at 7/30/2010 11:56 PM

Tiffany jewelry
mous Tiffany Jewelry Shop which sell directly Tiffany Rings, Earrings, Necklaces, Pendants, Bracelets,
Bangles, Accessories.
Tiffany co jewelry
Tiffany
Tiffany Bracelets
affordable tiffany jewelry, beautiful discount tiffany rings, tiffany necklaces,tiffany Pendants,
tiffany earrings and tiffany Bracelets.
Tiffany Charms
Tiffany Earrings
Tiffany Necklaces
Tiffany Rings
Tiffany Jewelry Online,Discount Tiffany & Co Jewelry On Sale,you can buy cheap Tiffany silver.
All jewelry come with Tiffany package
links of london
links london
links of london jewellery
links london
links of london jewellery</a
  
Gravatar # re: F# Matrix Transpose, Multiply
by xiaolei at 8/2/2010 2:41 AM

I know a software named EZ mpeg to avi softwarecan Convert MPG
/MPEG,MPEG-1/MPEG-2 format to AVI Video movie
. Only $12.95 USD

With a very easy to use interface you can also convert video file. your work will become very easy. You can download this software free from here: www.ezvideotools.com/mpeg-to-avi-converter.htm

  
Gravatar # re: F# Matrix Transpose, Multiply
by lv handbags at 8/2/2010 4:37 AM

our Louis Vuitton Online Exhibition, we have all the best and newest styles of louis vuitton 2009 collection Handbags that you want to look at ---all the best of the Fall and Winter fashions! You can find full product details of the newest 2009 New Collections release, spring summer handbagsthe latest price information and 2009 New Collections sale events, 2010 spring summer handbagsthe most helpful shopping guild and buying tips.

The year of 2010 will call up a new fashional era. Our louis vuitton designed a lot of new handbags. Louis vuitton 2010 spring handbags must draw your eyes. And the louis vuitton summer handbags must attract you buy one.

Check these cheap louis vuitton handbags below, no matter the luxury material , no matter the wonderful color.Discount information please pay attention to notice.
  
Gravatar # re: F# Matrix Transpose, Multiply
by joanna at 8/4/2010 7:50 PM

Perfect for the beach, the gym or just running around town on a warm summer day, Womens Adidas Shoes come in a wide variety of styles and colors that fit many fashions. Properly broken-in and cared-for Mens Adidas Shoes can provide many years of comfort and use.
  
Gravatar # Pillow Pets
by Pillow Pets at 8/27/2010 1:43 AM

Our main purpose is to help you find the hot toys .
silly bandz
Our animal rubber bands is selling fast. These animal rubber bands wholesale are made of silicone. wholesale Animal Shaped Rubber Bands are not just pretty,Animal Rubber Bands wholesale are also quite clever because they recover their original shape after each use, so you can use them over and over again.
zhu zhu pets,
  
Gravatar #  silly bandz
by silly bandz at 8/27/2010 1:52 AM

Our main purpose is to help you find the hot toys .
silly bandz
Our animal rubber bands is selling fast. These animal rubber bands wholesale are made of silicone. wholesale Animal Shaped Rubber Bands are not just pretty,Animal Rubber Bands wholesale are also quite clever because they recover their original shape after each use, so you can use them over and over again.
zhu zhu pets,
Baby Carriers is our new product.It is one of our best seller.
, power balance
Pillow Pets
Plush Pencil Case
is hot selling. Silicone Watch
They are rich-looking and most attractive and very popular with our other customers. We have business conections all over the world.Our hot toys includes:
  
Gravatar # re: F# Matrix Transpose, Multiply
by designer handbags at 8/28/2010 7:27 AM

and very popular with our other customers. We have business conections all over the world.Our hot toys includes:
  
Gravatar # timberland shoe company
by timberland for you at 9/1/2010 8:16 PM

On a certain cheap timberland boots day at a certain hour, we will pull into the station. Bands will be playing and flags discount timberland boots waving. Once we get there, so many wonderful timberland winter boots dreams will come true and the pieces of our lives will fit together like a completed jigsaw puzzle.How restlessly we pace the aisles, womens timberland boot the minutes for loitering --waiting, waiting, waiting for the station.But uppermost in our timberland shoes store minds is the final destination. On a certain day at a certain hour, we will pull into the station. Bands will be playing and timberland eye boat flags waving. Tucked away in our timberland for you subconscious is an idyllic vision. We see ourselves on a long trip that timberland 6 inch spans the continent. We are traveling by train. Out timberland hiking boots windows, we drink in the passing scene of cars on nearby highways, of children timberland shoe company waving at a crossing, of cattle grazing on a distant timberland boots hillside, of smoke pouring from a power plant, of row upon row of corn and wheat, of flatlands and timberland wheat shoes valleys, of mountains and rolling classic 3 eye timberland boat hillsides, of city skylines and village halls.But uppermost in our black timberland boots minds is the final destination.
  
Gravatar # re: F# Matrix Transpose, Multiply
by nannan at 9/2/2010 11:12 PM

GOOD Tiffany jewellery
Tiffany
variety of styles and colors that fit many fashions. ProperlVBvariety of styles and colors that fit many fashions. Properl
Tiffany & Co
Tiffany Co Bracelets
Tiffany Co Charms
Tiffany Co Earrings
Tiffany sale
Tiffany Co Necklaces
Tiffany uk
Tiffany Co Rings
tiffany jewelry
tiffany co
  
Gravatar # re: F# Matrix Transpose, Multiply
by ugg boots sale at 9/8/2010 2:13 AM

fashion ugg pink,ugg boots sale,ugg 5815,ugg 5825 "is getting "green".

ugg boots sale ugg classic tall,ugg slippers,ugg boots uk,
ugg boots tall,uggs on sale,ugg boots,ugg boots sale,
ugg boots uk,
UGG Handbags,
UGG 5854 Classic Mini,UGG 1647 Tasmina,UGG 1688 Amelie Sandals UGG 1759 Gypsy Sandal
Ugg Classic Tall 5815,Ugg Womens Broome 5511,Ugg Tall Stripe Cable Knit 5822,UGG Womens Corinth 5756 Cocoa,Ugg Ultra Tall 5245,ugg boots,UGG Classic Tall 5815,UGG Classic Short 5825,UGG Classic Cardy 5819,UGG Bailey Button 5803,UGG Metallic Tall 5812free shipping,sale online.
Classical p90x,p90x workout covers all the way of fitness methods.
We could enjoy best cheap cheap nike shoes sales online,about all kinds of nike air max,nike air max 90,nike shox.Run retailing and wholesale trade worldwidely for years,free shipping, super sale off retailing with 1 week delivery to your door.2
  
Gravatar # re: F# Matrix Transpose, Multiply
by cheap jerseys at 9/8/2010 7:02 PM

I can’t but agree.I provide the info of NFL Jerseys Wholesale.
Especially about the Football Jerseys business.
  

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 4 and 5 and type the answer here: