VPavliashvili
VPavliashvili

Reputation: 655

How can I use function in F# with two parametes which are 2D arrays of ints

I am totally new in f# and i need help for my homework

i have this function and when i call it with parameters it returns an error

here is the code

let MatrixMultiply (matrix1 : _[,] , matrix2 : _[,]) =
    let result_row = (matrix1.GetLength 0)
    let result_column = (matrix2.GetLength 1)
    let ret = Array2D.create result_row result_column 0
    for x in 0 .. result_row - 1 do
        for y in 0 .. result_column - 1 do
            let mutable acc = 0
            for z in 0 .. (matrix1.GetLength 1) - 1 do
                acc <- acc + matrix1.[x,z] * matrix2.[z,y]
            ret.[x,y] <- acc
    ret

here is the error message:

error FS0001: Expecting a type supporting the operator '*' but given a tuple type

let mat3 = (MatrixMultiply (mat1, mat2))
printfn "%A" mat3

this is way i am using this function, mat1 and mat2 variables are 3x3 2D matrices

let mat1 = Array2D.init 3 3 (fun x y -> (rand.Next(x+10),rand.Next(y+10)))
let mat2 = Array2D.init 3 3 (fun x y -> (rand.Next(x+10),rand.Next(y+10)))

Upvotes: 0

Views: 46

Answers (1)

LSM07
LSM07

Reputation: 817

The problem is how you defined mat 1 and mat 2:

let mat1 = Array2D.init 3 3 (fun x y -> (rand.Next(x+10),rand.Next(y+10)))
let mat2 = Array2D.init 3 3 (fun x y -> (rand.Next(x+10),rand.Next(y+10)))

The problem is that (rand.Next(x+10),rand.Next(y+10) is a tuple, (val1, val2). mat1 and mat2 are 2D Arrays of tuples. If you just write it:

let mat1 = Array2D.init 3 3 (fun x y -> rand.Next(x + y)) // or whatever max number you want
let mat2 = Array2D.init 3 3 (fun x y -> rand.Next(x + y))
let mat3 = MatrixMultiply(mat1, mat2)

it will work.

Upvotes: 2

Related Questions