F#Array2D - 提取对角线

问题描述 投票:1回答:2

我们假设我有一个矩阵

 [[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]]

我想将对角线提取为1d数组,意思是[|2;1;1|][|2;1;1;1|]

对于行和列,我们有

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

我们可以在向上和向下的方向上为第i个对角线构造类似的东西吗?

matrix f# diagonal
2个回答
0
投票

我没有看到提议的GetSlice方法语法如何适用于您的场景。另一方面,提供Item索引器属性确实可以方便地提取对角线。

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]

0
投票

除非你想使用一些外部库,否则它不会比以下更短。

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

我个人认为这根本不是问题,但这取决于你。当然,你可以使用Array.init或其他东西代替for循环,但我更喜欢陈述的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.