Implementation of Octave’s diag in Ruby

GNU Octave has a diag function which behaves like this:

octave> diag([1,2,3])
ans =
 
Diagonal Matrix
 
   1   0   0
   0   2   0
   0   0   3

To be more clear,
 diag \left( \begin{array}{ccc} 1 & 2 & 3 \end{array} \right) = \left(   \begin{array}{ccc}  1 & 0 & 0 \\ 0 & 2 & 0 \\ 0 & 0 & 3    \end{array}    \right)

Here is an implementation of the diag function in Ruby:

# Create a diagonal matrix given a vector (or an array), 
# placing the entries of the vector on the diagonal of 
# the matrix.
# For example, diag([1,2,3]) would give:
# [ 1 0 0 ]
# [ 0 2 0 ]
# [ 0 0 3 ]
# That would actually be a 2D matrix like this 
#  [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
# The array returned has to be converted to a matrix by doing 
#  Matrix[ *diag(vector) ]
def diag(vector)
  n = vector.size
  matrix = []
  n.times do |i|
    matrix << Array.new(n) { |x| (x == i) ? vector[x] : 0 }
  end
  matrix
end

You can also get the code in this gist; use it as you wish.

Tags: , ,

Leave a Reply