matrix.py

Created by asness

Created on February 10, 2019

1.17 KB


def f(m):
    return [[float(i) for i in m_row] for m_row in m]

def T(m):
    return list(map(list,zip(*m)))

def minor(m,i,j):
    return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])]

def det(m):
    if len(m) == 2:
        return m[0][0]*m[1][1]-m[0][1]*m[1][0]

    d = 0
    for c in range(len(m)):
        d += ((-1)**c)*m[0][c]*det(minor(m,0,c))
    return d

def inv(m):
    d = det(m)

    if len(m) == 2:
        return [[   m[1][1]/d, -1*m[0][1]/d],
                [-1*m[1][0]/d,    m[0][0]/d]]

    cfs = []
    for r in range(len(m)):
        cfRow = []
        for c in range(len(m)):
            mi = minor(m,r,c)
            cfRow.append(((-1)**(r+c)) * det(mi))
        cfs.append(cfRow)
    cfs = T(cfs)
    for r in range(len(cfs)):
        for c in range(len(cfs)):
            cfs[r][c] = cfs[r][c]/d
    return cfs

def add(m1, m2):
    return [[i + j for i, j in zip(m1_row, m2_row)] for m1_row, m2_row in zip(m1, m2)]

def smul(m, s):
    return [[s * i for i in m_row] for m_row in m]

def mmul(m1, m2):
    return [[sum(i * j for i, j in zip(m1_row, m2_col)) for m2_col in zip(*m2)] for m1_row in m1]

def sol(m1, m2):
    return mmul(inv(m1), m2)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.