Python prompt

In order to be immediately operative, we start to see the simplest of the programs we can write: that is, a simple sequence of commands.

The Python prompt will be of the type:

Python 3.3.2 (v3.3.2: d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AM
D64)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.

So let’s start working with the Python prompt, writing the individual commands directly, then print the programmer’s greeting on the screen:

>>> print (‘Hello world!’)
Hello World

How you can verify the print command does nothing but ask Python to show us on the video the string contained in the brackets. In our case it will write the sequence of characters ‘Hello world’.

python prompt

This sequence of characters is defined in the jargon of the character string programmers or simply string.

Python software

Let’s first see where to find the Python software to install on our machine in order to start programming with Python. The packages that we will have to install are available on the official website of the language at the following url:

Naturally, before downloading the software versions, we will have to inform ourselves about the type of machine at our disposal and the operating system installed on it. However, remember that Python is available for practically all operating systems in circulation.

The Python interpreter will allow the translation of our Python code into a language that our computer can understand and that will allow it to execute the instructions contained in it. In the writing period of this book, the current version of the Python interpretation is 3.1.2 which represents the stable one and that is why in the examples that will accompany us in the following chapters we will refer to that version.

We can safely download the Python software from the network, as the programming with Python is all open source and therefore freely downloadable from the internet where we can find sites that in addition to providing detailed procedures for downloading the current version of the software also provide satisfactory documentation.


R variables types

In this post we will deepen the concept of variables in the R environment by providing an explanation of the different types of variables. The R language provides two types of variables:

1) global variables;

2) local variables;

As you can guess, global variables are accessible globally within the program, local variables instead take on meaning only and exclusively in the sector of belonging, resulting only visible within the method in which they are initialized.

For most compilers, a variable name can contain up to thirty-one characters, so that a sufficiently descriptive name can be used for a variable, in R this limit is not indicated. The choice of the name takes on fundamental importance in order to make the code readable; this is because a readable code will be easily maintained even by people other than the programmer who created it.

We have talked about initialization of the variable as an operation to create the variable; let’s see then a trivial example:

> a <- 1

In this instruction the assignment operator (<-) was used, with the meaning of assigning precisely to the memory location identified by the name to the value 1. The type assigned to the variable is established during the initialization phase; it will then be decided whether to assign to it a text string, a Boolean value (true / false), a decimal number etc.

Variables and expressions in R

Variables and expressions in R are treated in a modern and efficient way, in fact while in most programming languages ​​a declaration of the variables used in the program is required, declaration made in the initial part before the executive section of the same, in R all this is not required. Because language does not require the declaration of variables; the type and its size will be decided when they are initialized.

The term variable refers to a type of data whose value is variable during the execution of the program. However, it is possible to assign an initial value to it, so we will talk about initializing the variable. The initialization phase assumes a fundamental importance because it represents the moment in which the variable is created, this moment coincides with that in which a given value is associated with it.

Unlike the so-called compilation languages, this procedure can be inserted anywhere in the script, even if the meanings can take different values.

When the interpreter encounters a variable, it deposits the relative value in a memory location and whenever a call to that variable appears in the program, it will refer to this location. It is a good planning rule to use names that will allow us to refer unambiguously to specific memory locations where the relevant data has been stored.

R names

In this post (The names in R) we analyze the rules to follow to correctly choose the names of constants, variables, methods, classes and modules, which represent the essential elements with which we will work in this environment.

A name in R can then consist of a capital letter, a lowercase letter or a symbol. (dot), which in turn can be any combination of uppercase and lowercase letters, and figures. The lower case characters correspond to the lowercase letters of the alphabet from a to z, while uppercase characters correspond to the uppercase letters of the alphabet from A to Z and the digits from 0 to 9. The number of characters that make up the name is not limited.

Here are some suggestions given in the guide to R provided by Google, on how to correctly name the objects (names in R):

Never use underscores (_) or dashes (-) to identify an object in the R environment.
The identifiers must be named according to the following conventions.
The preferred form for variable names is to use all lowercase letters and words must be separated by dots (, but the identifier in the variableValue form is also accepted.
Function names have an initial capital letter and no point (FunctionName) should be used.
The constants are identified in the same way as the functions, but with an initial k.

Code indentation in R

Even if the structure of the R language foresees particular delimiters for some program blocks, it is still useful, the indentation of the code in R, for the relative identification.

In this regard, it should be recalled that the code indentation refers to the technique used in programming through which program blocks are highlighted by inserting a certain amount of empty space at the beginning of a line of text, with the aim of increasing readability.

Although, as already mentioned, R provides appropriate delimiters for some language structures, we will use the same indentation to indicate the nested blocks; in this regard it is possible to use both a tabulation and an arbitrary number of white spaces.

In using this technique it is necessary to remember simple recommendations:

  • the number of spaces to use is variable;
  • all instructions in the program block must have the same number of indentation spaces.

In this context we will use the convention that provides for the exclusive use of two spaces o identify a new block and to leave out the use of the tab.

Operations in Matlab

The following arithmetic operations are defined in MATLAB:

1) addition +
2) subtraction –
3) multiplication *
4) division /
5) elevation to power

When the expression to be evaluated is too long to fit on a single command line, it is possible to use a continuation character given by. . . (three points). Eg:

>> 1 + 1/4 + …

ans =


It is possible to verify that since in MATLAB there is no distinction between whole, real or complex variables, the result of the operation of elevation to power in the case of fractional exponents may not correspond to that naturally expected. For example, if you want to calculate the cubic root of -5, you get:

>> (-9) ^ (1/5)

ans =

1.2555 + 0.9122i

then an imaginary number instead of a real number. The problem is due to the fact that MATLAB, working in complex notation, calculates as the first cubic root of -9 one of the two with non-imaginary imaginary part.

Operations in Matlab

Also in MATLAB it is possible to alter the classical precedences of the arithmetic operations through the appropriate use of the round brackets. For example, if in the previous case we had written (- 9) * 1/5 we would have obtained the value -1.8000 that is, correctly, – 9/5.

>> (- 9) * 1/5

ans =


As far as the vectors are concerned, elementary operations extend (when well defined) in a completely natural way, with the exception of division and power-up operations. Eg,

>> a = [1: 4];
>> b = [1: 3];
>> c = [3 2 6 -1];

>> a + c (sum of row carriers)

ans =

4 4 9 3

>> a-c (line array difference)

ans =

-2 0 -3 5

>> a + b
??? Error using ==> plus
Matrix dimensions must agree.

>> a * c
??? Error using ==> mtimes
Inner matrix dimensions must agree.

The last instructions show us that the operations between vectors are valid only if the dimensions are consistent. In fact, given a line vector s of dimension n (ie a matrix 1 * n) and a vector column d of size m, we can execute the scalar product s * d only if m = n (obtaining in this case a scalar).

>> s = [1: 4];

>> d = [1; 2; 3; 4];

>> s * d

ans =

So d * s will provide a m * n matrix.

>> s = [1: 4];

>> d = [1; 2; 3; 4];

>> M = d * s

M =

1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16

Colon operator in Matlab

Colon operator (:) is one of the most important MATLAB operators. It is found in many different forms. For example, the following expression:


represents a row vector that contains integers from 1 to 10

1 2 3 4 5 6 7 8 9 10

To obtain a specific sequence instead, an increase must be indicated. For example:

>> 100: -7: 50

ans =

100 93 86 79 72 65 58 51

that is, a sequence of numbers from 100 to 50 with a step equal to -7; while

>> 0: pi / 4: pi

ans =

0 0.7854 1.5708 2.3562 3.1416

Colon operator in Matlab

The subscribed expressions involving the operator two points assign portions of a matrix. For example, we assign the usual matrix:

A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]

and let’s extract some values:

A (1: k, j)

represents the first k elements of the jth column of A. Then we extract some elements:

>> A (1: 4.4)

ans =


and we calculate the sum of the fourth column.

>> sum (A (1: 4.4))

ans =


The colon assigns all the elements in a row or column of a matrix and the keyword END assigns the last row or column. So

>> sum (A (:, end))

ans =


calculates the sum of the elements in the last column of A.

Access to elements of an array in Matlab

In this post, we see how to access the elements of an array in the Matlab environment; first of all, then insert a sample matrix in the Matlab workspace:

>> A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]

A =

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

The element in line i and column j of A is denoted with the symbol A (i, j). Eg:

>> A (4.2)

ans =


is the number in the fourth row and second column. For our matrix it corresponds to 14. Thus it is possible to calculate the sum of the elements in the fourth column of A by typing:

A (1,4) + A (2,4) + A (3,4) + A (4,4)

This produces:

>> A (1,4) + A (2,4) + A (3,4) + A (4,4)

ans =


but it is not the most elegant way to add a single column. It is also possible to access the elements of a matrix using a single subscript, A (k). This is the usual way to access the elements of row vectors and column vectors.

Access to elements of an array in Matlab

But it can also be applied to a two-dimensional array in this case the matrix is ​​considered as a column vector, formed by the columns of the original matrix. Thus, for our matrix, A (8) is another way of identifying the value 14 stored in position A (4.2), ie fourth row second column.

>> A (8)

ans =


If you try to access the elements of an array outside it, you make a mistake:

>> t = A (4,5)
??? Attempted to access A (4.5); index out of bounds because size (A) = [4.4].

(Error message)

On the other hand, if we store a new value in an element of the matrix that exceeds its order, there is an increase in order to accommodate the newcomer:

>> A (4.5) = 17

A =

1 2 3 4 0
5 6 7 8 0
9 10 11 12 0
13 14 15 16 17

The carriers are treated in Matlab in a completely similar way. You can view the individual entries of a vector, after having defined it as follows:

V = [2 1 3 4];

to view the first item, simply type:

>> V (1)
ans =

This command prints the first element in the vector. Also note that a new variable called ans was created.

How to enter matrices in Matlab

You can enter MATLAB matrices in many different ways.

  • introduce an explicit list of elements.
  • load arrays from external data files.
  • generate arrays using the built-in function.
  • create matrices with their own functions in M-files.

Let’s start by showing how to register the matrix as a list of its elements. In this regard, only some basic conventions are followed:

  • Separate the elements of a row with blanks or commas.
  • Use a semicolon “;” to indicate the end of each row.
  • Enclose the entire list of items with square brackets, [].

How to enter matrices in Matlab

To enter the Durer matrix, simply type:

A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]

MATLAB exposes only the typed matrix to video,

A = 16 3 2 13
    5 10 11 8
    9  6 7 12
    4 15 14 1

This procedure precisely associates numbers with portions of memory. Once the matrix is supplied, it is automatically registered in the MATLAB workspace. Now you can indicate it simply by typing the letter A. at the Matlab prompt.

>> A

A =

     16 3 2 13
      5 10 11 8
      9 6 7 12
      4 15 14 1