Python code equivalent to Jim's MatLab