Skip to content

Instantly share code, notes, and snippets.

@FloooD
Forked from leegao/squaremat.lua
Created April 5, 2011 16:28
Show Gist options
  • Save FloooD/903940 to your computer and use it in GitHub Desktop.
Save FloooD/903940 to your computer and use it in GitHub Desktop.
only for diagonalizable 2x2 matrices
function m_pow(matrix, n)
local tr = matrix[1][1]+matrix[2][2] -- trace of matrix
local s = math.sqrt((matrix[1][1]-matrix[2][2])^2+4*matrix[1][2]*matrix[2][1]) -- sqrt(tr^2 - 4*determinant)
local r1 = 0.5*(tr+s) --1st eigenvalue
local r2 = tr-r1 --2nd eigenvalue
local r1n = r1^n
local r2n = r2^n
local b2 = (r1n-r2n)/s
local b1 = (r1*r2n - r2*r1n)/s
return {{b2*matrix[1][1]+b1, b2*matrix[1][2]}, {b2*matrix[2][1], b2*matrix[2][2]+b1}}
end
function print_matrix(matrix)
print(unpack(matrix[1]))
print(unpack(matrix[2]))
end
matrix = {{1,2},
{3,4}}
print_matrix(m_pow(matrix, 400))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment