问题
I have a square matrix of indeterminate row & column length (assume rows and columns are equal as befits a square).
I've plotted out an example matrix as follows:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
My goal is to get a sum from top-left to bottom-right of the diagonal values.
Obviously in this example, this is all i'll need:
diagsum = matrix[0][0]+matrix[1][1]+matrix[2][2]
#=> 15
I see the pattern where it's a +1 incremental for each row & column argument in the matrix, so the code i've developed for my matrix of indeterminate length (supplied as the argument to my method diagsum would preferably need to implement some sort of row_count method on my matrix argument.
回答1:
If
arr = [[1,2,3],
[4,5,6],
[7,8,9]]
then:
require 'matrix'
Matrix[*arr].trace
#=> 15
回答2:
This will sum the diagonal values.
matrix = []
matrix[0] = [1,2,3]
matrix[1] = [4,5,6]
matrix[2] = [7,8,9]
def diagsum(mat)
sum = 0
mat.each_with_index { |row,i| sum += row[i] }
sum
end
puts (diagsum matrix) # 15
回答3:
- Not clear what
xis. - But assuming that it is the number of columns/rows, you have
0..x, while the index only goes up tox - 1. You should change it to0...x. - You are assigning to variable
i, whose scope is only in the block. - You are only using
ionce, perhaps intended to correspond to either row or column, but not both. - You are adding the indices instead of the corresponding elements.
eachwill return the receiver regardless of whatever you get in the blocks.putswill returnnilregardless of whatever you get.
来源:https://stackoverflow.com/questions/32853157/determining-the-sum-of-top-left-to-bottom-right-diagonal-values-in-a-matrix-with