Green Fire
Green Fire

Reputation: 709

How to transpose a matrix?

I am new at F#.

I want to transpose a matrix, I can do this with loops like in any other language, But I want to do it with out loops.

My Matrix Declaration :

let BuildEmptyBord:BordCell[][]=[|for i in 1..3->[|for i in 1..3->BordCell.Empty|]|] 

So please help

Upvotes: 2

Views: 804

Answers (1)

Gus
Gus

Reputation: 26194

For matrix as jagged array you can use the Array.init function and then re-create the matrix with the dimensions swapped, like this:

let transpose (matrix:_ [][]) =
    if matrix.Length = 0 then failwith "Invalid matrix"  
    Array.init matrix.[0].Length (fun i -> 
        Array.init matrix.Length (fun j -> 
            matrix.[j].[i]))

Upvotes: 2

Related Questions