Ruby 编程中的 Transpose() 函数
Ruby 语言中 transpose 函数主要用于返回数组或矩阵的转置。
语法
array.transpose
或
Matrix.transpose
我们先举几个数组中 transpose 函数的示例,然后再举几个矩阵中的示例。
示例 1
考虑以下所示代码
# transpose() in array # array declaration first_arr = [[18, 22], [33, 3], [8, 6]] # array declaration second_arr = [[1, 3, 2, 5, 88, 9]] # print statements puts "transpose() output : #{first_arr.transpose()}
" puts "transpose() output : #{second_arr.transpose()}
"
输出
transpose() output : [[18, 33, 8], [22, 3, 6]] transpose() output : [[1], [3], [2], [5], [88], [9]]
示例 2
# transpose() in array # array declaration first_arr = [["xyz", "nil", "cat"]] # array declaration second_arr = [["donkey", "go", "lion"]] # print statements puts "transpose() output : #{first_arr.transpose()}
" puts "transpose() output : #{second_arr.transpose()}
"
输出
transpose() output : [["xyz"], ["nil"], ["cat"]] transpose() output : [["donkey"], ["go"], ["lion"]]
现在让我们探讨几个矩阵上的转置示例。
示例 3
# transpose() in Matrix require "matrix" # Initializing matrix matOne = Matrix[[5, 11], [1, 9]] # Prints the transpose matrix puts matOne.transpose()
输出
Matrix[[5, 1], [11, 9]]
示例 4
# transpose() in matrix require "matrix" # Initializing matrix matOne = Matrix[[1, 2], [6, 3], [4, 2]] # Printing matrix puts matOne.transpose()
输出
Matrix[[1, 6, 4], [2, 3, 2]]
广告