Uploaded by Worajedt Sitthidumrong

matlab lect 2

advertisement
MatLab for biologists
Lecture 2
May 19, 2010
1
1
Elementary programming
Using the above mentioned functions and constructions we can write basic
programs, however we are limited. See the following examples and try to
find out what is missing:
1. Write a function which computes the body mass index and decides that
the 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 printing out different values. In general, we evaluate an expression and according
to its logical value we go to different branches of our program. For this in
MatLab 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 false
end
Now we can evaluate the body mass index as:
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 the
input vector is bigger. (mean, median)
2
Example
• Write a function, the inputs are three numbers, the output is 1 if the
three number describe a right angle triangle, 0 else.
• Write a function which has two input numbers and plots the sinus
values between them.
1.2
switch statement
If different steps required for different cases the following command can be
used:
switch (switch-expr)
case case-expr1 ,
commands if case-expr == switch-expr
case {case-expri ,. . .,case-expri+n }
commands if case-expri...i+n == switch-expr
...
otherwise
commands if ∀ case-expri != switch-expr
end
Write a program which asks the user to type a number, and displays if
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 like
to make the same or very similar computations many times. The programming languages offer loops to solve these problems. The following possibilities
are 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 programming
languages offers the for loop. The syntax is:
for x=initval:stepval:endval
statements
end
3
Exercise
The statements will be executed as many times as x reaches endval so
that 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 nullvector S in the same size. Smooth R vector so that all the elements of S
becomes the average of the three closest elements of R, Sn = Rn−1 +R3n +Rn+1 .
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 of
iterations is not directly determined at the beginning. In MatLab the syntax
is:
while expression
statements
end
In this case statements are evaluated as soon as the expression no
longer 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 section
we will see how to develop algorithms to solve problems. For that we use
1
The nth Fibonacci number Fn is the sum of Fn−1 and Fn−2 , and F1 = F2 = 1
4
Exercise
flowchart diagrams. With this technique we can model every steps of the
algorithms 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 grouped
into one rectangular box. One arrow pointing into the box and one
arrow out.
command
Figure 1: Flowchart diagram of assignment statements.
• Conditional statement: see figure 2, in a diamond shaped box is the
condition and two out pointing arrows for its true or false values. To
create multiple branches (elseif), we can combine more symbols, connecting them to the false branch.
True
condition
command if true
False
command if false
Figure 2: Flowchart diagram of the conditional statement.
• Loops: in figure 3 they can considered as combination of conditions
and assignments.
• Blocks (functions, programs, batches): in the flowchart terminology
blocks start and stop with rounded rectangles, see figure 4.
1.5
Exercises
Develop and write a MatLab program which smooths a vector, similar to the
example above, but here the number of neighbors is given. Create a vector
with a sinus wave, add random noise to it and test your algorithm, plot the
result!
5
True
condition
command
False
Figure 3: Flowchart diagram of loops.
Start
command(s)
Stop
Figure 4: Flowchart diagram of blocks.
2
Exercises for programming and development
Develop and write a MatLab function which smooths a vector, and the number 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
Exercise
smoothVector(orig, hWS)
smooth = zeros(length(orig), 1)
i=hWS+1
False
i<=length(orig)-hWS
True
smooth(i)=mean(orig(i-hWS:i+hWS))
i=i+1
Stop
Figure 5: Flow chart diagram.
plot(scale, original, scale, smooth);
You have 100 measurement from an experiment and the task is to decide whether it was successful. An experiment is successful if you sort out
the 10 biggest and 10 smallest measures and the standard deviation of the
remaining 80 numbers is less than stdLimit. Develop and write a program
to 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 are
successful 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
Exercise
1.5
1
0.5
0
−0.5
−1
−1.5
0
2
4
6
8
10
12
14
16
18
20
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 the
commands line-by-line and check the changes on the plot (see figure 7):
x = 0:0.1:5;
d1 = cos(x) * 8;
d2 = x.^2;
1
figure(1);
2
h = plot(x, d1, x, d2);
3
set(h, ’LineWidth’, 2);
4
axis([-1 6 -20 20]);
grid on;
5
title(’Example plot’);
xlabel(’x-values’);
legend(h, ’cosine’, ’square’);
6
8
[y, xi] = min(d1);
text(x(xi), y, ’\leftarrow Local minimum’);
7
print -depsc -r200 firstplot;
Example plot
20
cosine
square
15
10
5
0
−5
← Local minimum
−10
−15
−20
−1
0
1
2
3
4
5
6
x−values
Figure 7:
3.1
Interactive editing, figure window
We can interactively modify the parameters of the plots, and add/change
annotations. Try in Edit menu. Change the font type and size of the figure
title. Change the position of the legend window. Set the size of the ‘←Local
minimum’ text smaller. Change the color of the square cure to black and
the line width to 4.
3.2
Special plots
Here we give some examples for special data visualization techniques. For
more information see the help.
The bar and bar3 commands create a bar plot from n × k matrices. Area
visualize the area of the vectors. e.g. see figure 8
data = [1 3 5; 2 4 6; 1 2 4; 4 6 7; 2 5 5];
bar(data);
bar3(data);
9
Exercise
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 course
webpage. We will visualize the terrain using the surf command. To create
a 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 command. 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
change the Swiss color map to grayscale, change to interpolated shading and
change 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.
c ‘primer’ – Ernesto Di Iorio – ETH Zurich
• A MatLab 10
Exercise
7
6
8
5
6
4
4
3
2
2
0
1
1
3
2
3
0
2
4
1
2
3
4
5
5
18
7
16
6
14
5
12
4
10
3
8
2
6
1
4
0
1
1
2
2
3
0
4
1
2
3
4
5
5
18
16
14
12
10
8
6
4
2
0
1
1.5
2
2.5
3
3.5
4
4.5
5
Figure 8: bar, bar3, and aera commands
11
13%
26%
13%
26%
14%
14%
20%
20%
27%
27%
Figure 9: pie and pie3 commands
250
200
150
100
50
50
100
150
200
250
300
350
400
Figure 10: surf and contourf commands
12
13
Download