Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap columns and rows in a matrix with Ruby

All I want to do is swap matrix[i][j] with matrix[j][i] using while loops. Why doesn't this work?

def my_transpose(matrix)

  new_matrix = []

  i = 0
  j = 0

  while i < matrix.size
    new_matrix[i] = []
    while j < matrix.size
      new_matrix[i] << matrix[j][i]
      j += 1
    end
    i += 1
  end

  return new_matrix
end

If I run this with something like

[
[1,2,3],
[1,2,3],
[1,2,3]
]

it just returns 1,1,1. How do I get it to return 1,1,1; 2,2,2; 3,3,3 ?

like image 645
reichertjalex Avatar asked Nov 30 '22 03:11

reichertjalex


1 Answers

If your question is How to swap columns and rows in a matrix with Ruby, the answer is to use the built-in Array#transpose

a = [
[1,2,3],
[1,2,3],
[1,2,3]
]
#=> [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
a.transpose
#=> [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
like image 147
Yu Hao Avatar answered Dec 04 '22 12:12

Yu Hao