{"nbformat_minor": 0, "nbformat": 3, "metadata": {"signature": "sha256:483b4aae21ef9a9b07174868a600d9c39f6d75b072739a78437831abe4c67463", "name": ""}, "worksheets": [{"cells": [{"input": ["import numpy as np"], "collapsed": false, "metadata": {}, "cell_type": "code", "outputs": [], "language": "python", "prompt_number": 1}, {"input": ["a = np.arange(9).reshape(3, 3)\n", "print(a.shape)\n", "print(a)\n", "b = np.arange(4, 4+9).reshape(3, 3)\n", "print(b.shape)\n", "print(b)"], "collapsed": false, "metadata": {}, "cell_type": "code", "outputs": [{"stream": "stdout", "text": ["(3, 3)\n", "[[0 1 2]\n", " [3 4 5]\n", " [6 7 8]]\n", "(3, 3)\n", "[[ 4 5 6]\n", " [ 7 8 9]\n", " [10 11 12]]\n"], "output_type": "stream"}], "language": "python", "prompt_number": 2}, {"input": ["a+b"], "collapsed": false, "metadata": {}, "cell_type": "code", "outputs": [{"text": ["array([[ 4, 6, 8],\n", " [10, 12, 14],\n", " [16, 18, 20]])"], "metadata": {}, "output_type": "pyout", "prompt_number": 3}], "language": "python", "prompt_number": 3}, {"source": ["So this is easy and one-to-one.\n"], "metadata": {}, "cell_type": "markdown"}, {"source": ["---\n", "\n", "What if the shapes do not match?"], "metadata": {}, "cell_type": "markdown"}, {"input": ["a = np.arange(9).reshape(3, 3)\n", "print(a.shape)\n", "print(a)\n", "b = np.arange(3)\n", "print(b.shape)\n", "print(b)"], "collapsed": false, "metadata": {}, "cell_type": "code", "outputs": [{"stream": "stdout", "text": ["(3, 3)\n", "[[0 1 2]\n", " [3 4 5]\n", " [6 7 8]]\n", "(3,)\n", "[0 1 2]\n"], "output_type": "stream"}], "language": "python", "prompt_number": 4}, {"source": ["What will this do?"], "metadata": {}, "cell_type": "markdown"}, {"input": ["a+b"], "collapsed": false, "metadata": {}, "cell_type": "code", "outputs": [{"text": ["array([[ 0, 2, 4],\n", " [ 3, 5, 7],\n", " [ 6, 8, 10]])"], "metadata": {}, "output_type": "pyout", "prompt_number": 5}], "language": "python", "prompt_number": 5}, {"source": ["It has *broadcast* along the last axis!"], "metadata": {}, "cell_type": "markdown"}, {"source": ["---\n", "\n", "Can we broadcast along the *first* axis?"], "metadata": {}, "cell_type": "markdown"}, {"input": ["a+b.reshape(3, 1)"], "collapsed": false, "metadata": {}, "cell_type": "code", "outputs": [{"text": ["array([[ 0, 1, 2],\n", " [ 4, 5, 6],\n", " [ 8, 9, 10]])"], "metadata": {}, "output_type": "pyout", "prompt_number": 6}], "language": "python", "prompt_number": 6}, {"source": ["Rules:\n", "\n", "* Shapes are matched axis-by-axis from last to first.\n", "* A length-1 axis can be *broadcast* if necessary."], "metadata": {}, "cell_type": "markdown"}], "metadata": {}}]}