iMPaCT try f#‎ > ‎

matrices in f#

problem:
open Impact

let c = [| [| 2.; 1.; -1.; 8.|];
           [| -3.; -1.; 2.; -11.|]; 
           [| -2.; 1.; 2.; -3.|] |] 

let d = [| [| 4.; 8.; 4.|]; 
           [| -3.; -1.; 7.|] |]
let printMatrix(matrix : float[][]) =
    for rowNum in 0 .. matrix.Length-1 do
        let row = matrix.[rowNum]
        for colNum in 0 .. row.Length-1 do
            printf "  %10f" row.[colNum]
        printfn ""
    printfn ""
 
let scalarMult (vector : float [], multiplier : float) =
    [| for i in 0 .. vector.Length-1 -> vector.[i] * multiplier |]
 
let vectorAdd(v1 : float [], v2 : float []) =
    [| for i in 0 .. v1.Length-1 -> v1.[i] + v2.[i]|]
solution:
open Impact

let c = [| [| 2.; 1.; -1.; 8.|];
           [| -3.; -1.; 2.; -11.|]; 
           [| -2.; 1.; 2.; -3.|] |] 

let d = [| [| 4.; 8.; 4.|]; 
           [| -3.; -1.; 7.|] |]

let printMatrix(matrix : float[][]) =
    for rowNum in 0 .. matrix.Length-1 do
        let row = matrix.[rowNum]
        for colNum in 0 .. row.Length-1 do
            printf "  %10f" row.[colNum]
        printfn ""
    printfn ""
 
let scalarMult (vector : float [], multiplier : float) =
    [| for i in 0 .. vector.Length-1 -> vector.[i] * multiplier |]
 
let vectorAdd(v1 : float [], v2 : float []) =
    [| for i in 0 .. v1.Length-1 -> v1.[i] + v2.[i]|]

c.[0] <- scalarMult(c.[0],1.0/2.0); printMatrix c
c.[1] <- vectorAdd(scalarMult(c.[0], 3.),c.[1]); printMatrix c
c.[2] <- vectorAdd(scalarMult(c.[0], 2.),c.[2]); printMatrix c

c.[1] <- scalarMult(c.[1],1.0/0.5); printMatrix c
c.[0] <- vectorAdd(scalarMult(c.[1], -0.5),c.[0]); printMatrix c
c.[2] <- vectorAdd(scalarMult(c.[1], -2.0),c.[2]); printMatrix c

//c.[2] <- scalarMult(c.[2],1.0/-1.0); printMatrix c
c.[2] <- scalarMult(c.[2],1.0/c.[2].[2]); printMatrix c
//c.[0] <- vectorAdd(scalarMult(c.[2], 1.0),c.[0]); printMatrix c
c.[0] <- vectorAdd(scalarMult(c.[2], -c.[0].[2]),c.[0]); printMatrix c
//c.[1] <- vectorAdd(scalarMult(c.[2], -1.0),c.[1]); printMatrix c
c.[1] <- vectorAdd(scalarMult(c.[2], -c.[1].[2]),c.[1]); printMatrix c
Comments