tags:

views:

127

answers:

2

Is there a simple way to swap the rows of a Matrix in F#?

+2  A: 

You can use slicing syntax to manipulate with entire rows/columns of a matrix:

// Create sample matrix
let m = Matrix.init 10 10 (fun x y -> float(x * 10 + y))
// Overwrite first row with the second row
m.[0..0, 0..9] <- m.[1..1, 0..9]

The slicing syntax allows you to select a part of the matrix - in this case, we're selecting a matrix with the height 1, but you can use the feature more generally (the part doesn't have to be a single column/row). I don't think there is any existing function for swapping two rows, but you can use slices and implement it like this:

let swap (m:matrix) a b = 
  let tmp = m.[a..a, 1..9]
  m.[a..a, 1..9] <- m.[b..b, 1..9]
  m.[b..b, 1..9] <- tmp
Tomas Petricek
+3  A: 

Here's another way using member function PermuteRows of Matrix type:

let m = Matrix.init 10 10 (fun x y -> float(x * 10 + y))
let m2 = m.PermuteRows (fun i -> 9 - i) 

You need to provide a row mapping function, here (i -> 9 - i).

Yin Zhu