diff --git a/lib/matrix.rb b/lib/matrix.rb index e79c361..50ad7e3 100644 --- a/lib/matrix.rb +++ b/lib/matrix.rb @@ -443,6 +443,21 @@ class Matrix end alias map collect + # Takes n matricies of same row and column count, and returns a matrix + # of length n arrays. + def zip(*args) + memo = self.map {|x| [x]} + args.each do |m| + Matrix.Raise ErrDimensionMismatch unless + m.row_count == memo.row_count && m.column_count == memo.column_count + + memo.each_with_index do |e, i, j| + memo[i, j] << m[i, j] + end + end + memo + end + # # Yields all elements of the matrix, starting with those of the first row, # or returns an Enumerator if no block given. diff --git a/test/matrix/test_matrix.rb b/test/matrix/test_matrix.rb index d8b95ec..7ffc7ac 100644 --- a/test/matrix/test_matrix.rb +++ b/test/matrix/test_matrix.rb @@ -279,6 +279,13 @@ class TestMatrix < Test::Unit::TestCase assert_equal(Matrix[[1, 4, 9], [16, 25, 36]], @m1.collect {|x| x ** 2 }) end + def test_zip + assert_equal(Matrix[[[1, 1], [2, 2], [3, 3]], + [[4, 4], [5, 5], [6, 6]]], @m1.zip(@m2)) + assert_equal(Matrix[[[1, 1, 1], [2, 2, 2], [3, 3, 3]], + [[4, 4, 4], [5, 5, 5], [6, 6, 6]]], @m1.zip(@m2, @m2)) + end + def test_minor assert_equal(Matrix[[1, 2], [4, 5]], @m1.minor(0..1, 0..1)) assert_equal(Matrix[[2], [5]], @m1.minor(0..1, 1..1))