Transcript
Page 1: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

1Daniel Baur / Introduction to Matlab Part III

Introduction to Matlab 7

Part III

Daniel Baur

ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

ETH Hönggerberg / HCI F128 – Zürich

E-Mail: [email protected]

http://www.morbidelli-group.ethz.ch/education/snm/Matlab

Page 2: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

2Daniel Baur / Introduction to Matlab Part III

Review of program control

Decisions

Error handling try ...catch err

statements;end

Loops

break;

continue;

Page 3: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

3Daniel Baur / Introduction to Matlab Part II

Data type «struct»

comp(1)

.name = 'water'

.MW = 18.02

.density = 1

.Antoine = [

8.07;

1730;

233];

comp(2)

.name =

'ethanol'.MW = 46.06

.density = 0.789

.Antoine = [

8.20;

1643;

230];

comp(3)

.name = ...

.MW = ...

.density = ...

.Antoine = ...

comp (1,n) struct

Page 4: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

4Daniel Baur / Introduction to Matlab Part II

Review of m-files

What is an m-file? An m-file is a collection of commands. It is equivalent to programs,

functions, subroutines, modules, etc. in other programming languages. It can even contain entire class definitions.

An m-file can be used for Creating a permanent record of what you are doing Experimenting on an algorithm Writing utilities and whole programs

Types of m-files Script m-file: No input and output. Operates on workspace variables. Function m-file: Start with the function key-word, accepts inputs and

gives outputs. All variables are local. Class m-file: Contains the classdef key-word, used in object oriented

programming.

Page 5: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

5Daniel Baur / Introduction to Matlab Part II

Example of a script (mysum.m)

The script reads

How to run the script? From the command window (check the path!) From the editor (press Run button or use Debug Run or press F5)

Page 6: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

6Daniel Baur / Introduction to Matlab Part III

How to deal with error messages in matlab

The topmost error message is usually the one containing the most useful information

The underlined parts of the message are actually links that you can click to get to the line where the error happened!

Page 7: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

7Daniel Baur / Introduction to Matlab Part III

Orange = Unusual Syntax

The script / function will run,

but there are some unusual

or subobtimal commands

This can be caused by (for

example): Not preallocating

variables, using variables in

an unusual way, overriding

variables before they are

used even once, etc.

Clicking the square and

mouse-over works too

Red = Syntax Error

The script / function will

produce and error when run.

Click the red square to jump

to the error, mouse over the

red bar or the underlined part

to get some info

Preventing errors before they happen

The MATLAB editor does (some) on-the-fly proof reading

Green = OK

No syntax errors

or unusual syntax found

Be aware that of course there

can still be semantical errors!

Page 8: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

8Daniel Baur / Introduction to Matlab Part III

Functions in Matlab

Function name (= file name)

Outputs

Inputs

Function description (spend a

minute or two here to save

yourself hours later on)

Function body (where the

magic happens)

function keyword

Page 9: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

9Daniel Baur / Introduction to Matlab Part III

Example of a Function

Calling the function

Page 10: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

10Daniel Baur / Introduction to Matlab Part III

Exercise

1. Create a function called «myFirstFunction.m» Scope: Compute f(x) = 2*x^2 – exp(x) + 3 Inputs: Value of x where f(x) is computed

Outputs: f(x) at x

2. Run the function for different values of x

3. Evaluate the function at 40 points evenly spaced from -5 to +5 and save the values in y

4. Plot y vs. x, use plot(x,y)

Page 11: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

11Daniel Baur / Introduction to Matlab Part III

Local vs. global variables

All variables in functions are local variables This means they exist only inside the function and are

cleared from the workspace after the function ends You can create variables that are seen everywhere by

using the global key-word

ALPHA has changed

everywhere!

Page 12: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

12Daniel Baur / Introduction to Matlab Part III

Local vs. global variables (Continued)

It is common practice to name global variables in CAPS Try to avoid global variables, since they tend to make your

code confusing and hard to understand If you want to pass a lot of variables to a lot of functions,

use structs and parametrizing functions

Page 13: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

13Daniel Baur / Introduction to Matlab Part III

Local vs. global variables (Continued)

If you want to create a variable that keeps its value from one function call to the next (for example an evaluation counter), use the persistent key-word

Persistent variables are local variables

spanning all calls of a specific function.

Page 14: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

14Daniel Baur / Introduction to Matlab Part IV

Solving problems / exercises in Matlab

Usually when you solve problems in Matlab, your program folder will look something like this:

Main executable (script m-file)

Functions used by main.m

Page 15: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

15Daniel Baur / Introduction to Matlab Part IV

The main File

There is usually one main file that is executed, or one per task

It defines or loads variables, operates on them (calculations, solver calls, restructuring, etc.) and displays or saves the results

Page 16: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

16Daniel Baur / Introduction to Matlab Part III

Calling functions from scripts

Scripted program execution is like riding a train down the main file:

Page 17: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

17Daniel Baur / Introduction to Matlab Part III

Debugging functions in Matlab

The command keyboard interrupts program execution and brings up the command prompt

You can use this prompt normally, for things like looking at variables or even changing them

The command return continues program execution (with the changed variables!)

Use the command dbquit (DeBugQuit) or the toolbar to terminate program execution immediately

Note that when keyboard is in a loop, it will stop at every iteration; dbquit is the quickest way to escape here

A very powerful debugging option is to use keyboard in a catch block (interrupt if an error occurs!)

Page 18: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

18Daniel Baur / Introduction to Matlab Part III

Debugging example«Keyboard» command prompt

Program execution has

been halted here

Page 19: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

19Daniel Baur / Introduction to Matlab Part III

Recursive functions

Functions in Matlab can be called recursively Example: Compute the factorial of an integer number

There is an adjustable limit of 500 recursive calls, after which an error is thrown to prevent stack overflow

! ( 1) ( 2) 1n n n n

! ( 1)!n n n

Page 20: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

20Daniel Baur / Introduction to Matlab Part III

Exercise1. Plot the result of «myFirstFunction» vs. [-5:0.5:5]

2. Type hold on; This prevents plot overwriting

3. Plot the result of «myFirstFunction» vs. [-5:0.5:5] using the command plot(x, f, 'ro')

4. Check the current axis interval with axis5. Define a new interval with axis([-3 3 -10 20])6. Set axis labels by xlabel('x'), ylabel('f(x)')7. Superimpose plot(x, 3*sin(x))8. Create a new figure with figure9. Plot the function 2*exp(x2+1)+6 using semilogy10.Place axis labels and rescale the plot to x=-2...2 and y =

10...1000

Page 21: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

21Daniel Baur / Introduction to Matlab Part III

More on 2D Plots

Try: x = linspace(0,10,100); y = tanh(x).*cos(x); plot(x,y)

You can change color, line style, marker style, line width and more: plot(x, y, 'rx--', 'LineWidth', 2)

Plotting multiple data sets: plot(x1, y1, x2, y2) plot(x1, y1);hold onplot(x2, y2);hold off

ColorMarker Line Style

Line Width

(default: 0.5)

Page 22: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

22Daniel Baur / Introduction to Matlab Part III

Line color and style specifiers

Line Color Specifier

Red 'r'

Green 'g'

Blue 'b'

Cyan 'c'

Magenta 'm'

Yellow 'y'

White 'w'

Black 'k'

Line Style Specifier

Continuous (default)

'r'

Dotted Line ':'

Dashed Line '--'

Dash-dotted Line '-.'

Page 23: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

23Daniel Baur / Introduction to Matlab Part III

Marker style specifiers

Marker Style Specifier

Plus Sign '+'

Circle 'o'

Asterisk '*'

Point '.'

Cross 'x'

Square 's'

Diamond 'd'

Five-pointed Star 'p'

Six-pointed Star 'h'

Marker Style Specifier

Triangle (up) '^'

Triangle (down) 'v'

Triangle (left) '<'

Triangle (right) '>'

Much more on line properties: doc lineseriesproperties

Page 24: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

24Daniel Baur / Introduction to Matlab Part III

Annotating graphs

You can use these commands to add descriptive elements to your graphs text(x, y, 'I''m a text'); title('Sub_{script}'); xlabel('I''m a label'); ylabel('Results');

legend('Data1', 'Data2', 'Location', 'Best')

Most Matlab annotators can interpret LaTeX-Commands!

Page 25: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

25Daniel Baur / Introduction to Matlab Part III

Text properties

Property Name Description Property Value

Rotation Text orientation Scalar (deg.), default: 0

FontAngle Normal, Italic Default: Normal

FontName Specifies font Arial, Times, Courier, etc.

FontSize Size of the font Scalar, default: 10

FontWeight Thickness of the font Light, normal, bold

Color Text Color Same as for line

BackgroundColor Color of background Same as for line

EdgeColor Color of box around text Same as for line

LineWidth Line width of the box line Scalar, default: 0.5

Page 26: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

26Daniel Baur / Introduction to Matlab Part III

Other types of plots

Plot a function in an interval fplot(@(x)8*x + cos(x.^2), [1,10]); [x,y] = fplot(@(x)8*x + cos(x.^2), [1,10]; No plot!

Different scales on the axes semilogx(x,y) semilogy(x,y) loglog(x,y)

Different coordinate systems theta = linspace(0, 2*pi);r = 1./(1+theta.^2);polar(theta, r);

θ

r

Page 27: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

27Daniel Baur / Introduction to Matlab Part III

Plots with error bars

x = linspace(1,10); y = 10./x; er = randn(size(y)); errorbar(x, y, er); The errorbars go from y-er to y+er

Page 28: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

28Daniel Baur / Introduction to Matlab Part III

3D plots I: Lines in space

t = linspace(0, 2*pi); x = sqrt(t).*cos(2*t); y = sqrt(t).*sin(2*t); z = t; plot3(x,y,z) grid on

The same line style options apply here.

grid on also works for other plots.

Page 29: Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften

29Daniel Baur / Introduction to Matlab Part III

3D plots II: Surfaces

x = linspace(-5, 5, 30); y = linspace(-2, 2, 20); [X, Y] = meshgrid(x,y); Z = sin(X) .* cos(Y); mesh(X,Y,Z); surf(X,Y,Z); shading interp;

contour(X,Y,Z); colorbar;


Top Related