Skip to content

Instantly share code, notes, and snippets.

@vikhyat
Created December 13, 2009 13:09
Show Gist options
  • Save vikhyat/255408 to your computer and use it in GitHub Desktop.
Save vikhyat/255408 to your computer and use it in GitHub Desktop.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment