开发者

how reverse a matrix object in ruby 1.9?

开发者 https://www.devze.com 2023-03-20 22:52 出处:网络
I am a beginner with Ruby. So I searched how reverse a matrix 1, 2, 3,48, 9, 10, 11 4, 5, 6,7 =>开发者_Go百科; 4, 5, 6,7

I am a beginner with Ruby. So I searched how reverse a matrix

1, 2, 3,  4    8, 9, 10, 11
4, 5, 6,  7 =>开发者_Go百科; 4, 5, 6,  7
8, 9, 10, 11   1, 2, 3,  4

I have tried:

require 'matrix'
m = Matrix[ [1,2,3,4],[4,5,6,7], [8,9,10,11] ]
m_rev = Matrix.build(m.row_size, m.column_size){|row|
    m.row_size.downto(0){|i|
        row = m.row(i)
    }
}


Try: Matrix[*m.to_a.reverse]:

m = Matrix[ [1,2,3,4], [5,6,7,8], [9,10,11,12] ]
 #=> Matrix[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
r = Matrix[*m.to_a.reverse]
 #=> Matrix[[9, 10, 11, 12], [5, 6, 7, 8], [1, 2, 3, 4]]

Do not miss the *.


You can do something like:

m_rev = Matrix.rows m.to_a.reverse


You were on the right track, except that Matrix.build iterates over both rows and columns:

m_rev = Matrix.build(m.row_size, m.column_size){|row, column|
  m[-row-1, column]
}

Simpler and faster:

m_rev = Matrix.rows(m.to_a.reverse)
# or
m_rev = Matrix[*m.to_a.reverse]
0

精彩评论

暂无评论...
验证码 换一张
取 消