一种在矩阵中交换F#中行的简单方法(A simple way to swap rows in a matrix for F#)
有一种简单的方法可以在F#中交换Matrix的行吗?
Is there a simple way to swap the rows of a Matrix in F#?
最满意答案
您可以使用切片语法来处理矩阵的整个行/列:
// 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]切片语法允许您选择矩阵的一部分 - 在这种情况下,我们选择高度为1的矩阵,但您可以更普遍地使用该功能(该部分不必是单个列/行)。 我不认为有任何现有的交换两行的功能,但你可以使用切片并实现它如下:
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] <- tmpYou 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更多推荐
发布评论