Skip to content

Instantly share code, notes, and snippets.

@CodeArtha
Last active July 10, 2019 18:49
Show Gist options
  • Select an option

  • Save CodeArtha/6d09ddd458b560e2288bc3943195592f to your computer and use it in GitHub Desktop.

Select an option

Save CodeArtha/6d09ddd458b560e2288bc3943195592f to your computer and use it in GitHub Desktop.
Simple python script written for my master thesis to invert a square matrix and print it in a format that can be pasted in libre office calc without needing further refactoring
from sympy import *
# Sample matrix
m = Matrix([
[0.0000, 0.0928, 1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,],
[0.0000, 0.0000, 0.0000, 0.2300, 0.5200, 0.1000, 0.1200, 0.1000,],
[1.0000, 0.1700, 0.0000, 1.0000, 1.0000, 0.6000, 0.1032, 0.2700,],
[0.0000, 0.0000, 0.0000, 0.2300, 0.0000, 1.0000, 0.0000, 0.1200,],
[0.0000, 0.0000, 0.0000, 0.2700, 0.0000, 0.0000, 0.0000, 0.0000,],
[0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0700, 0.7000, 0.0300,],
[0.0000, 1.0000, 0.0000, 0.0000, 0.0000, 0.3000, 0.0000, 0.0000,],
[0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.3800,],
])
# Dimensions of the matrix
x,y = m.shape
# print(x)
# print(y)
# Note: m must be a square matrix
if( x == y):
inverted = m**-1
# Manual printing of the matrix is needed for an easy import into excell through a simple copy-paste.
for line in range(x):
for cell in range(y):
print(round(inverted[line, cell], 4), end="\t")
print(" ") # prints a newline
else:
print("Warning matrix isn't square")
# Output
# 0.0000 -1.9231 1.0000 -0.3694 -1.7508 0.1822 -0.1700 -0.1022
# 0.0000 0.0000 0.0000 -0.3000 0.2556 0.0000 1.0000 0.0947
# 1.0000 0.0000 0.0000 0.0278 -0.0237 0.0000 -0.0928 -0.0088
# 0.0000 0.0000 0.0000 0.0000 3.7037 0.0000 0.0000 0.0000
# 0.0000 1.9231 0.0000 -0.1692 -1.4940 -0.3297 0.0000 -0.4266
# 0.0000 0.0000 0.0000 1.0000 -0.8519 0.0000 0.0000 -0.3158
# 0.0000 0.0000 0.0000 -0.1000 0.0852 1.4286 0.0000 -0.0812
# 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 2.6316
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment