在 F# 中的 2D 数组中切片,但类似于 Matlab



我想知道是否有办法使用列表或 int 数组作为索引来切成数组以获取 f# 中的子数组。

我知道你可以做到以下几点

Arr2d.[*,1] or Arr2d.[1..5,1..2] etc...

但是我一直在寻找类似 Matlab 的东西,您可以在其中编写:

Arr2d([1;6;10],1) or Arr2d(1:10,[1;6;10])

是否可以在 F# 中进行这样的切片?

谢谢!

这是我的示例解决方案:(可能不是最佳的,但有效)

let sampleMatrix = Array2D.init 10 5 (fun x y -> y)
val sampleMatrix : int [,] = [[0; 1; 2; 3; 4]
                              [0; 1; 2; 3; 4]
                              [0; 1; 2; 3; 4]
                              [0; 1; 2; 3; 4]
                              [0; 1; 2; 3; 4]
                              [0; 1; 2; 3; 4]
                              [0; 1; 2; 3; 4]
                              [0; 1; 2; 3; 4]
                              [0; 1; 2; 3; 4]
                              [0; 1; 2; 3; 4]]
let idxlist = [1;3;4]
let array2dColumnSlice (idxlist:list<int>) (data:'T[,]) = 
  let tmp = [|for i in idxlist -> data.[*,i]|] 
  Array2D.init tmp.[0].Length tmp.Length (fun x y -> tmp.[y].[x] )
let slice = array2dColumnSlice idxlist sampleMatrix
val slice : int [,] = [[1; 3; 4]
                       [1; 3; 4]
                       [1; 3; 4]
                       [1; 3; 4]
                       [1; 3; 4]
                       [1; 3; 4]
                       [1; 3; 4]
                       [1; 3; 4]
                       [1; 3; 4]
                       [1; 3; 4]]

如此处所述,除了您已经找到的内容之外,没有其他切片符号。

仅对于范围,可以通过将Array2D包装为可切片类型或使用旧的PowerPack的矩阵类型来实现。

请参阅此处的文档:
http://msdn.microsoft.com/en-us/library/dd233214.aspx#sectionToggle6

可以将此切片语法用于实现元素的类型 访问运算符和重载的 GetSlice 方法。例如, 以下代码创建一个包装 F# 2D 数组的矩阵类型, 实现 Item 属性以提供对数组索引的支持,以及 实现三个版本的 GetSlice。如果可以将此代码用作 矩阵类型的模板,您可以使用所有切片操作 本节将介绍。

最新更新