Created
September 14, 2014 22:29
-
-
Save kanungo/f1a733b74de790657530 to your computer and use it in GitHub Desktop.
System of linear equations with numpy
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
{ | |
"metadata": { | |
"name": "" | |
}, | |
"nbformat": 3, | |
"nbformat_minor": 0, | |
"worksheets": [ | |
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"# Solve the system of equations in the slides\n", | |
"import numpy as np\n", | |
"\n", | |
"# NOTE: We do this using the numpy matrix object\n", | |
"\n", | |
"# Create the A matrix\n", | |
"A = np.matrix([[1,2,3],[0,2,4],[0,0,3]])\n", | |
"print A\n", | |
"\n", | |
"# Create the b matrix (the right hand side)\n", | |
"b = np.matrix([[2],[1],[4]])\n", | |
"print b\n", | |
"\n", | |
"# Solve for x\n", | |
"x = A.I*b\n", | |
"\n", | |
"# Print the solution\n", | |
"print x" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [] | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"# Solve the system of equations in the slides\n", | |
"import numpy as np\n", | |
"\n", | |
"# NOTE: We do this using the numpy arrays\n", | |
"\n", | |
"# Create the A matrix\n", | |
"A = np.array([[1,2,3],[0,2,4],[0,0,3]])\n", | |
"print A\n", | |
"\n", | |
"# Create the b matrix (the right hand side)\n", | |
"b = np.array([2, 1,4]) # Note this to be a row vector\n", | |
"bCol = np.transpose(b) # We transpose this to make it a column vector\n", | |
"\n", | |
"# Solve for x\n", | |
"x = np.dot(np.linalg.inv(A),bCol)\n", | |
"\n", | |
"# Print the solution\n", | |
"print x" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [] | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"# Solve the system of equations in the slides\n", | |
"# There is a direct method that we did not do in class\n", | |
"# because I wanted to demonstrate the use of matrix / array\n", | |
"# operations\n", | |
"\n", | |
"import numpy as np\n", | |
"\n", | |
"# Create the A matrix\n", | |
"A = np.array([[1,2,3],[0,2,4],[0,0,3]])\n", | |
"print A\n", | |
"\n", | |
"# Create the b matrix (the right hand side)\n", | |
"b = np.array([2, 1,4]) # Note this to be a row vector\n", | |
"\n", | |
"# Obtain the solution directly using the solve function in the linalg module\n", | |
"x = np.linalg.solve(A,b)\n", | |
"\n", | |
"# Print the solution\n", | |
"print x" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [] | |
} | |
], | |
"metadata": {} | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment