TPL

Category:
Parallel
Description: Task Parallel Library (TPL) is applied in this sample to manipulate matrix. Code originally from Chris Smith's book
Code:
let ParallelSample3() = 
// multiply two matrices using the PFX
let matrixMultiply (a: float[,]) (b: float[,]) =
let aRow, aCol = Array2D.length1 a,
Array2D.length2 a
let bRow, bCol = Array2D.length1 b,
Array2D.length2 b
if aCol <> bRow then
failwith "Array dimension mismatch."

// Allocate space for the resulting matrix, c
let c = Array2D.create aCol bRow 0.0
let cRow, cCol = aCol, bRow

// compute each row of the resulting matrix
let rowTask rowIdx =
for colIdx = 0 to cCol - 1 do
for x = 0 to aRow - 1 do
c.[colIdx, rowIdx] <-
c.[colIdx, rowIdx] +
a.[x, colIdx] * b.[rowIdx, x]
()

let _ = Parallel.For(0, cRow, new Action(rowTask))
c

let n = 10 // we use n*n matrices
let unitMatrix = Array2D.create n n 0.0
for i = 0 to n - 1 do
unitMatrix.[i,i] <- 1.0
// display what should be a n by n unit matrix
let result = matrixMultiply unitMatrix unitMatrix
printfn "%A" result
Execution Result:
[[1.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0]
[0.0; 1.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0]
[0.0; 0.0; 1.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0]
[0.0; 0.0; 0.0; 1.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0]
[0.0; 0.0; 0.0; 0.0; 1.0; 0.0; 0.0; 0.0; 0.0; 0.0]
[0.0; 0.0; 0.0; 0.0; 0.0; 1.0; 0.0; 0.0; 0.0; 0.0]
[0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 1.0; 0.0; 0.0; 0.0]
[0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 1.0; 0.0; 0.0]
[0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 1.0; 0.0]
[0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 1.0]]

Last edited Sep 14, 2011 at 3:31 AM by ttliu2000, version 1

Comments

No comments yet.