获取矩阵的两个对角线 [英] Getting two diagonals of a Matrix

查看:486
本文介绍了获取矩阵的两个对角线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此Matrix类: http: //ruby-doc.org/stdlib-2.0.0/libdoc/matrix/rdoc/Matrix.html

I'm using this Matrix class: http://ruby-doc.org/stdlib-2.0.0/libdoc/matrix/rdoc/Matrix.html

我以这种方式实例化:

@matrix = Matrix.build(3,3) { |row, col| Cell.new }

如何从两个对角线上获取元素?我发现我可以这样从左上角到右下角获取元素:

How can I get the elements from both diagonals? I found I can get the elements from the upper left to the lower right diagonal this way:

@matrix.each(:diagonal).to_a

但是我找不到一种方法来获取右上角到左下角的元素.

But I cant find a way to get the elements in the upper right to lower left diagonal.

推荐答案

假设:

require 'matrix'

m = Matrix[[1,2,3],
           [4,5,6],
           [7,8,9]]
  #=> Matrix[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

获取主对角线很容易.让我们将其设为Matrix方法.

Obtaining the main diagonal is easy. Let's make it a Matrix method.

class Matrix
  def extract_diagonal
    each(:diagonal).to_a
  end
end

m.extract_diagonal
  # => [1, 5, 9]

获得对角线 1 的一种方法是将矩阵旋转"90度",然后取该矩阵的主对角线.为了执行旋转,这是我发现的另一种Matrix方法,在各种情况下都很有用:

One way of obtaining the antidiagonal1 is to rotate the matrix "90 degrees" and then take the main diagonal of that matrix. To perform the rotation, here's another Matrix method I've found useful in various situations:

class Matrix
  def rotate
    Matrix[*to_a.map(&:reverse).transpose]
  end
end

例如:

m.rotate
  #=> Matrix[[3, 6, 9],
  #          [2, 5, 8],
  #          [1, 4, 7]] 

因此m的反对角线是:

m.rotate.extract_diagonal
  #=> [3, 5, 7] 

1.根据 Wiki ,从正方形矩阵的左上角到右下角的对角线是主要对角线(有时是主要对角线,主要对角线,前导对角线或主要对角线)",而从右上角到左下角的对角线是对角线(有时是对角线,次要对角线,尾随对角线或次要对角线) .

1. According to Wiki, the diagonal that goes from the top left to the bottom right of a square matrix is the "main diagonal (sometimes principal diagonal, primary diagonal, leading diagonal, or major diagonal)", whereas the diagonal that goes from the top right to bottom left is the "antidiagonal (sometimes counterdiagonal, secondary diagonal, trailing diagonal or minor diagonal)".

这篇关于获取矩阵的两个对角线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆