Matlab course - current version
Day 1: Introduction to programming and using Matlab
Status: 21 August 2016
There are three versions of this script, which do not differ in content. The html version is practical in that it contains links, e.g. for downloading files. The pdf version is best suited for printing, and you can insert notes directly into the Word version to create your own personalised script. It is a matter of taste which version you prefer.
Several days will remain unchanged from the 2014 or 2015 version, I don't change the pages there.
Command reference: Matlab syntax
pdf version of the script: [Tag01.pdf]
Word version of the script: [Tag01.docx]
HTML version:
0) Preparation: Registration with the cloudstorage system of the University of Oldenburg
In this course, we will endeavour to provide you with daily re-registering students for at least one task you have programmed. In order to make your solutions available to us, I would like to ask you to register for this course with the university's cloud storage system. This service is available at
cloudstorage.uni-oldenburg.de/
Further information on the university cloud system can be found at
uol.de/itdienste/services/datenhaltung/cloudstorage/
You have to log in there once with your university account and password so that your email address is available for me to share my folders with you.
Once I have set up the folders, you should find two new folders on your cloud page:
- Matlab2016 The general course folder that all course participants can read. Here you will find files to download for each day of the course, as well as sample solutions to the exercises the next day. Only the tutors and I have write access to this folder.
- Lastname_Firstname_Matlab2016 (e.g. Mueller_Lieschen_Matlab2016) Your personal folder to which ONLY you, the two tutors and I have access. Please copy your solutions there. We will also save the programmes we have commented on there.
Notes on using the cloud system:
- As soon as you log in to the university cloud system, your email address (as in Stud.IP) will also be visible to other users of the university cloud system. You can then, for example, share folders with other students and exchange data. If you do not want your email address to be permanently visible, you can unsubscribe from the service at the end of the course.
- My tutors and I ONLY share these two folders with you. We can NOT see what you store in other folders on the cloudstorage.
- I will delete the course folders some time after the end of the course. So please do not use them to store data permanently.
- If you wish, you can set up a client on your private computer to use the cloud system for data storage. For this course, however, it is completely sufficient if you usethe web interface cloudstorage.uni-oldenburg.de to copy your finished, previously locally saved programmes to it.
Please:
- Name your files stored on the cloudstorage system uniquely for us by combining the file name with the task number and your name, e.g. T1H1_Sonja.m (We automatically search for the solutions to a task using a script. We cannot find solutions with different names).
- We save corrected / commented solutions under a different name in your personal folder.
A) THE MATLAB INTERFACE AND MATLAB AS A CALCULATOR:
Matlab is a programming environment that is frequently used in the scientific field. In this course, we will only utilise a small part of the possibilities of Matlab. In the first step, we will familiarise ourselves with the Matlab interface. (The following description refers to Matlab2016a on a Mac, other versions may look slightly different and you can customise the interface according to your own preferences).
User interface:
The most important window is the large "Command window". The cursor >> indicates that Matlab is ready to accept commands that can be typed in here. If Matlab is currently busy processing a programme, no cursor is displayed and "busy" is shown in the bar at the bottom. The command window has some practical features to make typing easier:
- To repeat command lines that you have already used, you can use the "up arrow" button in the Command window. This displays the last lines in succession when pressed several times.
- If you touch the beginning of a previously used line and press the "Up arrow" button, the last lines that occurred with this beginning are added.
- The command window can also add commands that have not yet been used in a Matlab session. If you type the beginning of a word and then press the "Tab" key, a list of possible additions appears.
At the bottom left is a small window with the name "Workspace". The workspace is the entirety of all currently defined variables. These are displayed as a list in the window. A variable is a name that designates a specific content. For example, you can continue working with a after defining a=1. Its content can be used for calculations (e.g. b=3*a) or changed (e.g. a=a+1).
- Double-clicking on a variable in the workspace window automatically opens the Variable Editor, which displays the content of the variable as a table.
The "Current Folder" window is located above this; it displays all files in the current directory. This can be changed using the small pull-down menu at the top. (We will deal with the topic of saving and loading tomorrow).
There are also two bars at the top. Explaining all the functionalities would go beyond the scope of this course, but both bars are partially self-explanatory. Two particularly important functions are
- The help window, symbolised by the question mark.
- The text editor for writing and saving programs, symbolised by the blank page on the far left.
Help:
Help is an html-based browser for searching and displaying Matlab commands. If you have installed toolboxes (which is always the case with the university licence), these are also automatically explained in the help. In addition to explanations of the individual functions (which you can find via the keyword search), there are also tutorials (for independent learning of Matlab and/or special concepts), examples, films, release notes (notes on different Matlab versions) and much more - it's worth clicking through!
Syntax basics:
- Variable: A variable is defined with the syntax Name=Value. The equals sign therefore means "set equal" and the order is decisive (name on the left, value on the right).
- Decimal numbers: Matlab is an American programme. Decimal places are separated with . and not with , as in German. e.g. u=8.765 (NOT u=8,765).
- Screen output: Normally, the result of each calculation step is displayed on the screen. If you want to suppress this screen output, write a semicolon after the command, e.g. a=75;
- Long lines: If a programme line is very long so that it can no longer be read properly, you can interrupt the command with ... and continue on the next line.
Tasks:
T1A1) Start Matlab and familiarise yourself with the different windows. Start the help. What options does it offer?
T1A2) Use the Matlab command window as a calculator.
- Try out the basic arithmetic operations, e.g. 7.32*674.986 or 100086+654.965-83.7 (each completed with Return).
- How does the answer to the input of 5*10+2 differ from 5*(10+2) and (5*10)+2?
- Attention: Remember the American notation with a full stop instead of a comma!
T1A3) When you have done some calculations, type in ans.
- How does Matlab react? Why?
- How does Matlab react to ans*2?
- What happens if you repeat ans*2 several times in a row? (You can use the up arrow key to do this.)
T1A4) Introduce a variable a with a=4.
- Observe the reactions in the different windows.
- Now type in b=10; . How do the outputs differ?
- How does Matlab react to the input a+b?
- How do the reactions to c=a+b; differ?
T1A5) Variables can be introduced and assigned values by the user as desired. However, there are also constants that are predefined in Matlab, for example pi. Have the value output.
T1A6) In addition to the basic arithmetic operations, Matlab also recognises more complex mathematical operations. Test 2^3 and b^4. What does this tick mean?
T1A7) Another example is the square root - but as there is no symbol for this on the keyboard, it is called up in the form of the sqrt function. The argument, the number to which the function is to be applied, must be written in brackets after the function name: sqrt(16) or d=sqrt(a). Other functions are e.g. sin, cos, exp, log, abs. What could these names mean? Try out your guess with examples.
T1A8) To check whether you have guessed correctly, look up the function names in the help.
- You will get a very short description if you type in help sin , for example.
- Much more information is available in the help window: search for sin and the other function names.
T1A9) Some mathematical operations require several arguments. With b/a, for example, this seems quite natural to us. If there is no abbreviated notation, as with the basic arithmetic operations, Matlab functions are passed all arguments separated by commas in the parenthesis that follows the function name. For example, the remainder of an integer division is calculated by the functionrem (remainder), which is given two arguments, e.g. rem(104, 10). The order of the arguments is important here: what happens if you enter rem(10, 104)?
T1A10) Perhaps you have already mistyped at some point during the exercise. What happened then? If nothing like this has happened to you yet, type in e1=sin(2*pi), thene2=sine(2*pi) and finally e3=sin(2pi). How does Matlab react in each case? How does the reaction differ if you type in f=10/0?
T1A11) Although your programmes are still very short today, this will soon change. That is why we are already starting to save programmes (i.e. sequences of commands) today. (We will discuss the theoretical background to this tomorrow):
- Before you start saving files, define a location where you will sort all the files in the course. First create a new folder "matlabkurs" (or whatever name you like) in your "My Documents" directory. Change to this folder in Matlab by clicking on the icon ... icon next to the "Current Folder" display.
- In future, every time you restart Matlab, make sure that you are in the correct folder.
- Open the Matlab editor by clicking on the icon for a new document. And type in there:
- a=5.5
b=0.75
c=a*b - Save this programme as test1.m (under File->save as). Make sure that you are in the correct directory. Call your first programme in the command window by typing test1.
- If you wish, you can already save your programmes today as a mental aid. The file must have the extension .m. To call up the programme in the command window, this extension is omitted and only the rest of the file name is used. Starting with today's homework, you should solve ALL tasks with the help of saved scripts and functions.
B) VECTORS AND MATRICES:
Vectors and matrices are the most important programming concept in Matlab. Almost all data is organised and processed in matrices. If you are not already familiar with matrix calculation, please read the short introduction from the book "Matlab und Mathematik kompetent Einsetzen" by S. Adam (download in Stud.IP) before the course.
Matrices are compound variables that combine related data in one object by arranging them in a rectangular scheme of rows and columns. Vectors are special matrices that consist of either only one row or only one column (row vector or column vector). The individual entries in vectors and matrices are referred to as elements of the matrix or vector.
Some calculation rules for dealing with vectors and matrices:
- Addition and subtraction only work for vectors and matrices of the same size (i.e. with the same number of rows and columns). You add or subtract the elements with the same indices.
- When multiplying a scalar value by a matrix (or a vector), each element is multiplied individually by the scalar.
- The multiplication of matrices is mathematically defined in a somewhat more complicated way (please take a look at the text on matrix calculation in Stud.IP), but is not used very often in biology. Point-wise multiplication, in which the elements of matrices (or vectors) of the same size that have the same indices are multiplied together, plays a more important role.
- When transposing, row indices and column indices are swapped with each other. This turns a column vector into a row vector and vice versa. A matrix is mirrored at the main diagonal.
- The Euclidean distance between points A and B in space is defined as:

e.g. in three-dimensional space for A=(a₁,a₂,a₃) and B=(b₁,b₂,b₃):
![]()
Matlab syntax:
- The values of the elements of vectors or matrices are specified in Matlab enclosed in square brackets , e.g. v=[1 2 3].
- Elements are separated within the square brackets:
-
- Within a line, elements are separated from each other by spaces or commas, e.g. v=[1 2 3] is equivalent to v=[1, 2, 3].
- Columns are separated by semicolons, e.g. s=[7;0.4;-3]. A matrix is defined e.g. by M=[1 0; -3 7].
- Indices are given in round brackets, e.g.
-
- v(2) is the second element of the vector v.
- s(1)=5 assigns the first element of s the value 5 to the first element of s.
- k=s(1) assigns the variable k the value of the first element of s .
- For matrices, the indices within the round brackets are separated by commas, e.g.
-
- M(2,1)=77 assigns the element in the second row and first column of the matrix M the value 77.
- new=M(2,2) transfers the value of the element in the second row and second column of the matrix M to the variable new.
- The colon is used in Matlab to generate number sequences. This is particularly important when counting and indexing.
Tasks:
T1B1) First calculate by hand: a=[1; 2] (column vector), b=[1 2] (row vector). What is c=a*b? Multiply the result c by the matrix d=[0 1; 0.1 10]. Then check your results with Matlab.
T1B2) Define the following vectors: a=[1 2 3]; b=[0.1 0.2 0.3]; c=[10; 20; 30]; d=[100; 200]; e=[-1; -2] and f=7.5. Which vectors are column vectors and which are row vectors?
Think about it and try it out: Which of the vectors can be added? Subtract? Multiply? Multiply point by point?
In which cases is the order of the vectors important, and in which cases is it not?
T1B3) If you realise that you would like to define a vector g whose values are the sum of the elements of a and c, you will have to play a little trick: one of the vectors must be transposed. Try it out: g1=a+c' and g2=a'+c. What is the difference?
T1B4) Matlab provides a pair of very practical functions for dealing with vectors. Try out how the following commands work using a few examples and, if in doubt, refer to the help:
sum(vector), mean(vector)
*) Try out which of the functions introduced in A7) also work for vectors.
T1B5) Define two matrices: M1=[1 1 1; 5 6 7] and M2=[0 -1; -2 0.5; 0.1 1] and look at them in the array editor. Which indices does the entry 6 in M1 have? Select an entry from M2, e.g. M2(1,2).
T1B6) Attention! Matlab recognises two ways of indexing a matrix component:
- Either you use the notation M1(1,2) with (row, column) in the brackets,
- or you count through the matrix as a long vector, whereby the columns are appended to a long column vector, e.g. M1(2).
- Which single index corresponds to M1(1,2)?
T1B7) Calculate M1*M2 and M2*M1. Transpose M2 and calculate the sum with M1.
* T1B8) Which of the vectors from exercise B2 can be multiplied by M1 or M2? Can they also be added?
T1B9) Fortunately, you don't need to type in large matrices completely in Matlab. Try out what happens if you enter o=ones(1,8) and z=zeros(3,3).
T1B10) Square brackets enclose all components of a matrix or vector. They can therefore also be used to combine vectors or matrices. Consider what the following expressions should return based on the vectors and matrices defined above and try out your hypotheses:
t1=[a b], t2=[a;b], t3=[a b f], t4=[d e], t5=[d;e], t6=[a c],
t7=[M1; a], t8=[M1; M2'], t9=[M1' M2]; t10=[[pi pi/2];[1 2];e']
T1B11) The colon operator plays an important role in Matlab. In its simplest form, it is used for counting: numbers=1:10 creates a vector with the numbers from 1 to 10.
T1B12) "Counting" is not only possible in steps of length 1. The step size is specified between the start and end value enclosed in colons.
- Try it out: number2= 10:10:100, number3=0:0.1:0.5.
- Create a vector that runs from the start value 5 with a step length of 2.5 to the end value 20.
T1B13) The colon operator is particularly important for indexing, i.e. for accessing defined elements of vectors or matrices.
- Which values result in numbers(2:4)?
- What could you write as an alternative to access these values?
- Access the 4th to 7th element from the vector numbers2 vector.
T1B14) If the colon operator stands alone when indexing, e.g. numbers(:), it means that the whole vector should be taken. This is quite boring for vectors, because in this case you could simply write numbers.
It is different with matrices.
- Define M3=[1 1 1 1; 5 6 7 8; 10 20 30 40].
- Try it out: M3(1,:), M3(:,3).
- What does M3(:) mean in contrast to M3 and to M3(:,:)?
T1B15) And now we combine what we have learnt: Pick out the third and fourth entry of the second line from M3.
T1B16) A very practical simplification when indexing is the term end. For example, the expression a(7:end) denotes everything from the seventh to the last entry of the vector a. This means that you do not need to know the length of the vector. Remove the last three elements from the vector numbers by using end.
T1B17) Your variables are still so small that they are displayed completely in the workspace window. However, this will soon change. To view the values of variables, there is the Variable Editor. It opens automatically when you double-click on one of the variables in the workspace window. This editor displays the values of the variable in a table. You can also change them here by typing - but you should be very careful with this, as these actions can no longer be traced later and, in particular, cannot be repeated automatically.
T1B18) For many applications, you need to know the size of matrices or vectors stored in variables.
- For a vector v is s=length(v) is the length of the vector.
- For matrices, it is advisable to use the command size command:
- rows=size(M3,1); % saves the number of rows (i.e. the length of the 1st dimension) in the variable rows
- columns=size(M3,2); % saves the number of columns (i.e. the length of the 2nd dimension) in the variable columns
- size=size(M3); % creates a vector sizewhose first value is the number of rows and whose second value is the number of columns.
C) GRAPHICAL REPRESENTATION OF VECTORS:
The graphical representation of data is extremely important for many applications, especially in the scientific field. Once you have "seen" data, it is easier to visualise it than if it is available in the form of vectors. This is why, for example, graphical representations of the results of analyses are always required in practical training reports, theses, etc. Matlab makes it very easy to visualise data arranged in vectors or matrices. The basic command for this is plot.
T1C1) Now we will plot a vector: Define the vector v=[1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 0 0 0 0 0 1.5 1.5 1.5 1.5 1.5]. Plot this data graphically using plot(v). What is shown on the x-axis and the y-axis?
T1C2) Using the colon operator, create a vector with a series of numbers, e.g.v=0.01:0.01:10; and plot it using plot(v). Try out different number series. What happens to the axes?
*T1C3) Create a matrix M consisting of several different number series and plot it with plot(M).
- What can you see?
- How can you plot a single row of the matrix?
- How a column?
T1C4) So far, the values have been plotted against the index of the vectors or matrix. This does not always make sense.
- Generate two vectors x=-1:0.1:1; and y=x.^2;
- with plot(x,y) the values are plotted against each other.
- What happens with plot(y,x)?
- Generate parabolas for different vectors x.
T1C5) How do you plot a single point on a graph? Plot the point P=[4.5 3].
T1C6) The axis([xmin xmax ymin ymax]) command can be used to view only a section of the available data or to scale data in figures (e.g. to make the representation of a single point meaningful).
- Try out different axis scalings for your curves.
- Also create a parabola with a larger definition range, e.g. from -10 to 10, plot it and look at it with different scalings.
- How do you get a plot that looks exactly like the original one in T1C4?
T1C7) There are a number of options to plot data as nicely or practically as possible.
- Try plot(y,x,'r') and try it out.
- What do the following options do? r, b, g, k, c, m, *, ^, s, d, :, -, --
- Make a note of the respective meaning and try out sensible combinations, e.g.plot(y,x,'r^:')
T1C8) There are several ways of plotting more than one vector at a time. Define two vectors v1=-3:6 and v2=[5 5 5 5 0 0 0 4 4 4] and an x-vectorx=1:10 against which you plot the vectors. Try it out (you can type out the lines or copy them into the command window, or copy everything together into the editor and save it as a programme):
% Display one vector at a time:
plot(x,v1)
hold on
plot(x,v2)
hold off
% Open a new graph window
figure
% Display both vectors simultaneously:
plot(x,v1,x,v2)
Are there any differences between the two figures?
D) HOMEWORK:
Command reference: Matlab syntax
The problems with red ormarked numbers will be discussed the next day. We comment on solutions to problems with red numbers, problems with * and problems with **.
- Please save your solution in your folder on the cloudstorage system.
- Please choose a file name that first contains the task number and then your own name (e.g. T1H1_Sonja.m). We search for the solutions automatically with a script - it will only find your solution if the task number is included in the name. Your own name must be included so that we can assign the file to you again after the correction. Otherwise it could happen that different people choose the same name and we overwrite each other's files when downloading.
- Please sort your files in your cloud folder sensibly, preferably by course day, so that we can find the respective tasks with as little effort as possible.
T1H1 ) As a primary school pupil, the mathematician Karl Friedrich Gauss was asked to add up all the numbers from 1 to 100. He was finished within a few minutes, as he recognised the principle that every sum of a number from the upper half of the series with a matching number from the lower half gave the value 101 (e.g. 1+100=101, 2+99=101 etc). Since there are 50 such pairs, the solution is 5050=101*50.
- The general formula for the sum of a series of natural numbers from a to b is s=1/2*(a+b)*(b-a+1).
- Test this formula by generating different series with the command r=a:b and calculating their sum with sum(r)and using the formula above.
T1H2) Create a matrix with a multiplication table for the small multiplication table, i.e.
| 1 | 2 | 3 | ... | 10 | |||||
| 2 | 4 | 6 | ... | ||||||
| 3 | 6 | 9 | ... | ||||||
| 4 | 8 | 12 | ... | ||||||
| ... | ... | ... | |||||||
| 10 | 20 | 30 | 100 |
(completely filled in, of course).
T1H3) Use the principle of defining matrices as components of matrices to create an 8*8 chessboard of 0 and 1.
- View your result in the Array Editor.
- You can also display the contents of a matrix graphically. If your matrix variable is called "chess", simply type in imagesc(chess).
T1H4 ) Which sequence of Matlab commands generates the content (without labelling) of the following table of height differences?
| km | Duforspitze | Matterhorn | Gornergrat | Zermatt | Brig |
| Duforspitze | 0 | -156 | -814 | -3014 | -3956 |
| Matterhorn | 156 | 0 | -658 | -2858 | -3800 |
| Gornergrat | 814 | 658 | 0 | -2200 | -3142 |
| Zermatt | 3014 | 2858 | 2200 | 0 | -942 |
| Brig | 3956 | 3800 | 3142 | 942 | 0 |
from the vector of height values v=[4634; 4478; 3820; 1620; 678]?
*T1H5) The two points A=[1,5] and B=[3,1] are given. Plot them in a coordinate system in which both axes cover the range from 0 to 10 using different symbols. Also draw the distance between the two points in a different colour.
*T1H6) If you want graphics that are even more attractive than the graphics options mentioned in T1_C7, you can use so-called "line properties". These are passed to the plot function as a key term and value, e.g. plot(x,y,'LineWidth',5).
- Other line properties are 'Colour', 'MarkerFaceColor', 'MarkerEdgeColor'and'MarkerSize'. What do these mean?
- Display your curve with a thick red line and blue triangles as data points.
*T1H7) Play a little with the interactive options to change your graph: zoom in on a certain area, change the line thickness, give the graph a title, etc. What options are there for interactively embellishing the graphic?
*T1H8) To further familiarise yourself with the use of vectors and matrices in Matlab, take a look at the following two scripts from another course: