matlab for biologists - u-szeged.hugroup.szbk.u-szeged.hu/.../education/matlab/matlab_lect_2.pdf ·...

13
MatLab for biologists Lecture 2 May 19, 2010 1

Upload: hakhuong

Post on 26-Aug-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

MatLab for biologistsLecture 2

May 19, 2010

1

1 Elementary programming

Using the above mentioned functions and constructions we can write basicprograms, however we are limited. See the following examples and try tofind out what is missing:

1. Write a function which computes the body mass index and decides thatthe user is under-, normal-, or overweight. Normal if 20 ≤ bmi ≤ 25.

2. Print out the first 100 prime numbers (isprime function).

1.1 if statement

In the fist example we should make a decision and according to the bmi print-ing out different values. In general, we evaluate an expression and accordingto its logical value we go to different branches of our program. For this inMatLab and usually in other programming languages we use the if - elseif- else statement. In MatLab we use the following code:

if (expression1)commands if expression1 is true

elseif (expression2)commands if expression2 is true...

else

commands if ∀ expressioni falseend

Now we can evaluate the body mass index as: Example

H=input(’Enter your height: ’);

W=input(’Enter your weight: ’);

if (BodyMassIndex(H, W) < 20)

disp(’You are underweight.’);

elseif (BodyMassIndex(H, W) < 25)

disp(’Your weight is normal.’);

else

disp(’You are overweight.’);

end

1.1.1 Exercises

• Write a function which decides whether the mean or the median of theinput vector is bigger. (mean, median)

2

• Write a function, the inputs are three numbers, the output is 1 if thethree number describe a right angle triangle, 0 else.

• Write a function which has two input numbers and plots the sinusvalues between them.

1.2 switch statement

If different steps required for different cases the following command can beused:

switch (switch-expr)case case-expr1,

commands if case-expr == switch-exprcase {case-expri,. . .,case-expri+n }

commands if case-expri...i+n == switch-expr...

otherwise

commands if ∀ case-expri != switch-exprend

Write a program which asks the user to type a number, and displays if Exercise

the number is less than one, one, two, three, four, five, or more than five.

1.3 Loops

The second example of the if statement shows that sometimes we would liketo make the same or very similar computations many times. The program-ming languages offer loops to solve these problems. The following possibilitiesare available:

• for: execute block of code specified number of times,

• while: repeatedly execute statements while condition is true.

1.3.1 for loop

To repeat set of commands for given times MatLab and in usual programminglanguages offers the for loop. The syntax is:

for x=initval:stepval:endval

statements

end

3

The statements will be executed as many times as x reaches endval sothat it stars form initval and increases with stepval in each iterations.For example the following lines computes the first 20 Fibonacci1 numbers:

F = ones(20,1);

for i=3:20

F(i) = F(i-1)+F(i-2);

end

Create a vector R with 100 random numbers (rand), create an other null- Exercise

vector S in the same size. Smooth R vector so that all the elements of Sbecomes the average of the three closest elements of R, Sn = Rn−1+Rn+Rn+1

3.

Plot R and S in the same plot.

1.3.2 while loop

The role of while loops is similar to for loops, but in this case the number ofiterations is not directly determined at the beginning. In MatLab the syntaxis:

while expression

statements

end

In this case statements are evaluated as soon as the expression nolonger holds true. For example if we want to find the first 100 prime numbers(isprime), this can be done in MatLab as:

primeNb = 0; counter = 1;

while (primeNb<100)

if isprime(counter)

counter

primeNb=primeNb+1;

end

counter = counter+1;

end

1.4 Development with flowchart

In the previous chapters we learned how to program MatLab . In this sectionwe will see how to develop algorithms to solve problems. For that we use

1The nth Fibonacci number Fn is the sum of Fn−1 and Fn−2, and F1 = F2 = 1

4

flowchart diagrams. With this technique we can model every steps of thealgorithms to have a logical overview and base to implement our programs.We can find flowchart symbols for all statements. These are the following:

• Assignment statements: in figure 1, one or several commands groupedinto one rectangular box. One arrow pointing into the box and onearrow out.

c o m m a n d

Figure 1: Flowchart diagram of assignment statements.

• Conditional statement: see figure 2, in a diamond shaped box is thecondition and two out pointing arrows for its true or false values. Tocreate multiple branches (elseif), we can combine more symbols, con-necting them to the false branch.

c o n d i t i o n

c o m m a n d i f t r u e

T r u e F a l s e

c o m m a n d i f f a l s e

Figure 2: Flowchart diagram of the conditional statement.

• Loops: in figure 3 they can considered as combination of conditionsand assignments.

• Blocks (functions, programs, batches): in the flowchart terminologyblocks start and stop with rounded rectangles, see figure 4.

1.5 Exercises

Develop and write a MatLab program which smooths a vector, similar to theexample above, but here the number of neighbors is given. Create a vectorwith a sinus wave, add random noise to it and test your algorithm, plot theresult!

5

c o n d i t i o n c o m m a n dT r u e

F a l s e

Figure 3: Flowchart diagram of loops.

c o m m a n d ( s )

S t a r t

S t o p

Figure 4: Flowchart diagram of blocks.

2 Exercises for programming and development

Develop and write a MatLab function which smooths a vector, and the num- Exercise

ber of neighbors (window size) is given. Create a vector with a sinus wave,add random noise to it and test your algorithm, plot the result!

First we develop the function:

An example for the implementation:

function smoothV = smoothVector(origV, halfWindowSize)

smoothV=zeros(length(origV), 1);

for i=halfWindowSize+1:length(origV) - halfWindowSize

smoothV(i) = mean(origV(i-halfWindowSize:i+halfWindowSize));

end;

Now we can test the algorithm e.g. :

scale = 0:0.1:6*pi;

original=sin(scale)+(rand(1, length(scale))-0.5)* 0.3;

smooth = smoothVector(original, 5);

6

s m o o t h = z e r o s ( l e n g t h ( o r i g ) , 1 )

s m o o t h V e c t o r ( o r i g , h W S )

S t o p

i = h W S + 1

i < = l e n g t h ( o r i g ) - h W S

i = i + 1

T r u e

F a l s e

s m o o t h ( i ) = m e a n ( o r i g ( i - h W S : i + h W S ) )

Figure 5: Flow chart diagram.

plot(scale, original, scale, smooth);

You have 100 measurement from an experiment and the task is to de- Exercise

cide whether it was successful. An experiment is successful if you sort outthe 10 biggest and 10 smallest measures and the standard deviation of theremaining 80 numbers is less than stdLimit. Develop and write a programto solve the problem (use: sort and std functions), download test data 1

and test data 2 files from the course homepage and test whether they aresuccessful or not if stdLimit = 0.3 and 0.85.

3 Visualization

However MatLab has wide range of different data visualization opportunities,we can define a general workflow how to build up our figures:

1. Prepare the data

2. Select a window and position a plot region within the window

3. Call elementary plotting function

4. Select line and marker characteristics

7

0 2 4 6 8 10 12 14 16 18 20−1.5

−1

−0.5

0

0.5

1

1.5

Figure 6:

5. Set axis limits, tick marks, and grid lines

6. Annotate the graph with axis labels, legend, and text

7. Export graph

We can exclude some of the steps. An example for visualization, type thecommands line-by-line and check the changes on the plot (see figure 7):x = 0:0.1:5; 1

d1 = cos(x) * 8;

d2 = x.^2;

figure(1); 2

h = plot(x, d1, x, d2); 3

set(h, ’LineWidth’, 2); 4

axis([-1 6 -20 20]); 5

grid on;

title(’Example plot’); 6

xlabel(’x-values’);

legend(h, ’cosine’, ’square’);

8

[y, xi] = min(d1);

text(x(xi), y, ’\leftarrow Local minimum’);

print -depsc -r200 firstplot; 7

−1 0 1 2 3 4 5 6−20

−15

−10

−5

0

5

10

15

20Example plot

x−values

← Local minimum

cosinesquare

Figure 7:

3.1 Interactive editing, figure window

We can interactively modify the parameters of the plots, and add/change Exercise

annotations. Try in Edit menu. Change the font type and size of the figuretitle. Change the position of the legend window. Set the size of the ‘←Localminimum’ text smaller. Change the color of the square cure to black andthe line width to 4.

3.2 Special plots

Here we give some examples for special data visualization techniques. Formore information see the help.

The bar and bar3 commands create a bar plot from n × k matrices. Areavisualize the area of the vectors. e.g. see figure 8data = [1 3 5; 2 4 6; 1 2 4; 4 6 7; 2 5 5];

bar(data);

bar3(data);

9

bar(data, ’stack’);

bar3(data, ’group’);

area(data);

The pie command creates a pie plot of a vector:data = [2 2.2 4.2 3.2 4.1];

pie(data);

pie3(data);

3.3 3D plots

MatLab offers commands to visualize surfaces and 3D objects. To continue,please download the height-map of Switzerland (swiss map) from the coursewebpage. We will visualize the terrain using the surf command. To createa contour plot of a surface we use the contour, contourf and contour3

functions. See figure 10.

3.3.1 More advanced plots

To show the colors used during visualization we can type the colorbar com-mand. We can change the colors using the colormap function (see help).

Here we see an example how to make our plot more attractive. Let us Exercise

change the Swiss color map to grayscale, change to interpolated shading andchange the direction of the view- and light angles. See figure 3.3.1.surf(swiss, ’FaceLighting’, ’phong’);

view(180, 80);

lightangle(145, 30);

shading(’interp’);

colormap(’gray’);

4 Used material

• An Introduction to MatLab – David F. Griffiths – University of Dundee

• Using MatLab – The MathWorks, Inc.

• A MatLab c© ‘primer’ – Ernesto Di Iorio – ETH Zurich

10

1 2 3 4 50

1

2

3

4

5

6

7

1

2

31

23

45

0

2

4

6

8

1 2 3 4 50

2

4

6

8

10

12

14

16

18

12

34

5

0

1

2

3

4

5

6

7

1 1.5 2 2.5 3 3.5 4 4.5 50

2

4

6

8

10

12

14

16

18

Figure 8: bar, bar3, and aera commands

11

13%

14%

27%

20%

26%

20%

26%

27%

13%

14%

Figure 9: pie and pie3 commands

50 100 150 200 250 300 350 400

50

100

150

200

250

Figure 10: surf and contourf commands

12

13