Day 04

Loops

Status: 25.9.2014

24.08.2016: The .pdf file of the script has been updated. Please use the new version.

Command reference: Matlab syntax

pdf version of the script: [Tag04.pdf]

Word version of the script: [Tag04.docx]

Downloads:

T4A1: [guesses.m]

**T4H7: [vogelfang.m]

HTML version:

A) WHILE LOOPS

Loops are a programming concept with which a sequence of commands can be repeated several times depending on a criterion.
In this respect, there is a strong similarity to case distinctions(if queries): the commands are only executed if a criterion is fulfilled.
In contrast to case distinctions, however, this execution does not normally only take place once with loops, but is repeated until the condition is no longer fulfilled. (In a cooking recipe, this is the difference between "add sugar or salt according to taste" and "stir until all the lumps have dissolved").

The general syntax of a while loop (i.e. a loop whose commands are executed again and again until a condition is no longer fulfilled) is as follows

  • Initialisation Test variable
  • while condition
    • Commands
    • Changing the test variable
  • end

It is important to note that

  • The condition must depend on (at least) one test variable
  • This test variable must be assigned a value before the loop begins
  • The value of this variable must be able to change within the loop
  • Attention! If the condition always remains true, the loop is executed an infinite number of times. This results in a so-called infinite loop.
  • Infinite loops (or other programmes that take too long) can be aborted in Matlab with ctrl-c .

T4A1) An example of a while loop could be the following programme (Download: [guesses.m])

function number=guesses
% function number=guesses
% The computer randomly selects an integer between 1 and 20. The
% user tries to guess it.
% Return value:
% number is the number of attempts required by the user.

secret=ceil(rand*20); % Random integer between 1 and 20
guessed=false; % Initialise test variable
number=0; % Initialise number of attempts with 0

while guessed==false % As long as the number is not guessed
user_guess=input('Please enter an integer between 1 and 20:'); %read in a new number from the user
number=number+1; % increment counter

if user_guess==secret % If the user has guessed the number
guessed=true; % update test variable accordingly
end
end
disp(['You have used ',num2str(number),' trials', number])
;

  • Try out the programme.
  • Follow the debugging-mode to see how the variables change while the programme is running.
  • Extend it so that the user is warned if he makes a nonsensical input.

T4A2) Why does the following loop go wrong?

a=1; b=10;
while a<b
b=2*b
end
sprintf('a=%g, b=%g',a,b)

(Remember ctrl-c when you try this loop...)

T4A3) Write a function that takes a number as an input argument and outputs random numbers to the screen until the random number drawn is greater than the number passed to the function by the user.

  • Use the function rand(1)function to generate a random number between 0 and 1.
  • Remember to make a query as to whether the user's input is meaningful.

B) FOR-LOOP

In principle, while loops are sufficient for all applications. However, you often know from the outset how many steps need to be completed. In these cases, it is more practical to use a counting loop. This is started in Matlab by the keyword for and usually uses the colon operator to define the number range to be considered.

The general syntax of a for loop is

  • for counter=initial value:increment:final value
    • commands
  • end

There are a few rules for the variable that is used as a counter in the for loop:

  • The counter can be used within the loop (this is actually very often the case).
  • However, the value of the counter may not be changed within the loop.
  • In principle, any vectors can be used for the counter, in particular vectors generated by the colon with a different increment (e.g. a=7:0.1:8) or vectors whose elements are explicitly specified (e.g. value=[0 1 2 4 8])

Nested for loops are often used, e.g. to process each element of a matrix M individually. Such programmes usually look like this:

  • Initialise M
  • [rows,columns]=size(M)
  • for z=1:rows
    • for s=1:columns
      • commands
    • end
  • end

T4B1) Try the following programme:

current=1;
for z=1:1:10
current=current*z;
sprintf('current value: %i ',current)
end

  • What does this programme calculate?
  • Follow the debugging-mode to see how the variables change while the programme is running.
  • Transfer the programme to a while-loop.

T4B2) The colon operator (which we have known for a long time) is an implicit for loop. Write new versions of the old tasks using for loops:
a) a function that returns the values on the diagonal of a square matrix
b) Create an 8*8 chessboard from 0 and 1 and view it with imagesc.
*) For fun, also create a 25*25 chessboard and view it.

T4B3) What is the difference between the colon operator and for loops? Can you think of an example that can be solved with a for loop but not with a colon operator? Are there also reverse examples?

T4B4) Write a function that takes a matrix and a threshold as input arguments and returns the value of how many of the matrix elements are greater than this threshold.

  • a) Use two nested for-loops
  • b) Use only one for loop
  • c) Use one while-loop
  • *d) Can you find a way to solve this problem without a loop?

T4B5) Loops can also help you if you want to graphically represent more data than you can reasonably fit into one figure. There are two ways to create multiple figures in Matlab:

  • Multiple graph windows:
    • Figure opens an additional graphics window
    • figure(1) makes the figure with the number 1 theactive window in which the next plot command displays data
    • clf deletes the contents of the current window
    • close(2) closes the window with the number 2
    • close all closes all graphics windows
  • subplots in the same graphics window:
    • subplot(numberofrows,numberofcolumns,active) creates a "matrix" of small figures. For example subplot(2,3,5) with 2 rows and 3 columns, whereby the 5th sub-window is active.
    • Attention! For reasons I do not understand, the mapping windows are not counted along the columns as in the linear indexing of matrices, but along the rows!
    • In the active sub-window, the plot-command (and all associated formatting and labelling) can be used as normal.
    • To activate another sub-window, the command subplot command is used with the corresponding specification for the current number (e.g.subplot(2,3,1)).
  • a) Write a programme that plots a graphic window for a variable number N and plot for the vector x=-5:0.1:5 plot the curve of the respective functionx.^N into it.
  • *b) Write a programme that uses subplotto display severalgraphs in sub-images.
    • The function plotted is x.^N is plotted for the respective vector x=[-x_grenze:0.1:x_grenze]
    • For N, the values N=[1, 2, 3, 4] and for the vector x the limit values x_limit=[5, 10, 20]are used.
    • Each of the 12 possible combinations of these two parameters is to be shown in a separate sub-figure.
    • Sort the figures so that
      • Parabolas with the same definition range (i.e. the same value of x_limit) are shown next to each other in the same "row" of the mapping windows
      • Parabolas with the same exponent N are arranged in the same "column" below each other.

T4B6) Loops do not only have advantages... In Matlab, they have the massive disadvantage that they can make programmes very slow (especially nested loops.) Therefore, it is always more elegant to find a solution to a problem with matrix operations than with loops. Let's try it out here. The command combination
tic
Commands
toc
displays on the screen how much time has elapsed between tic and toc, i.e. when the commands were processed. Use tic and toc to analyse how quickly you can create a 1000 x 1000 matrix whose elements all have the value 7. Create this matrix:

  • a) With the command ones
  • b) With a loop
  • c) With two nested loops
  • d) Is there a difference if you use for or while is used?

Continue working with one of the generated matrices and determine the time to add the value 10 to each of the elements:

  • e) With matrix addition
  • f) With a loop
  • g) With two nested loops
  • h) Is there a difference if you use for or while?

T4B7) The last task is a good application to introduce the Matlab Profiler. This Matlab tool analyses a program to see which lines consume the most CPU time. You start the profiler either by clicking on desktop -> profiler or you use the commands profile to start the analysis and profile viewer to open a window in which the results are shown. e.g.

clear all
profile on
T4B6a_jutta
profile viewer

Try out the profiler for your programmes from T4B6.

C) EXAMPLE: POPULATION GROWTH

The explanation of the development of population sizes has a long tradition in the life sciences. Here we will first look at the simplest example, the linear model for exponential growth:

Suppose we have a population of P flies in our lab and every day we count how big P is. If we do this for a while, we will notice certain regularities, e.g. it could be that every day 20% of the flies hatch and 10% of the flies die. We call these numbers f=0.2 (fertility) and m=0.1 (mortality). (Of course, such rules only apply on average - we will deal with statistical fluctuations around these mean values next week).

Now we can use these rules to predict how the population will grow. If we consider the population Pt on day t, then this number will change by the next day by

dPt=f*Pt - m*Pt = (f-m)*Pt.

This means that the population size Pt+1onday t+1 depends on the population size on the previous day t:

Pt+1=Pt + dPt = Pt + (f-m)*Pt = (1+f-m)*Pt

T4C1) Let us assume that the population with f=0.2 (fertility) and m=0.1 (mortality) has a size of P=500 on day t=1.

  • How many animals are there on the next day?
  • Calculate the population size for a few more days and write it into a vector P so that the t-th element P(t) of the vector contains the value Pt on day t .

T4C2) Write a programme that calculates the population size for the next T=100 days for the given values and writes it to a vector.

  • Have the vector output graphically. Remember to label the axes.
  • Generalise your program so that you can easily try out different values for the model parameters f, m, P(1) and T.
  • Try out how the population develops for a few different mortality and fertility rates. What happens, for example, with f<m? How do P(1) and T affect the development of the population?
  • Turn your programme into a function with which the user can pass the model parameters and receive the vector of the population size as a return.

*T4C3) Write a programme which, instead of a fixed number of days, receives a threshold value as a parameter and calculates the population size for the next day until the threshold value is reached.

  • Think about the problems that can occur when using unsuitable threshold values and how these can be avoided.

**T4C4) You can calculate the population development with a function completely without a loop. How could this be done?

D) HOMEWORK:

Command reference: Matlab syntax

TASKS FOR GRINDING PRACTICE:

T4H1) Create another multiplication table for the multiplication tables - this time with loops.

*T4H2) Write a function that reverses the order of the elements in any vector. For example, [19 7 30] becomes [30 7 19].

T4H3) Program a guessing game in which a Matlab programme guesses an integer between 1 and 100 that you think up with as few yes/no questions as possible. At the end, output the number of questions required.

*T4H4) Write a function with the two input arguments rows and columns. This function should return a matrix filled with two-digit decimal numbers that correspond to the index pair of the respective entry, e.g.

11 12 13 14
21 22 23 24


Extend your function so that it grumbles if the user enters a number of columns >9 (because then things get very ugly).

*T4H5) Something for those interested in graphics: You can also create beautifully coloured surfaces and geometric figures with Matlab.

Let's make a circle first:
degrad = pi/180;
w=0:1:360;
si=sin(w*degrad);
co=cos(w*degrad);
plot(co,si)

If you try this out, this circle looks pretty much like an egg. axis equal makes the axes square, so it's nicer to look at.
A closed line like this circle can be filled with a colour using the fill(x,y,farbdef) command.

  • Try filling the circle with a nice colour.
  • Draw several circles of different sizes inside each other, filled with different colours.
  • Move the centre of the circles towards each other to create a three-dimensional impression. (This is probably best seen with lots of unfilled circles
  • How do you draw a square? Try creating a three-dimensional impression with squares of different sizes.

MORE INTERESTING TASKS:

**T4H6) To draw an N-corner, you can orientate yourself on how a circle is drawn in T4H5. Strictly speaking, this is a 360-degree corner.

  • Draw a 3-corner, a 7-corner and a 25-corner in the same way.
  • Try out how to change the size and direction of these figures.
  • You only need to change the programme slightly to draw a five-pointed star in one go. How?
  • a) Draw a pretty starry sky with different sized, colourful stars with different numbers of corners against a dark blue background.
  • b) Embellish your starry sky so that it fills the whole screen. (Use the help to find out how to do this).
  • c) Draw your stars at random locations in the sky (a normally distributed random number is generated with x=randn(1)).
  • ***d) Make sure that the different stars do not overlap.

** T4H7) (To be used later ) You have the task of catching 10 male and 10 female great tits, blackbirds and robins, ringing them and determining their weight.

  • Write a function that does this work for you and returns a table containing the ring number (in ascending order from 1 to 60), bird species, sex and weight for each of the 60 birds. Use a numerical code (e.g. great tit=1, blackbird=2, robin=3), which is documented in the programme commentary.
  • You "catch" the birds with the following function[birdcatch.m]which can be used with[species,female,weight]=vogelfang and lets random birds flutter into the net. (You do not need to understand this function yet, just use it; we will discuss it on the next day of the course).
  • Return values:
    • Species is a character string,
    • Female is a truth value to indicate the sex,
    • weight is a number (in grams)
  • If you catch a bird that you do not need for your statistics, release it without recording its data.

To the 5th day of the course

(Changed: 11 Feb 2026)  Kurz-URL:Shortlink: https://uol.de/p36844en
Zum Seitananfang scrollen Scroll to the top of the page

This page contains automatically translated content.