Skip to main content

Section 2.4 Octave/MATLAB recap

for loops. The for loop allows programmers to tell MATLAB to repeat some set of instructions for a given number of times. The repeated instructions are all instructions between the for line and a corresponding end line. In the example below, we use a for loop to print the square roots of all integers from 1 to 16:

Arrays. The syntax 1:16 in the code above denotes an array (i.e. a vector, in more mathematical terms) of 16 elements, each of which equal to his position (namely the component of index \(k\) is equal to \(k\)). You can use a similar notation to extract some set of components from a vector namely, given the vector i=1:16, the syntax i(4:8) gives an array of 5 elements containing all components of i from 4 to 8.

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

Remark: the syntax i=linspace(a,b,n) is equivalent to i=a:(b-1)/n:b; 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. The default values are 100 points for the first and a distance of 1 for the second.
BEWARE: unlike almost all other programming languages around, in MATLAB vector (and matrices) indices start from 1, not from 0. Hence the following code gives an error:

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?