Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matrix F#Array2D-提取对角线_Matrix_F#_Diagonal - Fatal编程技术网

Matrix F#Array2D-提取对角线

Matrix F#Array2D-提取对角线,matrix,f#,diagonal,Matrix,F#,Diagonal,假设我有一个矩阵 [[0; 0; 1; 0; 0; 0] [0; 1; 0; 0; 0; 0] [2; 0; 0; 0; 0; 0] [0; 1; 0; 0; 0; 0] [0; 0; 1; 0; 0; 0] [0; 0; 0; 1; 0; 0]] 我想将对角线提取为一维数组,意思是[[2;1;1}]和[[2;1;1;1}] 对于行和列,我们有 matrix.[i,*] // The ith row matrix.[*,i] // the ith column 我们是否

假设我有一个矩阵

 [[0; 0; 1; 0; 0; 0]
  [0; 1; 0; 0; 0; 0]
  [2; 0; 0; 0; 0; 0]
  [0; 1; 0; 0; 0; 0]
  [0; 0; 1; 0; 0; 0]
  [0; 0; 0; 1; 0; 0]]
我想将对角线提取为一维数组,意思是
[[2;1;1}]
[[2;1;1;1}]

对于行和列,我们有

matrix.[i,*] // The ith row
matrix.[*,i] // the ith column

我们是否可以在向上和向下的方向上为第I条对角线构造类似的东西?

我看不出建议的
GetSlice
方法语法将如何应用于您的场景。另一方面,提供
索引器属性对于提取对角线可能非常方便

type 'a M = M of 'a list list with
    member me.Item i =
        let (M xss) = me in xss
        |> List.mapi (fun j ->
            List.mapi (fun k x ->
                if i = j - k then Some x else None )
            >> List.choose id )
        |> List.concat
给定一个矩阵作为列表列表:

let m =
 [[0; 0; 1; 0; 0; 0]
  [0; 1; 0; 0; 0; 0]
  [2; 0; 0; 0; 0; 0]
  [0; 1; 0; 0; 0; 0]
  [0; 0; 1; 0; 0; 0]
  [0; 0; 0; 1; 0; 0]]

M(m).[2] // val it : int list = [2; 1; 1; 1]

除非您想使用一些外部库,否则它不会比下面的短很多

let diag (mat: _ [,]) = 
    let l = min (mat.GetLength(0)) (mat.GetLength(1)) - 1
    [| for i in 0..l -> mat.[i,i] |]

我个人不认为这是一个问题,但这取决于你。当然,您可以使用
Array.init
或其他方法来代替for循环,但我更喜欢指定的解决方案。

到目前为止您尝试了什么?这感觉像是一个家庭作业问题。。无论如何,看看这里:它不是。我个人项目需要的东西。我已经用for循环解决了这个问题,但我希望实现更紧凑的东西。我这么说是因为通常没有任何示例代码来显示所做工作的问题会在给定的上下文中向我发出这种警报。很高兴知道!如果我理解正确,这只返回一条对角线。所需的是提取所有这些数据的方法(长度不同)