Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select column-wise of a 2d array in ruby

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?

like image 365
Muktadir Avatar asked May 27 '14 21:05

Muktadir


3 Answers

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"]
like image 177
Arup Rakshit Avatar answered Oct 23 '22 08:10

Arup Rakshit


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.

like image 42
Reinstate Monica -- notmaynard Avatar answered Oct 23 '22 09:10

Reinstate Monica -- notmaynard


The short answer:

A_t = A.tranpose
A_t[0]
like image 31
Hüseyin Biçen Avatar answered Oct 23 '22 10:10

Hüseyin Biçen