Skip to main content

Section 2.4 Python recap

for loops. The for loop allows programmers to tell Python to repeat some set of instructions for a given number of times. The repeated instructions are all instructions that follow the for line and are indented.

Example 1: print the first 7 natural numbers (startin from 0!):

Example 2: print all natural numbers between 1 and 95 in increments of 19:

Arrays. When doing numerical computations, it is preferable to use NumPy's own arrays. There are several ways to accomplish this, two of which are shown in the example below. The instruction np.arange(k) generates an array (i.e. a vector, in more mathematical terms) of \(k\) elements, the first of which is 0 (so that the component of index \(k\) is equal to \(k-1\)). The instruction np.zeros(k) generates an array of \(k\) elements, each of which equal to zero. With a notation similar to MATLAB, it is possible to access a range of elements of an array x between indices \(i\) and \(j\) with the code x[i:j+1] (see the example below).

Below are examples to generate arrays of equally spaced points, which can be useful in many cases.

Remark: the syntax x=np.linspace(a,b,n) is equivalent to x=np.arange(a,b,(b-a)/(n-1)); usually when the emphasis is on the number of array elements between a and b one uses the first while when the emphasis is on the spacing between tweo consecutive elements of the array one uses the latter.

Multiplications, divisions and powers. All numerical variables in MATLAB are matrices. Single numbers are \(1\times1\) matrices. An array of \(k\) elements is a \(1\times k\) matrix. When we have two variables a and b and we write a*b (or a/b or a^b)

MATLAB interprets these operations as matricial operations. If a and b are numbers, namely \(1\times1\) matrices, this coincides with the usual product (or division or power) but when a and b are arrays MATLAB will give an error message since those operations are not defined on arrays.

In order to tell MATLAB to perform those operations componentwise we need to use, instead, the symbols a.*b, a./b and a.^b.
As a test, try removing the dot from i.*j in the code above and see what happens.

Plots. MATLAB is able to plot an array b versus an array a through the instruction plot.

If you do not want MATLAB to draw the lines connecting consecutive points, you need to use the scatter command:

This is also the way functions' graphs are visualized in MATLAB:

When plotting the graph of an exponential nature, it is often more useful to plot the log of the "y" with respect to the log of the "x", which is accomplished by the loglog function, whose syntax is the same of the plot one.

What is the slope of the line above?