Created
December 13, 2009 13:09
-
-
Save vikhyat/255408 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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