{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This page has been moved to [https://econ.pages.code.wm.edu/414/syllabus/docs/index.html](https://econ.pages.code.wm.edu/407/notes/docs/index.html) and is no longer being maintained here."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Linear Algebra and Python Basics\n",
"\n",
"In this chapter, I will be discussing some linear algebra basics that will provide sufficient linear algebra background for effective programming in Python for our purposes. We will be doing very basic linear algebra that by no means covers the full breadth of this topic. Why linear algebra? Linear algebra allows us to express relatively complex linear expressions in a very compact way.\n",
"\n",
"Being comfortable with the rules for scalar and matrix addition, subtraction, multiplication, and division (known as inversion) is important for our class.\n",
"\n",
"Before we can implement any of these ideas in code, we need to talk a bit about python and how data is stored.\n",
"\n",
"## Python Primer\n",
"\n",
"There are numerous ways to run python code. I will show you two and both are easily accessible after installing Anaconda:\n",
"\n",
"1. The Spyder integrated development environment. The major advantages of Spyder is that it provides a graphical way for viewing matrices, vectors, and other objects you want to check as you work on a problem. It also has the most intuitive way of debugging code.\n",
"\n",
" Spyder looks like this:\n",
" ![](../site_pics/Spyder_1.png)\n",
" Code can be run by clicking the green arrow (runs the entire file) or by blocking a subset and running it.\n",
" In Windows or Mac, you can launch the Spyder by looking for the icon in the newly installed Program Folder Anaconda. \n",
" \n",
"2. The Ipython Notebook (now called Jupyter). The major advantages of this approach is that you use your web browser for all of your python work and you can mix code, videos, notes, graphics from the web, and mathematical notation to tell the whole story of your python project. In fact, I am using the ipython notebook for writing these notes. \n",
" The Ipython Notebook looks like this:\n",
" ![](../site_pics/Jupyter_1.png)\n",
" In Windows or Mac, you can launch the Ipython Notebook by looking in the newly installed Program Folder Anaconda.\n",
"\n",
"In my work flow, I usually only use the Ipython Notebook, but for some coding problems where I need access to the easy debugging capabilities of Spyder, I use it. We will be using the Ipython Notebook interface (web browser) mostly in this class.\n",
"\n",
"### Loading libraries\n",
"\n",
"The python universe has a huge number of libraries that extend the capabilities of python. Nearly all of these are open source, unlike packages like stata or matlab where some key libraries are proprietary (and can cost lots of money). In lots of my code, you will see this at the top:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"import sympy as sympy\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from scipy import *"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This code sets up Ipython Notebook environments (lines beginning with `%`), and loads several libraries and functions. The core scientific stack in python consists of a number of free libraries. The ones I have loaded above include:\n",
"\n",
"1. sympy: provides for symbolic computation (solving algebra problems)\n",
"2. numpy: provides for linear algebra computations\n",
"3. matplotlib.pyplot: provides for the ability to graph functions and draw figures\n",
"4. scipy: scientific python provides a plethora of capabilities\n",
"\n",
"### Creating arrays, scalars, and matrices in Python\n",
"\n",
"Scalars can be created easily like this:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5\n"
]
}
],
"source": [
"x = .5\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Vectors and Lists\n",
"\n",
"The numpy library (we will reference it by np) is the workhorse library for linear algebra in python. To creat a vector simply surround a python list ($[1,2,3]$) with the np.array function:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1 2 3]\n"
]
}
],
"source": [
"x_vector = np.array([1,2,3])\n",
"print(x_vector)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We could have done this by defining a python list and converting it to an array:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The list: [1, 2]\n",
"Has length: 2\n",
"The vector: [1 2]\n",
"Has shape: (2,)\n"
]
}
],
"source": [
"c_list = [1,2]\n",
"print(\"The list:\",c_list)\n",
"print(\"Has length:\", len(c_list))\n",
"\n",
"c_vector = np.array(c_list)\n",
"print(\"The vector:\", c_vector)\n",
"print(\"Has shape:\",c_vector.shape)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is a list, not an array: [5, 6]\n",
"\n"
]
}
],
"source": [
"z = [5,6]\n",
"print(\"This is a list, not an array:\",z)\n",
"print(type(z))"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is an array, not a list [5 6]\n",
"\n"
]
}
],
"source": [
"zarray = np.array(z)\n",
"print(\"This is an array, not a list\",zarray)\n",
"print(type(zarray))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Matrices"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[(5, 1), (6, 2)]\n",
"Note that the length of our combined list is 2 not (2 by 2): 2\n"
]
}
],
"source": [
"b = list(zip(z,c_vector))\n",
"print(b)\n",
"print(\"Note that the length of our combined list is 2 not (2 by 2):\",len(b))"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"But we can convert the list to a matrix like this:\n",
"[[5 1]\n",
" [6 2]]\n",
"\n",
"A has shape: (2, 2)\n"
]
}
],
"source": [
"print(\"But we can convert the list to a matrix like this:\")\n",
"A = np.array(b)\n",
"print(A)\n",
"print(type(A))\n",
"print(\"A has shape:\",A.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Matrix Addition and Subtraction\n",
"\n",
"### Adding or subtracting a scalar value to a matrix\n",
"\n",
"To learn the basics, consider a small matrix of dimension $2 \\times 2$, where $2 \\times 2$ denotes the number of rows $\\times$ the number of columns. Let $A=\\bigl( \\begin{smallmatrix} a_{11} & a_{12} \\\\ a_{21} & a_{22} \\end{smallmatrix} \\bigr)$. Consider adding a scalar value (e.g. 3) to the matrix $A$.\n",
"\n",
"$$\n",
"\tA+3=\\begin{bmatrix}\n",
"\t a_{11} & a_{12} \\\\\n",
"\t a_{21} & a_{22} \t\n",
"\t\\end{bmatrix}+3\n",
"\t=\\begin{bmatrix}\n",
"\t a_{11}+3 & a_{12}+3 \\\\\n",
"\t a_{21}+3 & a_{22}+3 \t\n",
"\t\\end{bmatrix}\n",
"$$\n",
"\n",
"The same basic principle holds true for $A-3$:\n",
"\n",
"$$\n",
"\tA-3=\\begin{bmatrix}\n",
"\t a_{11} & a_{12} \\\\\n",
"\t a_{21} & a_{22} \t\n",
"\t\\end{bmatrix}-3\n",
"\t=\\begin{bmatrix}\n",
"\t a_{11}-3 & a_{12}-3 \\\\\n",
"\t a_{21}-3 & a_{22}-3 \t\n",
"\t\\end{bmatrix}\n",
"$$\n",
"\n",
"Notice that we add (or subtract) the scalar value to each element in the matrix A. A can be of any dimension.\n",
"\n",
"This is trivial to implement, now that we have defined our matrix A:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[8 4]\n",
" [9 5]]\n"
]
}
],
"source": [
"result = A + 3\n",
"#or\n",
"result = 3 + A\n",
"print(result)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Adding or subtracting two matrices\n",
"\n",
"Consider two small $2 \\times 2$ matrices of dimension $2 \\times 2$. As before let $A=\\bigl( \\begin{smallmatrix} a_{11} & a_{12} \\\\ a_{21} & a_{22} \\end{smallmatrix} \\bigr)$ and let $B=\\bigl( \\begin{smallmatrix} b_{11} & b_{12} \\\\ b_{21} & b_{22} \\end{smallmatrix} \\bigr)$. To find the result of $A-B$, simply subtract each element of $A$ with the corresponding element of $B$:\n",
"\n",
"$$\n",
"A - B =\n",
"\t\\begin{bmatrix}\n",
"\t a_{11} & a_{12} \\\\\n",
"\t a_{21} & a_{22} \t\n",
" \\end{bmatrix} -\n",
"\t\\begin{bmatrix} \n",
" b_{11} & b_{12} \\\\\n",
"\t b_{21} & b_{22}\n",
"\t\\end{bmatrix} =\n",
" \\begin{bmatrix}\n",
"\t a_{11}-b_{11} & a_{12}-b_{12} \\\\\n",
"\t a_{21}-b_{21} & a_{22}-b_{22} \t\n",
"\t\\end{bmatrix}\n",
"$$\n",
"\n",
"Addition works exactly the same way:\n",
"\n",
"$$\n",
"A + B =\n",
"\t\\begin{bmatrix}\n",
"\t a_{11} & a_{12} \\\\\n",
"\t a_{21} & a_{22} \t\n",
"\t\\end{bmatrix} +\n",
"\t\\begin{bmatrix} \n",
" b_{11} & b_{12} \\\\\n",
"\t b_{21} & b_{22}\n",
"\t\\end{bmatrix} =\n",
"\t\\begin{bmatrix}\n",
"\t a_{11}+b_{11} & a_{12}+b_{12} \\\\\n",
"\t a_{21}+b_{21} & a_{22}+b_{22} \t\n",
"\t\\end{bmatrix}\n",
"$$\n",
"\n",
"An important point to know about matrix addition and subtraction is that it is only defined when $A$ and $B$ are of the same size. Here, both are $2 \\times 2$. Since operations are performed element by element, these two matrices must be conformable- and for addition and subtraction that means they must have the same numbers of rows and columns. I like to be explicit about the dimensions of matrices for checking conformability as I write the equations, so write\n",
"\n",
"$$\n",
"A_{2 \\times 2} + B_{2 \\times 2}= \\begin{bmatrix}\n",
" a_{11}+b_{11} & a_{12}+b_{12} \\\\\n",
" a_{21}+b_{21} & a_{22}+b_{22} \t\n",
"\\end{bmatrix}_{2 \\times 2}\n",
"$$\n",
"\n",
"Notice that the result of a matrix addition or subtraction operation is always of the same dimension as the two operands.\n",
"\n",
"Let's define another matrix, B, that is also $2 \\times 2$ and add it to A:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[-0.4089757 -0.03934539]\n",
" [ 0.28474541 -0.47162285]]\n"
]
}
],
"source": [
"B = np.random.randn(2,2)\n",
"print(B)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[4.5910243 , 0.96065461],\n",
" [6.28474541, 1.52837715]])"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"result = A + B\n",
"result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Matrix Multiplication\n",
"\n",
"### Multiplying a scalar value times a matrix\n",
"\n",
"As before, let $A$=$\\bigl( \\begin{smallmatrix} a_{11} & a_{12} \\\\ a_{21} & a_{22} \\end{smallmatrix} \\bigr)$. Suppose we want to multiply A times a scalar value (e.g. $3 \\times A$)\n",
"\n",
"$$\n",
"\t3 \\times A = 3 \\times \\begin{bmatrix}\n",
"\t a_{11} & a_{12} \\\\\n",
"\t a_{21} & a_{22} \t\n",
"\t\\end{bmatrix} =\n",
"\t\\begin{bmatrix}\n",
"\t 3a_{11} & 3a_{12} \\\\\n",
"\t 3a_{21} & 3a_{22} \t\n",
"\t\\end{bmatrix}\n",
"$$\n",
"\n",
"is of dimension (2,2). Scalar multiplication is commutative, so that $3 \\times A$=$A \\times 3$. Notice that the product is defined for a matrix A of any dimension.\n",
"\n",
"Similar to scalar addition and subtration, the code is simple:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[15, 3],\n",
" [18, 6]])"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"A * 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Multiplying two matricies\n",
"\n",
"Now, consider the $2 \\times 1$ vector $C=\\bigl( \\begin{smallmatrix} c_{11} \\\\\n",
" c_{21}\n",
"\\end{smallmatrix} \\bigr)$ \n",
"\n",
"Consider multiplying matrix $A_{2 \\times 2}$ and the vector $C_{2 \\times 1}$. Unlike the addition and subtraction case, this product is defined. Here, conformability depends not on the row **and** column dimensions, but rather on the column dimensions of the first operand and the row dimensions of the second operand. We can write this operation as follows\n",
"\n",
"$$\n",
"\tA_{2 \\times 2} \\times C_{2 \\times 1} = \n",
"\t\\begin{bmatrix}\n",
"\t a_{11} & a_{12} \\\\\n",
"\t a_{21} & a_{22} \t\n",
"\t\\end{bmatrix}_{2 \\times 2}\n",
" \\times\n",
" \\begin{bmatrix}\n",
"\tc_{11} \\\\\n",
"\tc_{21}\n",
"\t\\end{bmatrix}_{2 \\times 1} \t=\n",
"\t\\begin{bmatrix}\n",
"\t a_{11}c_{11} + a_{12}c_{21} \\\\\n",
"\t a_{21}c_{11} + a_{22}c_{21} \t\n",
"\t\\end{bmatrix}_{2 \\times 1}\n",
"$$\n",
"\n",
"Alternatively, consider a matrix C of dimension $2 \\times 3$ and a matrix A of dimension $3 \\times 2$\n",
"\n",
"$$\n",
"\tA_{3 \\times 2}=\\begin{bmatrix}\n",
"\t a_{11} & a_{12} \\\\\n",
"\t a_{21} & a_{22} \\\\\n",
"\t a_{31} & a_{32} \t\n",
"\t\\end{bmatrix}_{3 \\times 2}\n",
"\t,\n",
"\tC_{2 \\times 3} = \n",
"\t\\begin{bmatrix}\n",
"\t\t c_{11} & c_{12} & c_{13} \\\\\n",
"\t\t c_{21} & c_{22} & c_{23} \\\\\n",
"\t\\end{bmatrix}_{2 \\times 3}\n",
"$$\n",
"\n",
"Here, A $\\times$ C is\n",
"\n",
"$$\n",
"\\begin{align}\n",
"\tA_{3 \\times 2} \\times C_{2 \\times 3}=&\n",
"\t\\begin{bmatrix}\n",
"\t a_{11} & a_{12} \\\\\n",
"\t a_{21} & a_{22} \\\\\n",
"\t a_{31} & a_{32} \t\n",
"\t\\end{bmatrix}_{3 \\times 2}\n",
"\t\\times\n",
"\t\\begin{bmatrix}\n",
"\t c_{11} & c_{12} & c_{13} \\\\\n",
"\t c_{21} & c_{22} & c_{23} \n",
"\t\\end{bmatrix}_{2 \\times 3} \\nonumber \\\\\n",
"\t=&\\begin{bmatrix}\n",
"\t a_{11} c_{11}+a_{12} c_{21} & a_{11} c_{12}+a_{12} c_{22} & a_{11} c_{13}+a_{12} c_{23} \\\\\n",
"\t a_{21} c_{11}+a_{22} c_{21} & a_{21} c_{12}+a_{22} c_{22} & a_{21} c_{13}+a_{22} c_{23} \\\\\n",
"\t a_{31} c_{11}+a_{32} c_{21} & a_{31} c_{12}+a_{32} c_{22} & a_{31} c_{13}+a_{32} c_{23}\n",
"\t\\end{bmatrix}_{3 \\times 3}\\nonumber\t\n",
"\\end{align}\n",
"$$\n",
"\n",
"So in general, $X_{r_x \\times c_x} \\times Y_{r_y \\times c_y}$ we have two important things to remember: \n",
"\n",
"* For conformability in matrix multiplication, $c_x=r_y$, or the columns in the first operand must be equal to the rows of the second operand.\n",
"* The result will be of dimension $r_x \\times c_y$, or of dimensions equal to the rows of the first operand and columns equal to columns of the second operand.\n",
"\n",
"Given these facts, you should convince yourself that matrix multiplication is not generally commutative, that the relationship $X \\times Y = Y \\times X$ does **not** hold in all cases.\n",
"For this reason, we will always be very explicit about whether we are pre multiplying ($X \\times Y$) or post multiplying ($Y \\times X$) the vectors/matrices $X$ and $Y$.\n",
"\n",
"For more information on this topic, see this\n",
"http://en.wikipedia.org/wiki/Matrix_multiplication."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(3, 2)\n",
"(2, 2)\n"
]
}
],
"source": [
"# Let's redefine A and C to demonstrate matrix multiplication:\n",
"A = np.arange(6).reshape((3,2))\n",
"C = np.random.randn(2,2)\n",
"\n",
"print(A.shape)\n",
"print(C.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will use the numpy dot operator to perform the these multiplications. You can use it two ways to yield the same result:"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[-1.62960465 -0.66937954]\n",
" [-4.71071009 -0.47809108]\n",
" [-7.79181554 -0.28680261]]\n",
"[[-1.62960465 -0.66937954]\n",
" [-4.71071009 -0.47809108]\n",
" [-7.79181554 -0.28680261]]\n"
]
}
],
"source": [
"print(A.dot(C))\n",
"print(np.dot(A,C))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Suppose instead of pre-multiplying C by A, we post-multiply. The product doesn't exist because we don't have conformability as described above:"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"ename": "ValueError",
"evalue": "shapes (2,2) and (3,2) not aligned: 2 (dim 1) != 3 (dim 0)",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mC\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdot\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mA\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mValueError\u001b[0m: shapes (2,2) and (3,2) not aligned: 2 (dim 1) != 3 (dim 0)"
]
}
],
"source": [
"C.dot(A)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Matrix Division\n",
"The term matrix division is actually a misnomer. To divide in a matrix algebra world we first need to invert the matrix. It is useful to consider the analog case in a scalar work. Suppose we want to divide the $f$ by $g$. We could do this in two different ways:\n",
"$$\n",
"\t\\frac{f}{g}=f \\times g^{-1}.\n",
"$$\n",
"In a scalar seeting, these are equivalent ways of solving the division problem. The second one requires two steps: first we invert g and then we multiply f times g. In a matrix world, we need to think about this second approach. First we have to invert the matrix g and then we will need to pre or post multiply depending on the exact situation we encounter (this is intended to be vague for now).\n",
"\n",
"### Inverting a Matrix\n",
"\n",
"As before, consider the square $2 \\times 2$ matrix $A$=$\\bigl( \\begin{smallmatrix} a_{11} & a_{12} \\\\ a_{21} & a_{22}\\end{smallmatrix} \\bigr)$. Let the inverse of matrix A (denoted as $A^{-1}$) be \n",
"\n",
"$$\n",
"\tA^{-1}=\\begin{bmatrix}\n",
" a_{11} & a_{12} \\\\\n",
"\t\t a_{21} & a_{22} \n",
" \\end{bmatrix}^{-1}=\\frac{1}{a_{11}a_{22}-a_{12}a_{21}}\t\\begin{bmatrix}\n",
"\t\t a_{22} & -a_{12} \\\\\n",
"\t\t\t\t -a_{21} & a_{11} \n",
"\t\t \\end{bmatrix}\n",
"$$\n",
"\n",
"The inverted matrix $A^{-1}$ has a useful property:\n",
"$$\n",
"\tA \\times A^{-1}=A^{-1} \\times A=I\n",
"$$\n",
"where I, the identity matrix (the matrix equivalent of the scalar value 1), is\n",
"$$\n",
"\tI_{2 \\times 2}=\\begin{bmatrix}\n",
" 1 & 0 \\\\\n",
"\t\t 0 & 1 \n",
" \\end{bmatrix}\n",
"$$\n",
"furthermore, $A \\times I = A$ and $I \\times A = A$.\n",
"\n",
"An important feature about matrix inversion is that it is undefined if (in the $2 \\times 2$ case) $a_{11}a_{22}-a_{12}a_{21}=0$. If this relationship is equal to zero the inverse of A does not exist. If this term is very close to zero, an inverse may exist but $A^{-1}$ may be poorly conditioned meaning it is prone to rounding error and is likely not well identified computationally. The term $a_{11}a_{22}-a_{12}a_{21}$ is the determinant of matrix A, and for square matrices of size greater than $2 \\times 2$, if equal to zero indicates that you have a problem with your data matrix (columns are linearly dependent on other columns). The inverse of matrix A exists if A is square and is of full rank (ie. the columns of A are not linear combinations of other columns of A).\n",
"\n",
"For more information on this topic, see this\n",
"http://en.wikipedia.org/wiki/Matrix_inversion, for example, on inverting matrices."
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[-0.56388901 -0.64446024]\n",
" [ 1.37278794 0.07501784]]\n"
]
}
],
"source": [
"# note, we need a square matrix (# rows = # cols), use C:\n",
"C_inverse = np.linalg.inv(C)\n",
"print(C_inverse)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Check that $C\\times C^{-1} = I$:"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[ 1.00000000e+00 -6.02293165e-18]\n",
" [-7.37890427e-17 1.00000000e+00]]\n",
"Is very close to:\n",
"[[1.00000000e+00 4.09029871e-17]\n",
" [1.37169701e-17 1.00000000e+00]]\n"
]
}
],
"source": [
"print(C.dot(C_inverse))\n",
"print(\"Is very close to:\")\n",
"print(C_inverse.dot(C))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Transposing a Matrix\n",
"\n",
"At times it is useful to pivot a matrix for conformability- that is in order to matrix divide or multiply, we need to switch the rows and column dimensions of matrices. Consider the matrix\n",
"$$\n",
"\tA_{3 \\times 2}=\\begin{bmatrix}\n",
"\t a_{11} & a_{12} \\\\\n",
"\t a_{21} & a_{22} \\\\\n",
"\t a_{31} & a_{32} \t\n",
"\t\\end{bmatrix}_{3 \\times 2}\t\n",
"$$\n",
"The transpose of A (denoted as $A^{\\prime}$) is\n",
"$$\n",
" A^{\\prime}=\\begin{bmatrix}\n",
"\t a_{11} & a_{21} & a_{31} \\\\\n",
"\t a_{12} & a_{22} & a_{32} \\\\\n",
"\t\\end{bmatrix}_{2 \\times 3}\n",
"$$"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"A is\n",
"[[0 1]\n",
" [2 3]\n",
" [4 5]]\n",
"The Transpose of A is\n",
"[[0 2 4]\n",
" [1 3 5]]\n"
]
}
],
"source": [
"A = np.arange(6).reshape((3,2))\n",
"B = np.arange(8).reshape((2,4))\n",
"print(\"A is\")\n",
"print(A)\n",
"\n",
"print(\"The Transpose of A is\")\n",
"print(A.T)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One important property of transposing a matrix is the transpose of a product of two matrices. Let matrix A be of dimension $N \\times M$ and let B of of dimension $M \\times P$. Then\n",
"$$\n",
"\t(AB)^{\\prime}=B^{\\prime}A^{\\prime}\n",
"$$\n",
"For more information, see this http://en.wikipedia.org/wiki/Matrix_transposition on matrix transposition. This is also easy to implement:"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[ 4 12 20]\n",
" [ 5 17 29]\n",
" [ 6 22 38]\n",
" [ 7 27 47]]\n",
"Is identical to:\n",
"[[ 4 12 20]\n",
" [ 5 17 29]\n",
" [ 6 22 38]\n",
" [ 7 27 47]]\n"
]
}
],
"source": [
"print(B.T.dot(A.T))\n",
"print(\"Is identical to:\")\n",
"print((A.dot(B)).T)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## More python tools\n",
"\n",
"### Indexing\n",
"\n",
"Python begins indexing at 0 (not 1), therefore the first row and first column is referenced by 0,0 **not** 1,1.\n",
"\n",
"### Slicing \n",
"\n",
"Accessing elements of numpy matrices and arrays. This code grabs the first column of A:"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0 1]\n",
" [2 3]\n",
" [4 5]]\n"
]
},
{
"data": {
"text/plain": [
"array([0, 2, 4])"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"print(A)\n",
"A[:,0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"or, we could grab a particular element (in this case, the second column, last row):"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"A[2,1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The last row of A is"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([4, 5])"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"A[-1,:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Excluding the first row:"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[2, 3],\n",
" [4, 5]])"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"A[1:,:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Logical Checks to extract values from matrices/arrays:"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0 1]\n",
" [2 3]\n",
" [4 5]]\n"
]
}
],
"source": [
"print(A)"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[False False True]\n"
]
},
{
"data": {
"text/plain": [
"array([[4, 5]])"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"print(A[:,1]>4)\n",
"\n",
"A[A[:,1]>4]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### For loops\n",
"\n",
"Create a $12 \\times 2$ matrix and print it out:"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[ 0 1]\n",
" [ 2 3]\n",
" [ 4 5]\n",
" [ 6 7]\n",
" [ 8 9]\n",
" [10 11]\n",
" [12 13]\n",
" [14 15]\n",
" [16 17]\n",
" [18 19]\n",
" [20 21]\n",
" [22 23]]\n",
"(12, 2)\n"
]
}
],
"source": [
"A = np.arange(24).reshape((12,2))\n",
"print(A)\n",
"print(A.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The code below loops over the rows (12 of them) of our matrix A. For each row, it slices A and prints the row values across all columns. Notice the form of the for loop. The colon defines the statement we are looping over. For each iteration of the loop **idented** lines will be executed:"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0 1]\n",
"[2 3]\n",
"[4 5]\n",
"[6 7]\n",
"[8 9]\n",
"[10 11]\n",
"[12 13]\n",
"[14 15]\n",
"[16 17]\n",
"[18 19]\n",
"[20 21]\n",
"[22 23]\n"
]
}
],
"source": [
"for rows in A:\n",
" print(rows)"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[ 0 2 4 6 8 10 12 14 16 18 20 22]\n",
"[ 1 3 5 7 9 11 13 15 17 19 21 23]\n"
]
}
],
"source": [
"for cols in A.T:\n",
" print(cols)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### If/then/else\n",
"\n",
"The code below checks the value of x and categorizes it into one of three values. Like the for loop, each logical if check is ended with a colon, and any commands to be applied to that particular if check (if true) must be indented."
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Heads\n",
"100\n"
]
}
],
"source": [
"x=.4\n",
"\n",
"if x<.5:\n",
" print(\"Heads\")\n",
" print(100)\n",
"elif x>.5:\n",
" print(\"Tails\")\n",
" print(0)\n",
"else:\n",
" print(\"Tie\")\n",
" print(50)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### While loops\n",
"\n",
"Again, we have the same basic form for the statement (note the colons and indents). Here we use the shorthand notation `x+=1` for performing the calculation `x = x + 1`:"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"True\n",
"True\n",
"True\n",
"True\n",
"True\n",
"True\n",
"True\n",
"True\n",
"False\n",
"10\n"
]
}
],
"source": [
"x=0\n",
"while x<10:\n",
" x+=1 \n",
" print(x<10)\n",
"\n",
"print(x)"
]
}
],
"metadata": {
"hide_input": false,
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.12"
}
},
"nbformat": 4,
"nbformat_minor": 4
}