{ "cells": [ { "cell_type": "markdown", "id": "e5c13795", "metadata": { "id": "QFg76NCRWAqs" }, "source": [ " \n", "\n", "# **NumPy Arrays**" ] }, { "cell_type": "markdown", "id": "64e03610", "metadata": { "id": "t3d_pJFEwLX_" }, "source": [ "## Import NumPy\n", "\n", "The first step to use NumPy is to import it. You can do that using `import NumPy`. Importing allows a Python file or a Python module to access the script from another Python file or module so that we can have access to its functions and properties.\n", "\n", "Ususally we import NumPy as `np` alias; this is just a shorter name referring to the same thing. This is optional." ] }, { "cell_type": "code", "execution_count": 1, "id": "51a0ff34", "metadata": { "id": "DYCMSLTXnr5X" }, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "markdown", "id": "87277992", "metadata": { "id": "7AWNJibgMd0D" }, "source": [ "Here is a basic example of initializing a NumPy array:" ] }, { "cell_type": "code", "execution_count": 2, "id": "fbc6db4e", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Ko2oQEQ5MLOu", "outputId": "535edd8a-df4e-4a89-f7fb-3e67a5d34c1e" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1 2 3]\n" ] } ], "source": [ "a = np.array([1, 2, 3])\n", "print(a)" ] }, { "cell_type": "markdown", "id": "a7162dd6", "metadata": { "id": "cJWEWXFbHTPL" }, "source": [ "## How are lists different from NumPy arrays?\n", "\n", "When writing code, there are often multiple ways to achieve the same result. However, the speed of the program is usually important, so choosing the faster method is more convenient. While both lists and NumPy can sometimes accomplish the same tasks, NumPy is generally **faster** and more memory-efficient. Additionally, there are some operations that lists cannot perform at all, but NumPy can. Here are some examples:" ] }, { "cell_type": "code", "execution_count": 3, "id": "0a427e5d", "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 207 }, "id": "Qua7tQvzJBzF", "outputId": "21b03f12-6feb-4bc8-a9a0-ab53c848b5c2" }, "outputs": [], "source": [ "# Lists\n", "a = [1, 3, 5]\n", "b = [1, 2, 3]\n", "\n", "# print (a*b) # gives error!!!" ] }, { "cell_type": "code", "execution_count": 4, "id": "cea40c74", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "ieM33AguJRaJ", "outputId": "9424aa58-dba4-4b64-c94e-21fcd81f8b4c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 1 6 15]\n" ] } ], "source": [ "# Numpy\n", "a = np.array([1, 3, 5])\n", "b = np.array([1, 2, 3])\n", "\n", "print (a*b) # it works!!!" ] }, { "cell_type": "markdown", "id": "e53f47ad", "metadata": { "id": "S_YnnE5_yVZ_" }, "source": [ "## Creating Array\n", "\n", "To create an array you can use the `np.array()` function; as the input we can pass a numerical list. Below, you can see some examples of one-, two- and three-dimensional arrays." ] }, { "cell_type": "code", "execution_count": 5, "id": "2f82c15b", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "luQ4q86FdfBJ", "outputId": "389bc72e-701a-49c2-b326-9a0646bdec73" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1 2 3]\n" ] } ], "source": [ "a=np.array([1,2,3]) #1D array\n", "print(a)" ] }, { "cell_type": "code", "execution_count": 6, "id": "a7e0a8db", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "rvHHGfMNdezZ", "outputId": "68e9d633-ed24-45a2-a2a9-56e85761c4a9" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 2 3]\n", " [4 5 6]]\n" ] } ], "source": [ "B=np.array([[1,2,3],[4,5,6]]) #2D array\n", "print(B)" ] }, { "cell_type": "code", "execution_count": 7, "id": "d5f36161", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "dOe7Kw2QzMoK", "outputId": "48ee2ee9-8434-4eec-ab10-e040790bb2cb" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[[1 2]\n", " [3 4]]\n", "\n", " [[5 6]\n", " [7 8]]]\n" ] } ], "source": [ "C=np.array([[[1,2],[3,4]],[[5,6],[7,8]]]) #3D array\n", "print(C)" ] }, { "cell_type": "markdown", "id": "1ccee166", "metadata": { "id": "LDLUY2Me1dUg" }, "source": [ "💡Note that NumPy arrays are of type `ndarray`. You can check this using `type(array_name)`." ] }, { "cell_type": "code", "execution_count": 8, "id": "0f21ffa6", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "bPC5P3Qq1ZHD", "outputId": "853683a6-7ff8-4b22-f885-35c6b98817d8" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(B))" ] }, { "cell_type": "markdown", "id": "b151b311", "metadata": { "id": "ag8xybgR0bie" }, "source": [ "## Dimension, Shape, and Size\n", "\n", "Dimension, shape and size refer to different properties in arrays. It's important to know and check them in our program. Here's a brief definition,\n", "* __Dimension:__ the number of axes (dimensions) of the array.\n", "\n", " ✅ Syntax: `array_name.ndim`\n", "* __Shape:__ This is a tuple of integers indicating the size of the array in each dimension. For a matrix with **n rows** and **m columns,** the shape will be **(n,m)**.\n", "\n", " ✅ Syntax: `array_name.shape`.\n", "* __Size:__\n", "the total number of elements of the array. This is equal to the product of the elements of shape.\n", "\n", " ✅ Syntax: `array_name.size`" ] }, { "cell_type": "code", "execution_count": 9, "id": "8e70dd6c", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "ouAHAtU02iW2", "outputId": "9e39c6f8-35fe-4748-acde-38e5d8a1c2b7" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a_dimention = 1\n", "a_shape = (3,)\n", "a_size = 3\n" ] } ], "source": [ "print(\"a_dimention =\",a.ndim)\n", "print(\"a_shape =\",a.shape)\n", "print(\"a_size =\",a.size)" ] }, { "cell_type": "code", "execution_count": 10, "id": "ecec5b71", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "99SIOorgeSVw", "outputId": "7a37e358-ff75-48d9-9900-a49678de653b" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "B_dimention = 2\n", "B_shape = (2, 3)\n", "B_size = 6\n" ] } ], "source": [ "print(\"B_dimention =\",B.ndim)\n", "print(\"B_shape =\",B.shape)\n", "print(\"B_size =\",B.size)" ] }, { "cell_type": "code", "execution_count": 11, "id": "97309f91", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "o0yea5RpT5wV", "outputId": "02840a83-be8f-4b90-9942-fb31c937fbb5" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "(2, 2, 2)\n", "8\n" ] } ], "source": [ "print(C.ndim)\n", "print(C.shape)\n", "print(C.size)" ] }, { "cell_type": "markdown", "id": "370bd0c7", "metadata": { "id": "ZImrnj7D6uio" }, "source": [ "### `np.newaxis`\n", "\n", "It's important to note that one-dimensional arrays are different from two-dimensional arrays in NumPy. Therefore, a column or a row vector can be saved both as a one- and a two-dimensional array. However, for most matrix operations using column/row vectors and matrices, you will need to have them both as two-dimensional arrays, or you will get an error. To add a new dimension to an array you can use the following command:" ] }, { "cell_type": "code", "execution_count": 12, "id": "ef35ea9c", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "SPUZE065RrKQ", "outputId": "9a97e9c1-0d95-4151-ab29-39c21d50c329" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(4,)\n", "(1, 4)\n", "(4, 1)\n" ] } ], "source": [ "array_1D = np.array([1, 2, 3, 4])\n", "print(array_1D.shape)\n", "\n", "# row vector\n", "array_2D_row = array_1D[np.newaxis, :] # Adds a new axis to create a 2D array with one row\n", "print(array_2D_row.shape)\n", "\n", "#column vector\n", "array_2D_column = array_1D[:, np.newaxis] # Adds a new axis to create a 2D array with one column\n", "print(array_2D_column.shape)" ] }, { "cell_type": "markdown", "id": "942bb2e6", "metadata": { "id": "_I5PRL0IWu_P" }, "source": [ "## Array Indexing\n", "\n", "You can access specific elements in an array by specifying their row and column indices using the syntax `array_name [row, column]` or by specifying the exact location in a multi-dimensional array using `array_name [dim1_ind, dim2_ind, ...]`.\n", "\n", "You can also easly access a specific row or column:\n", "\n", "* To access a specific row, use the syntax `array_name[row, :]`.\n", "* To access a specific column, use the syntax `array_name[:, column]`.\n", "\n", "You can also access specific elements in a row or column and skip the rest using a method called **slicing**. Slicing allows you to specify the start index, end index, and step size with the syntax `array_name[start:end:step, start:end:step, ...]`.\n", "\n", "Here is how the slicing syntax is interpreted:\n", "\n", "|Syntax |Description|\n", "|-------------- |------- |\n", "|[start : end] | step size is 1 |\n", "|[start : : step]| end is the last index \t | \n", "|[ : end : step] | start is 0, the first index|\n", "|[ : ] | all elements in that dimension with step=1|\n", "\n", "💡Remember that array indexing starts at **zero**.\n", "\n", "Here are some examples to illustrate array indexing and slicing with multi-dimensional arrays:" ] }, { "cell_type": "code", "execution_count": 13, "id": "b1c123b6", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "lxrJC5DHe10A", "outputId": "395e6062-7871-45e3-e766-b32d920ec4ac" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a= \n", " [[1 2 3]\n", " [4 5 6]\n", " [7 8 9]]\n" ] } ], "source": [ "# 3x3 2D array\n", "a = np.array([[1, 2, 3],\n", " [4, 5, 6],\n", " [7, 8, 9]])\n", "print(\"a= \\n\", a)" ] }, { "cell_type": "code", "execution_count": 14, "id": "f2676e1b", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "5stQ5zUBe1pV", "outputId": "99f7f5c1-335e-47b8-f0a3-8f08e2c59f76" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a[1, 2]= 6\n" ] } ], "source": [ "# Find the last element of the second row\n", "print(\"a[1, 2]=\", a[1, 2])" ] }, { "cell_type": "code", "execution_count": 15, "id": "9ddca022", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "h1jROmSHe1fR", "outputId": "a2dea383-a2c9-4ff7-fe80-db0d3847d9cb" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a[0, -1]= 3\n" ] } ], "source": [ "# Find the last element of the first row\n", "print(\"a[0, -1]=\", a[0, -1])" ] }, { "cell_type": "code", "execution_count": 16, "id": "e1948f55", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "nUmem-SKe1ZJ", "outputId": "60c520a9-a2f9-4553-b117-ecc64259a861" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First row= [1 2 3]\n" ] } ], "source": [ "# Get the first row\n", "print(\"First row=\", a[0, :])" ] }, { "cell_type": "code", "execution_count": 17, "id": "18743e14", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "ogu1_Z0Ae1QW", "outputId": "ddca50e3-5bf5-428a-9793-d8363ef272f2" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First column= [1 4 7]\n" ] } ], "source": [ "# Get the first column\n", "print(\"First column=\", a[:, 0])" ] }, { "cell_type": "code", "execution_count": 18, "id": "18da4688", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "uLzznFvre1JE", "outputId": "7e302625-04f1-46a1-d485-a0853339a20a" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Slicing: \n" ] } ], "source": [ "# Slicing\n", "print(\"Slicing: \")" ] }, { "cell_type": "code", "execution_count": 19, "id": "83873849", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "uQT3wQZee-G0", "outputId": "7ee34868-f559-4e1d-8bc8-59cda415a3f4" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1 3]\n" ] } ], "source": [ "print(a[0, 0:3:2]) # First row, start=0, end=3, step=2\n", "# Selects elements from the first row (index 0)\n", "# starting from the 0th index to the 2nd index (not including the 3rd index)\n", "# taking every second element" ] }, { "cell_type": "code", "execution_count": 20, "id": "08ae81ae", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "VKcJwNLG5cvw", "outputId": "981535c9-5f6f-453e-dde5-3016fd7df264" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 3]\n", " [7 9]]\n" ] } ], "source": [ "print(a[0:3:2, 0:3:2])\n", "# Selects elements from rows and columns starting from index 0 to index 2 (not including index 3)\n", "# taking every second element in both dimensions" ] }, { "cell_type": "markdown", "id": "3ecc8557", "metadata": { "id": "fdKPESLQtmJl" }, "source": [ "### Replacing an Element Inside an Array" ] }, { "cell_type": "code", "execution_count": 21, "id": "31cab0ab", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "4Vv0RG8Nt8oF", "outputId": "b1459f50-184d-412e-ceb4-9f97593850f9" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First version: \n", " [[ 2 4 6]\n", " [ 8 10 13]]\n", "Second version: \n", " [[ 2 4 6]\n", " [ 8 10 12]]\n", "Third version: \n", " [[ 1 4 6]\n", " [ 2 10 12]]\n" ] } ], "source": [ "b = np.array([[2, 4, 6], [8, 10, 13]])\n", "print(\"First version: \\n\", b)\n", "\n", "# Replace the last element (13) with 12.\n", "b[1,2] = 12\n", "print(\"Second version: \\n\", b)\n", "\n", "# Replace the first column with 1 and 2\n", "b[:,0] = [1, 2]\n", "print(\"Third version: \\n\", b)" ] }, { "cell_type": "markdown", "id": "0a295d7a", "metadata": { "id": "1_84lKb6-HHx" }, "source": [ "## Initializing Commonly Used Arrays\n", "\n", "NumPy offers several built-in functions that allow us to create arrays of different shapes filled with specified values. This is very useful, especially for creating larger arrays. Below is a list of these functions. Note that you don't need to memorize the syntax, but just know that these functions exist. You can always look them up online when you need them.\n", "\n", "|Function | Description|\n", "|--|--|\n", "|``np.zeros((shape))``| array filled with zeros|\n", "|``np.ones((shape))``|array filled with ones|\n", "|``np.full((shape), value)``|array filled with specified value|\n", "|``np.random.rand(shape)``|array filled with random floats|\n", "|``np.random.randint(min,max, size=(shape))``|array filled with random integers between ``min`` and ``max``|\n", "|``np.identity(n)``|square identity matrix of shape ``n*n``|\n", "\n", "Below are some examples in code. Uncomment the print function if you want to see the results. Note that the shape is again in the format (row, column)." ] }, { "cell_type": "code", "execution_count": 22, "id": "15d91e0d", "metadata": { "id": "DPI5RqAzGeJL" }, "outputs": [], "source": [ "A=np.zeros((2,4))\n", "#print(A)\n", "\n", "B=np.ones((3,2))\n", "#print(B)\n", "\n", "C=np.full((2,2), 0.5)\n", "#print(C)\n", "\n", "D=np.random.rand(2,3)\n", "#print(D)\n", "\n", "E=np.random.randint(-5,5, size=(2,3))\n", "#print(E)\n", "\n", "F=np.identity(3)\n", "#print(F)" ] }, { "cell_type": "markdown", "id": "80fb8f1e", "metadata": { "id": "6v3PIsdXHpOR" }, "source": [ "## Reshaping Arrays\n", "\n", "Numpy provides several functions for reshaping arrays. Reshaping changes the dimensions (shape) of the array while preserving the total number of elements.\n", "\n", "|Function | Description|\n", "|--|--|\n", "|``arr.reshape()``| to change the shape of an array while keeping the original data|\n", "|``arr.flatten()``| function converts a multi-dimensional array into a one-dimensional array|\n", "|``np.vstack((arr1, arr2))``|stacks arrays vertically, i.e., it combines arrays along rows|\n", "|``np.hstack((arr1, arr2))``|stacks arrays horizontally, i.e., it combines arrays along columns|\n", "|``np.random.concatenate(((arr1, arr2)), axis)``|stacks arrays along any specified axis|" ] }, { "cell_type": "code", "execution_count": 23, "id": "eaac2893", "metadata": { "id": "EwIc7JWqfyTt" }, "outputs": [], "source": [ "arr1 = np.array([1, 2, 3, 4, 5, 6])\n", "arr2 = np.array([1, 2, 3])" ] }, { "cell_type": "code", "execution_count": 24, "id": "1cbab5b9", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "dHiiqpJffyKQ", "outputId": "2a30919d-7304-4bca-e40e-37ffb5d61779" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "reshaped: \n", " [[1 2 3]\n", " [4 5 6]]\n" ] } ], "source": [ "# reshape\n", "reshaped_arr = arr1.reshape(2, 3)\n", "print(\"reshaped: \\n\", reshaped_arr)" ] }, { "cell_type": "code", "execution_count": 25, "id": "53e3d1e0", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "6JWHK00Jfx8B", "outputId": "7fe66f67-e0b8-4c63-9716-b7431e5b1ee0" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "flattened: \n", " [1 2 3 4 5 6]\n" ] } ], "source": [ "# flatten\n", "flat_arr = reshaped_arr.flatten()\n", "print(\"flattened: \\n\", flat_arr)" ] }, { "cell_type": "code", "execution_count": 26, "id": "cbc89119", "metadata": { "id": "33xkn4m-f4Sk" }, "outputs": [], "source": [ "# stack\n", "arr3 = np.array([4, 5, 6])\n", "arr4 = np.array([7, 8, 9])" ] }, { "cell_type": "code", "execution_count": 27, "id": "9eb47c16", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "pRFdW9VOf7Ls", "outputId": "4e104a53-15f2-4148-f36a-b39b30509eb4" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "vstacked: \n", " [[4 5 6]\n", " [7 8 9]]\n" ] } ], "source": [ "# vertical stack\n", "vstacked = np.vstack((arr3, arr4))\n", "print(\"vstacked: \\n\", vstacked)" ] }, { "cell_type": "code", "execution_count": 28, "id": "8ff2bbb6", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "8ercGEaZf8w_", "outputId": "e72f932f-0ba1-4e31-f3f2-a4c7231ac409" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hstacked: \n", " [[4 5 6 4 5 6]\n", " [7 8 9 7 8 9]]\n" ] } ], "source": [ "# horizontal stack\n", "hstacked = np.hstack((vstacked, vstacked))\n", "print(\"hstacked: \\n\",hstacked)" ] }, { "cell_type": "code", "execution_count": 29, "id": "5c084c8d", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "W9Ra3FM6LRoG", "outputId": "2650a814-45a7-40d3-b1ea-792eaf1d399a" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "stacked: \n", " [1 2 3 4 5 6 1 2 3]\n" ] } ], "source": [ "# concatinate\n", "stacked = np.concatenate((arr1, arr2), axis=0)\n", "print(\"stacked: \\n\", stacked)" ] }, { "cell_type": "markdown", "id": "f5dde0e6", "metadata": { "id": "UMQEbQC_vgv3" }, "source": [ "## Copying Arrays\n", "\n", "To copy an array in another array you can use the `copied_arr = first_arr.copy()` function." ] }, { "cell_type": "code", "execution_count": 30, "id": "ffb2dd06", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "lOD4Qz5oui-D", "outputId": "88c60046-bebd-43a9-bbfc-77ec88000c9c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "arr1=\n", " [[0. 0.]\n", " [0. 0.]]\n", "arr2=\n", " [[4. 0.]\n", " [0. 0.]]\n" ] } ], "source": [ "arr1 = np.zeros((2,2));\n", "\n", "# using .copy()\n", "arr2 = arr1.copy()\n", "arr2[0,0] = 4\n", "print (\"arr1=\\n\",arr1)\n", "print (\"arr2=\\n\",arr2)" ] }, { "cell_type": "markdown", "id": "834e55db", "metadata": { "id": "h6-gVywBjiFl" }, "source": [ " **Attention:** Note that `second_arr=first_arr` is different from copying. This just returns **views** rather than **copies** of the array data. As a result any change to one array, `second_arr`, or `first_arr`, will be applied to both of them." ] }, { "cell_type": "code", "execution_count": 31, "id": "73490ae8", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "QqWuc-JOipAK", "outputId": "e5d89035-6d1a-4e4c-e2c3-bbd88cf99e3d" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "arr1=\n", " [[2. 0.]\n", " [0. 0.]]\n", "arr3=\n", " [[2. 0.]\n", " [0. 0.]]\n" ] } ], "source": [ "# using assignment operator\n", "arr3 = arr1\n", "arr3[0,0] = 2\n", "print (\"arr1=\\n\",arr1)\n", "print (\"arr3=\\n\",arr3)" ] }, { "cell_type": "markdown", "id": "68da22fe", "metadata": { "id": "BW1Gq4ZAk0JR" }, "source": [ "## Exercises" ] }, { "cell_type": "markdown", "id": "a272a1da", "metadata": { "id": "RAFb-4tFgPGg" }, "source": [ "### **Exercise: Recreating a matrix**\n", "\n", "You have just learned about several array creation functions in Section 10.5. Using `np.zeros` and `np.ones`, try to recreate the matrix below. You may also use the method of element replacement. Don't forget to print and check your progress in the intermediate steps to ensure you are on the right track." ] }, { "cell_type": "markdown", "id": "aaca071d", "metadata": { "id": "JQQgJilr-NIK" }, "source": [ "![matrix-1.png](../../images/matrix-1.png)" ] }, { "cell_type": "code", "execution_count": 32, "id": "d9ce9e06", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "OEOcG6DNhSfb", "outputId": "1c2d1c98-92fc-456d-c361-1c433a4d0723" }, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (2174539493.py, line 4)", "output_type": "error", "traceback": [ " \u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[32]\u001b[39m\u001b[32m, line 4\u001b[39m\n\u001b[31m \u001b[39m\u001b[31mmatrix = # your code here\u001b[39m\n ^\n\u001b[31mSyntaxError\u001b[39m\u001b[31m:\u001b[39m invalid syntax\n" ] } ], "source": [ "import numpy as np\n", "\n", "# Create a 5x5 matrix filled with zeros\n", "matrix = # your code here\n", "print(matrix)" ] }, { "cell_type": "code", "execution_count": null, "id": "ceee10c2", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "8gwe42orhSUl", "outputId": "1a2f82cd-a377-4070-8e6f-f4c4d46e5d56" }, "outputs": [], "source": [ "# Create a 3x3 matrix filled with ones\n", "inside = # your code here\n", "print(inside)" ] }, { "cell_type": "code", "execution_count": null, "id": "eb16bc4e", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "P_mkLvm_hSMo", "outputId": "ec390f13-059b-4b58-9c44-a76bebc1ddf3" }, "outputs": [], "source": [ "# Replace the element in the middle of the 3x3 matrix with 6\n", "inside[1, 1] = # your code here\n", "print(inside)" ] }, { "cell_type": "code", "execution_count": null, "id": "1f8da99d", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "uyCtNiblhR_3", "outputId": "ccb04368-d9c5-4e13-f8e2-750eeb4ad5d1" }, "outputs": [], "source": [ "# Fill the middle of the 5x5 matrix with the 3x3 matrix\n", "# your code here\n", "print(matrix)" ] }, { "cell_type": "code", "execution_count": null, "id": "a4ae841f", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Tnw5owrmDeA7", "outputId": "b2f95b19-3c7b-477c-cb5c-8b7338a208a8" }, "outputs": [], "source": [ "# Replace the last element of the final matrix with 2\n", "# your code here\n", "print(\"Final matrix:\")\n", "print(matrix)" ] }, { "cell_type": "markdown", "id": "ad5953b9", "metadata": { "id": "UbBUBhkgkWZT" }, "source": [ "____\n", "### **Optional Exercise: Matrix extraction**\n", "\n", "There is a matrix with three different parts marked in different colors. First, create the matrix as an array, and then write three separate codes to extract the values inside each colored box. The green and blue areas should be provided as matrices, while for the pink area, it is sufficient to print only the elements.\n", "\n", "💡Hint: You can use a for loop to find the elements inside the pink area." ] }, { "cell_type": "markdown", "id": "31070162", "metadata": { "id": "moaWS9GekYli" }, "source": [ "![matrix-2.png](../../images/matrix-2.png)" ] }, { "cell_type": "code", "execution_count": null, "id": "21397f1a", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "vVP0uo4ah3vs", "outputId": "97f6bbac-09b7-4834-f7f4-67723726335b" }, "outputs": [], "source": [ "import numpy as np\n", "\n", "# Create a list of numbers from 1 to 30 (including 30)\n", "list_matrix = # your code here\n", "\n", "# Convert the list into a numpy array\n", "matrix = # your code here\n", "\n", "# Reshape it as 6x5\n", "matrix = matrix.reshape(# your code here)\n", "print(\"Matrix: \\n\", matrix)" ] }, { "cell_type": "code", "execution_count": null, "id": "dd1b0e93", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "gDpF2PQjh3m9", "outputId": "8d6ec4b4-0410-45ef-fede-cccac970aaef" }, "outputs": [], "source": [ "# Green area\n", "green = # your code here\n", "print(\"Green area: \\n\", green)" ] }, { "cell_type": "code", "execution_count": null, "id": "e59af0c4", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "HThkX_oIh3VH", "outputId": "1ae10e32-54e1-4a88-b0d1-d615f1a0162d" }, "outputs": [], "source": [ "# Blue area\n", "blue = # your code here\n", "print(\"Blue area: \\n\", blue)" ] }, { "cell_type": "code", "execution_count": null, "id": "3192cf57", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "tDZ766aRG61Z", "outputId": "3d11174b-11ee-47e8-bf1d-af4db4e7563d" }, "outputs": [], "source": [ "# Pink area\n", "print(\"Pink area: \")\n", "for i in range(4):\n", " pink = # your code here\n", " print(pink)" ] }, { "cell_type": "markdown", "id": "956b17c7", "metadata": { "id": "f6MNydEjG2Md" }, "source": [ "____\n", "### **Exercise: Array manipulation**\n", "\n", "Your task is to complete the following steps:\n", "\n", "1. Create a list of numbers from 0 to 8 using the `range` function.\n", "2. Use the created list to create a 3x3 two-dimensional NumPy array by reshaping it.\n", "3. Replace all the diagonal values in the NumPy array with 0 using a single for loop.\n", "4. Add two columns filled with zeros to the matrix.\n", "5. Add one row filled with ones to the matrix. Hint: you can use `[1]*array_2d_0.shape[1]` (a row filled with 1) as the second argument for the vstack methode.\n", "\n", "💡Don't forget to print and check your progress in the intermediate steps to ensure you are on the right track." ] }, { "cell_type": "code", "execution_count": null, "id": "a44b4ffd", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "HCpe6tw3iS3o", "outputId": "b4017807-2aa6-49e3-c0a9-46234970bab3" }, "outputs": [], "source": [ "import numpy as np\n", "\n", "# 1- Create a list of numbers from 0 to 9 using the range function\n", "number_list = # your code here\n", "print(\"List: \\n\", number_list)" ] }, { "cell_type": "code", "execution_count": null, "id": "48c17666", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "MjrJ1RNMigk8", "outputId": "a69156aa-952d-4bc5-f356-9ae4d7d8746f" }, "outputs": [], "source": [ "# 2.1- Create a numpy array from the existing list\n", "array_2d = # your code here\n", "\n", "# 2.2- Reshape the array so it becomes 3x3\n", "array_2d = # your code here\n", "print(\"Reshaped: \\n\", array_2d)" ] }, { "cell_type": "code", "execution_count": null, "id": "bb36a46c", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "pRRg9L3SiWYH", "outputId": "2820118b-9b2f-4aa5-eb4e-a7079acf1cca" }, "outputs": [], "source": [ "# 3- Replace diagonal values with 0 using a single for loop\n", "for i in range(3):\n", " # your code here\n", "\n", "print(\"Diagonal: \\n\", array_2d)" ] }, { "cell_type": "code", "execution_count": null, "id": "6e3c6fe7", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "6IMF8uU1iYMJ", "outputId": "bb070451-cbda-4b2e-a75a-cae65f4e8a4c" }, "outputs": [], "source": [ "# 4- Add two columns filled with zeros to the matrix\n", "# 4.1 make an array of zeros with same number of rows and 2 columns\n", "zeros_column = # your code here\n", "\n", "# 2.2 concatenate the new matrix and the old one\n", "array_2d_0 = # your code here\n", "print(\"Extra columns: \\n\", array_2d_0)" ] }, { "cell_type": "code", "execution_count": null, "id": "10973a38", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "VIvnNzVtiYB-", "outputId": "21e33582-f208-48a5-88a3-ca2bb3216ee4" }, "outputs": [], "source": [ "# 5- Add one row filled with 1's to the matrix.\n", "# 5.1: make one row with same amount of columns as the current array\n", "ones_row = # your code here\n", "\n", "# 5.2: concatenate it with the old array\n", "array_2d_1 = # your code here\n", "\n", "# Print the resulting numpy array\n", "print(\"Modified 2D Numpy Array:\")\n", "print( array_2d_1)" ] }, { "cell_type": "markdown", "id": "5f635e10", "metadata": { "id": "p_dJPkaLYVW8" }, "source": [ "____\n", "### **Exercise: Array manipulation**\n", "\n", "Your objective is to perform a series of steps on matrices to explore matrix operations.\n", "\n", "1. Create a matrix A of size 3 by 5 and fill it with zero's.\n", "2. Create a new matrix B by selecting only the **even** columns of matrix A and a new matrix C by selecting the **odd** colums of matrix A.\n", "3. Perform following operations on B and C: `C = C+1`\n", "`B += 1`\n", "4. Print matrix A and examine the results.\n", "\n", "💡Don't forget to print and check your progress in the intermediate steps to ensure you are on the right track." ] }, { "cell_type": "code", "execution_count": null, "id": "0fdb9638", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "s1oRHc2nj2QX", "outputId": "c3cea317-625d-4c8c-e301-4dc81742d99e" }, "outputs": [], "source": [ "import numpy as np\n", "\n", "# Step 1: Create a 3x5 matrix A with zeros.\n", "A = # your code here\n", "print(\"Mtarix A_1: \\n\", A)" ] }, { "cell_type": "code", "execution_count": null, "id": "18ce474b", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "OYVQvx3Ij49r", "outputId": "862e2e63-03ed-4ac7-e960-5a4317660711" }, "outputs": [], "source": [ "# Step 2: Create matrix B using even columns of matrix A (column indexing starts from 0)\n", "B = # your code here\n", "print(\"Matrix B_1: \\n\", B)" ] }, { "cell_type": "code", "execution_count": null, "id": "cdc063d8", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "g4qVmvwMj8c6", "outputId": "0ebc2fd0-a050-45e5-affc-f3e90181b2f4" }, "outputs": [], "source": [ "# Create a matrix C using odd columns of matrix A\n", "C = # your code here\n", "print(\"Matrix C_1: \\n\", C)" ] }, { "cell_type": "code", "execution_count": null, "id": "18f4ce5b", "metadata": { "id": "AyVR9sy7j_kD" }, "outputs": [], "source": [ "# Step 3: Negate all values in matrix B\n", "C = C+1\n", "B += 1" ] }, { "cell_type": "code", "execution_count": null, "id": "8fc5ad52", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "3xUgp6s8YV9E", "outputId": "d8281445-3832-4068-bce4-d8e2157c1371" }, "outputs": [], "source": [ "# Step 4: Print matrices A and B\n", "print(\"Matrix A:\")\n", "print(A)\n", "\n", "print(\"Matrix B: \")\n", "print(B)" ] } ], "metadata": { "jupytext": { "text_representation": { "extension": ".md", "format_name": "myst", "format_version": 0.13, "jupytext_version": "1.16.4" } }, "kernelspec": { "display_name": "Python 3", "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.12.11" }, "source_map": [ 13, 19, 27, 33, 37, 48, 54, 69, 83, 89, 100, 111, 122, 126, 136, 152, 164, 176, 188, 194, 213, 239, 253, 264, 275, 286, 297, 308, 321, 333, 337, 356, 373, 395, 409, 416, 428, 440, 448, 460, 472, 484, 490, 506, 511, 525, 530, 537, 541, 555, 567, 579, 591, 604, 613, 617, 637, 649, 661, 675, 690, 705, 720, 734, 750, 769, 784, 798, 810, 822, 830 ] }, "nbformat": 4, "nbformat_minor": 5 }