{ "cells": [ { "cell_type": "markdown", "metadata": { "toc": true }, "source": [ "

Table of Contents

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> All content here is under a Creative Commons Attribution [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/) and all source code is released under a [BSD-2 clause license](https://en.wikipedia.org/wiki/BSD_licenses). Parts of these materials were inspired by https://github.com/engineersCode/EngComp/ (CC-BY 4.0), L.A. Barba, N.C. Clementi.\n", ">\n", ">Please reuse, remix, revise, and [reshare this content](https://github.com/kgdunn/python-basic-notebooks) in any way, keeping this notice." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Module 4: Overview \n", "\n", "We cover the following topics here:\n", "\n", "1. Recap of objects and types\n", "2. What do we mean by vectors, matrices and arrays\n", "3. Using a Python library: introducing NumPy\n", "4. Creating vectors, matrices and arrays with NumPy\n", "5. Special matrices in NumPy (e.g. identity matrices, random numbers)\n", "\n", "## Preparing for this module\n", "\n", "* Not much, just a general understanding of scalars, matrices and arrays." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " \n", "\n", "This session appears lengthy, but it is a recap of very familiar topics. \n", "\n", "Quickly go over what you are comfortable with; we hope to get everyone to the same level of understanding.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Objects and type: a quick recap\n", "\n", "> \"Arrays store objects of the same type.\" \n", "\n", "There's a lot in that sentence:\n", "* ***objects***: do you recall what an object is in Python?\n", "* ***type***: do you recall what a type is?\n", "\n", "A quick recap might be helpful (refer to [session 1](https://yint.org/pybasic01) for a refresher)\n", "* ***everything in Python is an object***. For example, a numeric value, a string, a list, a tuple. These are all just objects. Objects can be assigned to a variable, and they can also be the inputs for a function.\n", "* **``type(object)``** will tell you which type of object you have. For example ``type(45.2)`` will give ``float`` as a reply.\n", "\n", "So now you should understand that an ***array*** is just a collection of these objects. Let's take a look with an example.\n", "\n", "Here is a collection of floating points objects:\n", "\n", "``[45.2, 91.2, 67.2, -23.78]``\n", "\n", "The type of the object is ``float`` (we could have also used ``int`` (integer) objects). The 4 objects are collected in a list, and that list is also an object.\n", "\n", "Remember you can always confirm the ***type*** of an ***object*** as follows. Try it:\n", "```python\n", "type(45.2)\n", "type(42)\n", "type('some text')\n", "type([45.2, 91.2, 67.2, -23.78])\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Vectors, Matrices and Arrays using NumPy\n", "\n", "Let's quickly get a few definitions out of the way, and start. Start by collecting some objects together, first singly (scalar), then in a list (vector), then as a 'spreadsheet' (matrix), then as an array (3-dimensional, or higher dimensional).\n", "\n", "\n", "### Scalars\n", "\n", "If our collection of (numeric) objects coincidentally is only a single number, we call that a ***scalar***.\n", "* ```python\n", "scalar_1 = 45.2```\n", "* ```python\n", "scalar_2 = 0```\n", "* ```python\n", "scalar_3 = -12```\n", "\n", "### Vectors\n", "\n", "A collection of scalars in a single row, or column, is very much like a `list` in regular Python. This collection we then call a ***vector***.\n", "* ```python \n", "list_1 = [1, 2, 6, -2, 0]```\n", "* ```python \n", "list_2 = [0, 0, 0, 0, 0, 0, 0, 0]```\n", "* ```python \n", "list_3 = [254.2, 501, 368.4, 697, 476.5, 188.2, 525.6, 451, 514]```\n", "\n", "\n", "We say this collection has a single dimension: a single row of numbers, or a single column of numbers. If there coincidentally is 1 number in the collection, we simply call that a scalar. But in theory we can store as many numbers as we like in our vector.\n", "\n", "Think, for example, the impeller speed of a batch reactor, measured every minute, during the duration of a batch. This 1-dimensional sequence is called a vector.\n", "\n", "### Matrix\n", "\n", "If we take several 1-dimensional vectors, but **each one of the same length**, and put them together, side-by-side then we get a ***matrix***. \n", "\n", "* ```python \n", "matrix_1 = [ [1, 2, 6, -2], [4, 3, 2, 1] ] # has 2 rows and 4 columns```\n", "* ```python \n", "matrix_2 = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] # has 3 rows and 3 columns```\n", "* ```python \n", "matrix_3 = [ [9, 8, 7, 6], [5, 4, 4, 3] ] # also has 2 rows and 4 columns```\n", "\n", "You could crudely store, as we showed above, a matrix by using a list of lists, where the main list (the outside list) contains objects which themselves are lists. This is perfectly valid in Python: remember that a list can contain objects of any type, including other lists. But while this \"list-of-lists\" approach can store your data, it would not be great for calculations.\n", "\n", "**Try this:** (the result is complely unintuitive for mathematical operations)\n", "```python\n", "matrix_1 + matrix_3\n", "matrix_3 + 7\n", "```\n", " \n", "Another point to note is that a vector is simply a matrix, but where one of the dimensions is equal to 1: either 1 row, or 1 column. \n", "\n", "Matrices are widely used in engineering and data analysis. Often each row is an object, or a sample, or an observation. And each column represents some sort of value measured on that object or sample. For example:\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Measurement 1Measurement 2Measurement 3Measurement 4
Sample 15.50.55-23.4561522.2
Sample 26.70.44-22.2526616.4
Sample 34.90.61-38.1612515.7
\n", "This matrix would have 3 rows and 4 columns.\n", "\n", "\n", "### Array\n", "\n", "If we take several 2-dimensional matrices, but **each one with the same number of rows and columns**, and put them together, then we get a ***3-dimensional array***. \n", "\n", "A matrix was a list-of-lists. We can go up to a third dimension and make a list-of-lists-of-lists. \n", "\n", "Why stop there? We can go to higher and higher dimensions. We use a general names for such a collection of (numeric) objects: an ***array***. \n", "\n", "An array is an *n*-dimensional structure of numbers. You can therefore say:\n", "* a vector is a 1-dimensional data structure\n", "* a matrix is a 2-dimensional data structure\n", "* an array is an *n*-dimensional data structure\n", "\n", "\n", " \n", "\n", "For example, a 3-dimensional array here shows data collected in a lab: we are performing the experiment several times (``N``, the layers - each layer is a matrix actually - that lies on top of each other). \n", "\n", "In each experiment we collect a matrix of data from several sensors. There are ``K`` sensors. We set the sensors to collect data on a regular interval, once every 3 seconds, for example, so that we end up with exactly the same number of samples per sensor, ``J`` values per sensor.\n", "\n", "\n", "Storing the data like this is useful, because now you could perform calculations on all experiments over all time, for all sensors in array **X**.\n", "\n", "*For example:* you can calculate the average in the direction of arrow ``J``, to reduce the *array* to a *matrix*. That matrix would be the average value of the sensor for the experiments. That reduced matrix would have ``N`` rows and ``K`` columns.\n", "\n", "Engineering applications benefit from using *vectors*, or *matrices* or *arrays*: they are sequences of data all of the _same type_. Arrays behave a lot like lists in Python, except for the constraint that all elements have the same type. \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Libraries in Python: introducing NumPy for working with arrays\n", "\n", "There is an important Python library in science and engineering, called **NumPy**, \n", "that provides support for _n-dimensional array_ data structures (a.k.a, `ndarray`).\n", "\n", "Later on we will learn about the library called ``pandas`` (Python Data Analysis Library), which is better suited than NumPy for many situations. But underneath each pandas dataframe (we will define that term later), exists a NumPy array. So understanding NumPy is key to understanding pandas. Learning NumPy is also an easy step for people coming from MATLAB.\n", "\n", "Let us import NumPy and get started.\n", "\n", "### Importing libraries\n", "\n", "First, a word on importing libraries to expand your running Python session. Because libraries are large collections of code and are for special purposes, they are not loaded automatically when you launch Python (or IPython, or Jupyter). You have to import a library using the `import` command. For example, to import **NumPy**, you can enter:\n", "\n", "```python\n", "import numpy\n", "```\n", "\n", "Once you execute that command, you can call any NumPy function using the dot notation, prepending the library name. For example, some commonly used functions are:\n", "\n", "* [`numpy.sqrt()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.sqrt.html)\n", "* [`numpy.ones()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ones.html#numpy.ones)\n", "* [`numpy.zeros()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html#numpy.zeros)\n", "* [`numpy.copy()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.html#numpy.copy)\n", "\n", "\n", "Part of the community effort of creating the Python libraries, is also an effort at maintaining excellent documentation. \n", "\n", "### To try:\n", ">Click and read one of those links to explore the documentation - the pages each have the same layout, so once you know where to look, you can quickly search and refer to the documentation for other functions.\n", "\n", "> Also try: ``dir(numpy)``. Do you remember what the ``dir(...)`` function does?\n", "\n", "The ``dir(...)`` function applies to any ***object*** in Python, and ``numpy`` here, once imported, is also an object.\n", "\n", "> What ***type*** is ``numpy`` ?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Importing libraries as an alias\n", "\n", "You will find _a lot_ of source code that uses a different syntax for importing. Most often you will see:\n", ">```python\n", ">import numpy as np\n", ">```\n", "\n", "All this does is create an alias for `numpy` with the shorter string `np`, so you then would call a **NumPy** function like this: `np.linspace()` instead of the lengthier ``numpy.linspace()``.\n", "\n", " This is just an alternative way of doing it. It is arguably better that you are explicit (using the full ``numpy.``), but practicality, code reuse, and screen real-estate often dictate that people write it simply as ``np``. Both are fine.\n", "\n", "```python\n", "import numpy\n", "import numpy as np # both do the same\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Creating your first array .... well vector, to be specific\n", "\n", "To create a NumPy array from an existing Python ``list`` of numbers, we use **`numpy.array()`**, like this:\n", "\n", "```python\n", "my_list = [3, 4, 7, -2, 11]\n", "np.array(my_list)\n", "\n", "# or more compactly, without the intermediate variable:\n", "np.array([3, 4, 7, -2, 11])\n", "```\n", "\n", "Try it yourself:\n", "\n", ">Create an array of 11 numbers below, some negative, some positive, some integers, some floating point\n", "\n", "```python\n", "# Create a vector of 11 numbers\n", "import numpy as np\n", "eleven = np.array([ ... ])\n", "print(eleven)\n", "print(len(eleven)) # verify the length\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python allows you to create lists of mixed types, for example, strings, floating point, integers, etc.\n", "What happens if you try creating a NumPy array from a mixed list of object types?\n", "\n", "***What happens?***\n", "\n", "In this list there are 3 objects, of 3 different types. Try running the code below to verify:\n", "```python\n", "my_list = ['abc', 123, 456.7] \n", "np.array(my_list)\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Creating vectors, matrices and arrays with NumPy\n", "\n", "NumPy offers many [ways to create arrays](https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html#routines-array-creation). Also read [this overview](https://docs.scipy.org/doc/numpy/user/basics.creation.html#arrays-creation).\n", "\n", "\n", "### Creating your first vector with NumPy\n", "> 1. Scroll through the first link above to see just how many ways there are.\n", "> 2. One of the simplest vectors we can create is a vector of just ones (1's). Try the `numpy.ones()` command below. We must tell NumPy how many array elements we would like. \n", " \n", "```python\n", "# To try: change the '5' to some other integer number\n", "import numpy as np\n", "np.ones(shape=5) # Using the explicit function call\n", "np.ones(5) # often we use this shortcut instead\n", "```\n", "\n", "There is also a command to create a vector of zeros:\n", "```python\n", "np.zeros(shape=3)\n", "np.zeros(3)\n", "```\n", "\n", "> Here you see that Python functions can be called by specifying the function input name: in this example the single input ``shape`` is specified in ``np.zeros(shape=...)``." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Creating your first matrix (a two-dimensional array)\n", "\n", "For this we use the ``.ones()`` or ``.zeros()`` command, but we just specify the ``shape`` argument to differently. Instead of an integer, we provide a tuple.\n", "\n", "```python\n", "twoD = np.ones(shape=(5,7))\n", "print(twoD)\n", "\n", "# Verify that the shape is what you expect:\n", "print(twoD.shape)\n", "print('------------')\n", "\n", "naughts = np.zeros((5,7))\n", "print(naughts)\n", "print(type(naughts)) # you have now created an object with type `numpy.ndarray`\n", "```\n", "\n", "Every NumPy array can be queried using the ``.shape`` attribute. That means, add ``.shape`` to the array, and you will ask Python to return the attribute of that array called ``shape``." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Creating your first multi-dimensional array\n", "\n", "Why stop at two-dimensions? Create a 3-dimensional array with 2 rows, 3 columns and 4 layers: in other words a $2 \\times 3 \\times 4$ array.\n", "\n", "Just adjust the `tuple` provided to the `shape` argument:\n", "```python\n", "threeD = np.zeros(shape=(2,3,4))\n", "print(threeD)\n", "print(threeD.shape)\n", "```\n", "\n", "> Is this what you expected to see? You might have to imagine the 3rd dimension going in and out of the screen.\n", "> \n", "> 1. Try to create a matrix with 4 rows and 5 columns, where every value in the matrix is the number 8. Do this by making a matrix of only ``.ones()`` and multiplying that matrix by the value of 8.\n", ">\n", "> 2. Now do the same thing, using the ``np.full`` command. If you need help, please see the [Numpy documentation for the ``np.full`` command](https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html#numpy.full]) .\n", "\n", "```python\n", "\n", "# Step 1:\n", "eights = np.ones( ___ ) * ___\n", "print(eights)\n", "\n", "# Step 2:\n", "eight_again = np.full(shape=___, fill_value=___)\n", "print(eight_again)\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Summary so far\n", "\n", "You have created vectors, matrices and arrays. These have a specific ``.shape`` attribute that you can check.\n", "\n", "There is are several attributes of interest, but one that you will find useful is the ``.ndim`` (the number of dimensions). Try it on one of your prior arrays.\n", "\n", "These objects are of the type ``numpy.ndarray``: an n-dimensional array." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Further ways of creating NumPy arrays\n", "\n", "In this section we will look at creating arrays, particularly matrices, in an efficient manner. \n", "\n", "1. Identity matrices: what if you need an [identity matrix](https://en.wikipedia.org/wiki/Identity_matrix) (a matrix with 1's on the diagonal)?\n", "2. Random matrices: arrays filled with random numbers\n", "3. Vector sequences: say you need a vector where the entries are ``[0, 1, 2, 3, 4, ..., 9]``\n", "4. Matrix from a vector: take a vector (of say 12 entries) and [reshape](https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html) it into an array (of 3 rows and 4 columns)\n", "\n", "In the next section we will look at each one of these.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Identity matrices\n", "\n", "A square matrix with 1's on the diagonal and zeros everywhere else is known as an identity matrix. For example a $4\\times 4$ identity matrix is: $$I_4 = \\begin{bmatrix}\n", "1 & 0 & 0 & 0 \\\\\n", "0 & 1 & 0 & 0 \\\\\n", "0 & 0 & 1 & 0 \\\\\n", "0 & 0 & 0 & 1 \\end{bmatrix}$$\n", "\n", "```python\n", "import numpy as np\n", "\n", "# Read the help text for the `identity` function:\n", "help(np.identity)\n", "id5 = np.identity(n=5)\n", "print(id5)\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A similar function to ``np.identity(...)`` is ``np.eye(...)``. It is a play on words, where ``eye`` refers to the uppercase letter $I$. The above above $4\\times 4$ matrix is often written as $I_4$ in mathematical notation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Try the following, to see what they produce:**\n", "\n", "```python\n", "also_id5 = np.eye(5)\n", "print(also_id5)\n", "print('-----')\n", "\n", "yet_again = np.eye(5, 5)\n", "print(yet_again)\n", "print('-----')\n", "\n", "another_id5 = np.eye(5, 5, 0) # start the 1's in the 0th position (i.e. row 1 and column 1)\n", "print(another_id5)\n", "print('-----')\n", "\n", "# What if we want diagonal ones, but not on the main diagonal,\n", "# but starting in the first row and third column rather?\n", "print(np.eye(5, 5, 2))\n", "```\n", "\n", ">After the above, can you explain the difference between ``np.identity()`` and ``np.eye()``?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Arrays of random numbers\n", "\n", "For simulations it is often helpful to create and use arrays of random values. Each value might be a starting position or state. Or sometimes you just want to test a piece of code, not only with 1's and 0's, but any random values.\n", "\n", "For this it is helpful to create arrays of any shape, filled with random values:\n", "\n", "```python\n", "import numpy as np\n", "\n", "# Random floats between 0 (included) and 1 (not included)\n", "rnd_matrix = np.random.random(size=(4,3)) \n", "print(rnd_matrix)\n", "\n", "# Or try a multi-dimensional array\n", "rnd_array = np.random.random(size=(4, 2, 3))\n", "print(rnd_array)\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sometimes we want random integers though, between some ``low``er and upper (``high``) bounds. The random values may include the ``low`` values, but will be till just under the ``high`` value specified.\n", "\n", "```python\n", "# Run this code a few times to verify that you get -3, but never a +7\n", "rnd_int = np.random.randint(low=-3, high=7, size=(4, 5))\n", "print(rnd_int)\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Sequences\n", "\n", "Vectors containing a sequence, such as ``[0, 1, 2, ... 9]`` or ``[2, 4, 6, 8, ... 12]`` are often used as a starting point for calculations. To create these we use the `numpy.arange()` and `numpy.linspace()` commands.\n", "\n", "*Syntax:*\n", "\n", "`numpy.arange(start, stop, step)`\n", "\n", "* `start` by default is zero\n", "* `stop` is not inclusive (in other words, NumPy will stop just before this value), and \n", "* the `step` has a default value of 1.\n", "\n", "As mentioned above, Python functions can be called by specifying the input arguments (``start`` and ``stop`` and ``step`` are the argument names).\n", "\n", "Try it out below:\n", "```python\n", "import numpy as np\n", "np.arange(4)\n", "\n", "# We could have also written, but you will \n", "# agree that this is unnecessary, as the defaults\n", "# are already good enough. But this is explicit:\n", "np.arange(start=0, stop=4, step=1)\n", "\n", "np.arange(start=2, stop=6, step=1)\n", "\n", "# Leave `step` unspecified if it is just \"1\"\n", "np.arange(start=2, stop=6) \n", "\n", "# Most common usage: leave all arguments unspecified\n", "np.arange(2, 6) \n", "\n", "# Jump in steps of 2\n", "np.arange(start=2, stop=9, step=2) \n", "np.arange(2, 9, 2)\n", "```\n", "\n", "> We saw the built-in Python ``range`` function in [an earlier module](https://yint.org/pybasic02). So what is the difference between the NumPy library's ``np.arange`` function and the built-in ``range`` function?\n", ">\n", "> 1. Try replacing ``np.arange(...)`` with ``range`` and see what differences you notice.\n", "> 2. Try using ``np.arange(...)``, but step in increments of 0.5, or 0.33333 instead. Note that you cannot do this with the ``range(...)`` function.\n", "> 3. Create a sequence of values starting at $-4$ and ending just below $+4$, in steps of $1$\n", "> 4. Create a sequence of values starting at $-2$ and ending just below $+2$, in steps of $0.5$. How many elements are in the sequence? Remember the ``len`` function? What about the ``.shape`` attribute?\n", ">5. Start at $+2$ and step ***down*** in increments of $0.25$, until just before $-2$. How many elements are in the sequence?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There is also the `np.linspace()` command, which is similar to `np.arange()`. The differences are:\n", "* you specify the length of your sequence, instead of a step size. \n", "* the `stop` value ***is included*** by default, but it can be removed.\n", "\n", "It returns an array with evenly spaced numbers over the specified interval. \n", "\n", "*Syntax:*\n", "\n", "`np.linspace(start, stop, num)`\n", "\n", "where the default value of `num=50`. Type `help(np.linspace)` to see how you can either include or exclude the endpoint. \n", "\n", "### To try:\n", "\n", ">1. Confirm that you indeed get a sequence of 50 values when you do not specify ``num``. Also confirm that the ``stop`` value is the last value in the vector.\n", ">2. Try to get a vector with fewer elements, say 6, instead of 50.\n", ">3. Go backwards again: create a sequence where the numbers decrease in value." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reshaping\n", "\n", "One you have a sequence of numbers in a long vector, you might want to fold them up in a matrix, or an multi-dimensional array.\n", "\n", "Use the ``reshape`` function of a NumPy array to do that.\n", "\n", "```python\n", "vector = np.arange(12)\n", "matrix = vector.reshape((3, 4))\n", "```\n", "\n", "Note the order! NumPy will first fill each row, so the first row will be ``[0, 1, 2, 3]`` and then the next row will be ``[4, 5, 6, 7]``, and so on.\n", "\n", "Try it:\n", "\n", "```python\n", "vector = np.arange(12)\n", "print('This is a vector with a shape of: ' + str(vector.shape))\n", "matrix = vector.reshape((4, 3))\n", "matrix = vector.reshape((2, 6))\n", "print('This is a matrix with a shape of: ' + str(matrix.shape))\n", "matrix = vector.reshape((4, 4)) # intentional error\n", "``` " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Next steps\n", "\n", "Above we have created vectors, matrices and arrays in all sorts of formats. With ones, zeros, diagonals, random numbers, and sequences of numbers. \n", "\n", "Next it is time to put these to use, and perform calculations on them. This is in the next module, module 5." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ">***Feedback and comments about this worksheet?***\n", "> Please provide any anonymous [comments, feedback and tips](https://docs.google.com/forms/d/1Fpo0q7uGLcM6xcLRyp4qw1mZ0_igSUEnJV6ZGbpG4C4/edit)." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# IGNORE this. Execute this cell to load the notebook's style sheet.\n", "from IPython.core.display import HTML\n", "css_file = './images/style.css'\n", "HTML(open(css_file, \"r\").read())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.7.3" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": true, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": true, "toc_position": { "height": "calc(100% - 180px)", "left": "10px", "top": "150px", "width": "376px" }, "toc_section_display": true, "toc_window_display": true } }, "nbformat": 4, "nbformat_minor": 2 }