I have a 2d array A = [[a1,a2,a3],[b1,b2,b3],[c1,c2,c3]].
I want to access this array column-wise.
something like that-
A[all][0]
-> [a1,b1,c1]
How can i do that?
Do as below using #transpose
method :
A.transpose.each do |ary|
# your code
end
As per your comment, I would suggest to use Matrix
class. Once you will create a Matrix
object, you can access the elements of it, row wise or column wise.
require 'matrix'
A = [['a1','a2','a3'],['b1','b2','b3'],['c1','c2','c3']]
mat = Matrix[ *A ]
mat.column(1).to_a # => ["a2", "b2", "c2"]
An alternative option would be to use to use Array#map:
A = [["a1","a2","a3"],["b1","b2","b3"],["c1","c2","c3"]]
=> [["a1", "a2", "a3"], ["b1", "b2", "b3"], ["c1", "c2", "c3"]]
>> col = 0
=> 0
>> A.map{|a| a[col]}
=> ["a1", "b1", "c1"]
Could be rolled into a method as needed.
The short answer:
A_t = A.tranpose
A_t[0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With