Download presentation
Presentation is loading. Please wait.
Published byCordelia Charles Modified over 9 years ago
1
Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften ETH Hönggerberg / HCI F128 – Zürich E-Mail: daniel.baur@chem.ethz.ch http://www.morbidelli-group.ethz.ch/education/snm/Matlab
2
Review of program control Decisions Error handling try... catch err statements; end Loops break; continue; 2Daniel Baur / Introduction to Matlab Part III
3
Data type «struct» 3Daniel Baur / Introduction to Matlab Part II 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
4
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. 4Daniel Baur / Introduction to Matlab Part II
5
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) 5Daniel Baur / Introduction to Matlab Part II
6
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! 6Daniel Baur / Introduction to Matlab Part III
7
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 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 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 7Daniel Baur / Introduction to Matlab Part III Green = OK No syntax errors or unusual syntax found Be aware that of course there can still be semantical errors! Green = OK No syntax errors or unusual syntax found Be aware that of course there can still be semantical errors!
8
Functions in Matlab 8Daniel Baur / Introduction to Matlab Part III 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 function keyword
9
Example of a Function Calling the function 9Daniel Baur / Introduction to Matlab Part III
10
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 y 3.Evaluate the function at 40 points evenly spaced from -5 to +5 and save the values in y yxplot(x,y) 4.Plot y vs. x, use plot(x,y) 10Daniel Baur / Introduction to Matlab Part III
11
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 global You can create variables that are seen everywhere by using the global key-word 11Daniel Baur / Introduction to Matlab Part III ALPHA has changed everywhere!
12
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 12Daniel Baur / Introduction to Matlab Part III
13
Local vs. global variables (Continued) persistent 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 13Daniel Baur / Introduction to Matlab Part III Persistent variables are local variables spanning all calls of a specific function.
14
Solving problems / exercises in Matlab Usually when you solve problems in Matlab, your program folder will look something like this: 14Daniel Baur / Introduction to Matlab Part IV Main executable (script m-file) Functions used by main.m
15
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 15Daniel Baur / Introduction to Matlab Part IV
16
Calling functions from scripts Scripted program execution is like riding a train down the main file: 16Daniel Baur / Introduction to Matlab Part III
17
Debugging functions in Matlab keyboard 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 return The command return continues program execution (with the changed variables!) dbquit Use the command dbquit (DeBugQuit) or the toolbar to terminate program execution immediately keyboard dbquit Note that when keyboard is in a loop, it will stop at every iteration; dbquit is the quickest way to escape here keyboard catch A very powerful debugging option is to use keyboard in a catch block (interrupt if an error occurs!) 17Daniel Baur / Introduction to Matlab Part III
18
Debugging example 18Daniel Baur / Introduction to Matlab Part III «Keyboard» command prompt Program execution has been halted here
19
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 19Daniel Baur / Introduction to Matlab Part III
20
Exercise 1.Plot the result of «myFirstFunction» vs. [-5:0.5:5] hold on 2.Type hold on ; This prevents plot overwriting plot(x, f, 'ro') 3.Plot the result of «myFirstFunction» vs. [-5:0.5:5] using the command plot(x, f, 'ro') axis 4.Check the current axis interval with axis axis([-3 3 -10 20]) 5.Define a new interval with axis([-3 3 -10 20]) xlabel('x')ylabel('f(x)') 6.Set axis labels by xlabel('x'), ylabel('f(x)') plot(x, 3*sin(x)) 7.Superimpose plot(x, 3*sin(x)) figure 8.Create a new figure with figure semilogy 9.Plot the function 2*exp(x 2 +1)+6 using semilogy 10.Place axis labels and rescale the plot to x=-2...2 and y = 10...1000 20Daniel Baur / Introduction to Matlab Part III
21
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 on plot(x2, y2); hold off 21Daniel Baur / Introduction to Matlab Part III Color Marker Line Style Line Width (default: 0.5)
22
Line color and style specifiers Line ColorSpecifier Red 'r' Green 'g' Blue 'b' Cyan 'c' Magenta 'm' Yellow 'y' White 'w' Black 'k' Line StyleSpecifier Continuous (default) 'r' Dotted Line ':' Dashed Line '--' Dash-dotted Line '-.' 22Daniel Baur / Introduction to Matlab Part III
23
Marker style specifiers Marker StyleSpecifier Plus Sign '+' Circle 'o' Asterisk '*' Point '.' Cross 'x' Square 's' Diamond 'd' Five-pointed Star 'p' Six-pointed Star 'h' Marker StyleSpecifier Triangle (up) '^' Triangle (down) 'v' Triangle (left) '<' Triangle (right) '>' 23Daniel Baur / Introduction to Matlab Part III doc lineseriesproperties Much more on line properties: doc lineseriesproperties
24
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! 24Daniel Baur / Introduction to Matlab Part III
25
Text properties Property NameDescriptionProperty Value RotationText orientationScalar (deg.), default: 0 FontAngleNormal, ItalicDefault: Normal FontNameSpecifies fontArial, Times, Courier, etc. FontSizeSize of the fontScalar, default: 10 FontWeightThickness of the fontLight, normal, bold ColorText ColorSame as for line BackgroundColorColor of backgroundSame as for line EdgeColorColor of box around textSame as for line LineWidthLine width of the box lineScalar, default: 0.5 25Daniel Baur / Introduction to Matlab Part III
26
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]; [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); 26Daniel Baur / Introduction to Matlab Part III θ r
27
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 27Daniel Baur / Introduction to Matlab Part III
28
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 28Daniel Baur / Introduction to Matlab Part III The same line style options apply here. grid on also works for other plots.
29
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; 29Daniel Baur / Introduction to Matlab Part III
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.