Download presentation
Presentation is loading. Please wait.
1
Mathematical Programming with MATLAB
Tuesday
2
HA17: Program Development
Algorithms Top-Down Design and Modules Good Programming Practices Optimizing Code Debugger M- Lint Profiler Performance Measurements
3
Scientific Computing empty Mauri Puoskari
4
Developing an Algorithm
One of the key tasks in solving engineering and scientific problems is the development and implementation of an algorithm to solve the problems. We can define an algorithm as: “A method or procedure of computation which usually involves a series of steps”. That is nothing more than the general procedure we use in any problem solving exercise. However the important thing in computing is to have a structured and organized approach. In solving any engineering or scientific problem which requires computation there is a series of overall steps. These are shown in the following figure.
5
Developing an Algorithm
6
An Engineering Example
Let us look at each of these steps by way of a particular example. The example is the calculation of liquid loss from a hole in the base of a storage tank.
7
Example … continue ρL = liquid density (kg/m3) Ph = Pascals
Phase 1: Understanding the Physical Problem The situation is represented in the diagram (previous slide). Flow is given by Bernoulli’s equation. Key parameters are tank pressure P; liquid density ρL; height of liquid h and the atmospheric pressure. Flow rate is related to the pressure difference (Ph - Pa). Phase 2: From Physical Problem to Mathematical Description Bernoulli’s equation applied across the hole gives: ρL = liquid density (kg/m3) Ph = Pascals Pa = Pascals Ph = P + liquid head = P + ρL gh where h = metres and g = 9.81 m/s2.
8
Example … continue So we get Mass flow rate is: G = u Ah ρL (kg/s)
where Ah = flow area (m2) or hole diameter = dh CD = loss (or concentration) coefficient; 0.61 (sharp hole), 0.8 (smooth hole) This is the equation which calculates the flow rate of lost liquid.
9
Example … continue Phase 3: Solution: Flow Diagram (or Pseudo code)
10
Example … continue Phase 4: Implement Algorithm and Document Code
Below is the implementation in MATLAB. Note the following: Code documentation: What it does Who wrote it What date What are the required inputs What is given as output(s) Are there other routines used in this code Any revisions made, date, by whom Comments: Put comments in the code so it is readable Checks: For incorrect input or other potential errors Indentation can help clearly identify subsections of your algorithm. PLEASE MAKE SURE YOU DO THIS IN YOUR CODE! The following MATLAB code shows the implementation of the algorithm.
11
Example … continue % This routine computes the out flow of a liquid from a pressurized % tank using a form of the Bernoulli equation. % % Inputs are: % P = vapour space pressure (kPa) % h = liquid height (m) % rho_l = liquid density (kg/m^3) % d_h = hole diameter (mm) % Outputs are: % G = liquid flow rate (kg/s) % Author: N.N, Dept. of Physics, UEF % Date: September 2010 % Revisions: none
12
Example … continue % Parameters g = 9.81; P_a = ; C_d = 0.61; % Get input from user P = input('Give the vapour space pressure (kPa) '); h = input('Give the liquid height (m) '); d_h = input('Give the hole diameter (mm) '); rho_l = input('Give the liquid density (kg/m^3) '); % compute flow area (m^2) A_h = d_h^2/4*1e-6 ; % convert input from kilopascals to pascals P = P*1000; % compute the liquid flow G = C_d*A_h*rho_l*sqrt(2*(P-P_a)/rho_l +2*g*h); % display output fprintf('Liquid flowrate is %6.2f (kg/s) \n', G)
13
Example … continue Phase 5: Test and Verify the Algorithm
As a simple test use the following input. P = 200 kPa h = 4 metres d_h = 25 mm ρL = 1200 kg/m3 Output result gives: liquid flow rate is G=1.78 kg/s This simple example should give you a basic idea of what is expected as a standard for solving computational problems: keep in mind the basic principles, be structured in your approach, document and comment your code and test it to see if it is correct.
14
Top-Down Design If we look at a problem as a whole, it may seem impossible to solve because it is so complex. Complex problems can be solved using top-down design, also known as stepwise refinement, where We break the problem into parts Then break the parts into parts Soon, each of the parts will be easy to do
15
Advantages of Top-Down Design
Breaking the problem into parts helps us to clarify what needs to be done. At each step of refinement, the new parts become less complicated and, therefore, easier to figure out. Parts of the solution may turn out to be reusable. Breaking the problem into parts allows more than one person to work on the solution.
16
Structured Programs We will use top-down design for all remaining MATLAB programming projects. This is the standard way of writing programs. Programs produced using this method and using only the three kinds of control structures, sequential, selection and repetition, are called structured programs. Structured programs are easier to test, modify, and are also easier for other programmers to understand.
17
A Simple Example Problem: Write a program that draws this picture of a house.
18
The Top Level Draw the outline of the house Draw the chimney
Draw the door Draw the windows Main Draw Outline Draw Chimney Draw Door Draw Windows
19
Pseudocode for Main Call Draw Outline Call Draw Chimney Call Draw Door
Call Draw Windows
20
A Refinement The door has both a frame and knob. We could break this step further into two steps. Main Draw Outline Draw Chimney Draw Door Draw Windows Draw Door Frame Draw Knob
21
Pseudocode for Draw Door
Call Draw Door Frame Call Draw Knob
22
Another Level? Should any of these steps be broken down further? Possibly. How do I know? Ask yourself whether or not you could easily write the algorithm for the step. If not, break it down again. When you are satisfied with the breakdown, write the pseudo code for each of the steps (modules) in the hierarchy. Typically, each module will be coded as a separate MATLAB function.
23
Good Programming Practices: Overview
Rationale Programming Style Why and How of Modular Code Top-down program design Basic Debugging
24
Rationale Organized modular programs are . . . Debugging . . .
• easier to maintain • easier to debug • not much harder to write Debugging . . . • is inevitable • can be anticipated with good program design • can be done interactively with Matlab 7
25
Programming Style A consistent programming style gives your programs a visual familiarity that helps the reader quickly comprehend the intention of the code. A programming style consists of • Visual appearance of the code • Conventions used for variable names • Documentation with comment statements
26
Programming Style … Use visual layout to suggest organization
• Indent if...end and for...end blocks • Use blank lines separate major blocks of code Example: indent code for conditional structures and loops if condition 1 is true Block 1 elseif condition 2 is true Block 2 end for i=1:length(x) Body of loop
27
Programming Style … Use meaningful variable names d = 5; t = 0.02;
r = d/2; r2 = r + t; d_in = 5; thick = 0.02; r_in = d_in/2; r_out = r_in + thick; Follow Programming and Mathematical Conventions Variable names Typical usage k, n, m Array subscripts, loop counters i, j √−1 with complex arithmetic m, n End of a sequence, k = 1, , n, Number of rows (m) and columns (n) in a matrix A, B Generic matrix x, y, z Generic vectors Note: Consistency is more important than convention
28
Programming Style … Document code with comment statements
• Write comments as you write code, not after. • Include a prologue that supports “help” command. • Assume that the code is going to be used more than once and by one person. • Comments should be short notes that augment the meaning of the program statements: do not repeat the code. • Comments alone do not create good code.
29
Programming Style … Example: Comments at beginning of a block
% --- Evaluate curve fit and plot it along with original data tfit = linspace(min(t),max(t)); pfit = polyval(c,tfit); plot(t,p,’o’,tfit,pfit,’--’); xlabel(’Temperature (C)’); ylabel(’Pressure (MPa)’); legend(’Data’,’Polynomial Curve Fit’); Example: Short comments at side of statements cp = 2050; % specific heat of solid and liquid paraffin (J/kg/K) rho = 810; % density of liquid or solid paraffin (kg/m^3) k = 0.23; % thermal conductivity, (W/m/C) L = 251e3; % latent heat (J/kg) Tm = 65.4; % melting temperature (C)
30
Supporting On-line Help
First line of a function is the definition. Second line must be a comment statement. All text from the second line up to the first non-comment line is printed in response to >> help functionName
31
Function File Format A Function M-File contains:
1 2 3 A Function M-File contains: a function definition line a comment block and blank space for your code an end statement 4
32
Prologue Used in Your Own Toolbox
Summary: one line description of what the function does. Synopsis: list the various ways in which the function can be called. Input: describe each input variable. Output: describe each output variable.
33
Modular Code A module should be dedicated to one task
• Flexibility is provided by input/output parameters General purpose modules need . . . • Description of input/output parameters • Meaningful error messages so that user understands the problem.
34
Modular Code … Reuse modules • Debug once, use again
• Minimize duplication of code • Any improvements are available to all programs using that single module • Error messages must be meaningful so that user of general purpose routine understands the problem Organization takes experience • Goal is not to maximize the number of m-files • Organization will evolve on complex projects
35
Example: Built-in Bessel functions
The Bessel functions are solutions to ODE The Bessel function of the first kind is Jν(z), where ν is a real number and z is complex Other Bessel functions (which are also solutions to the ODEs) are defined in terms of Jν(z).
36
Example: Built-in Bessel functions …
Rather than repeat the code that computes Jν(z) and Γ(z), these fundamental functions are part of a core routine that gets evaluated via an interface function >> lookfor bessel BESSCHK Check arguments to bessel functions. BESSEL Bessel functions of various kinds. BESSELA Obsolete Bessel function. BESSELH Bessel function of the third kind (Hankel function). BESSELI Modified Bessel function of the first kind. BESSELJ Bessel function of the first kind. BESSELK Modified Bessel function of the second kind. BESSELY Bessel function of the second kind. BESSLDEM Driver function for Bessel zero finding. BESSLODE Bessel’s equation of order 0 used by BESSLDEM.
37
Example: Built-in Bessel functions …
38
Defensive Programming
Do not assume the input is correct. Check it. • Provide a default condition for a if...elseif...else... construct. • Include optional (verbose) print statements that can be switched on when trouble occurs. • Provide diagnostic error messages.
39
Pre-emptive Debugging
Use defensive programming • Break large programming projects into modules Develop reusable tests for key modules Good test problems have known answers Run the tests after changes are made to the module • Include diagnostic calculations in a module Enclose diagnostics inside if...end blocks so that they can be turned off (now also try … catch) Provide extra print statements that can also be turned on and off
40
Debugging Tools Matlab version 6 (and later) has an interactive debugger • The type and dbtype commands are used to list contents of an m-file. • The error function prints a message to the screen, and stops execution. This provides for graceful failure, and the opportunity to inform the reader of potential causes for the error. • The warning function prints a message to the screen, but does not stop execution. • Pause or keyboard commands can be used to temporarily halt execution. More about debugging on later slides.
41
Use of keyboard Command
function r = quadroot(a,b,c) % quadroot Roots of quadratic equation and demo of keyboard command % % Synopsis: r = quadroot(a,b,c) % Input: a,b,c = coefficients of a*x^2 + b*x + c = 0 % Output: r = column vector containing the real or complex roots d = b^2 - 4*a*c; if d<0 fprintf(’Warning in function QUADROOT:\n’); fprintf(’\tNegative discriminant\n\tType "return" to continue\n’); keyboard; end q = -0.5*( b + sign(b)*sqrt(b^2 - 4*a*c) ); r = [q/a; c/q]; % store roots in a column vector
42
Some Useful MATLAB Features
Matlab has features to solve some recurring programming problems: Variable number of I/O parameters Indirect function evaluation with feval In-line function objects (Matlab version 7.x) Global Variables
43
Variable Input and Output Arguments
Each function has internal variables, nargin and nargout. Use the value of nargin at the beginning of a function to find out how many input arguments were supplied. Use the value of nargout at the end of a function to find out how many input arguments are expected. Usefulness: • Allows a single function to perform multiple related tasks. • Allows functions to assume default values for some inputs, thereby simplifying the use of the function for some tasks
44
Variable Input and Output Arguments…
Consider the built-in plot function Inside the plot function nargin nargout plot(x,y) plot(x,y,’s’) plot(x,y,’s--’) plot(x1,y1,’s’,x2,y2,’o’) h = plot(x,y) The values of nargin and nargout are determined when the plot function is invoked.
45
Indirect Function Evaluation
The feval function allows a function to be evaluated indirectly. Usefulness: • Allows routines to be written to process an arbitrary f(x). • Separates the reusable algorithm from the problem-specific code. feval is used extensively for root-finding, curve-fitting, numerical quadrature and numerical solution of initial value problems etc. Functions which uses feval are called function-functions.
46
Example: Indirect Function Evaluation
On the slide we define a function-function fsum which has a function name as an input parameter. MATLAB function feval permits one to have as an input variable a string which is naming another function. Examples >> fsum(’sin’,0,pi,5) ans = 2.4142 >> fsum(’cos’,0,pi,5)
47
Use of feval function s = fsum(fun,a,b,n) % FSUM Computes the sum of function values, f(x), at n equally % distributed points in an interval a <= x <= b % % Synopsis: s = fsum(fun,a,b,n) % Input: fun = (string) name of the function to be evaluated % a,b = endpoints of the interval % n = number of points in the interval x = linspace(a,b,n); % create points in the interval y = feval(fun,x); % evaluate function at sample points s = sum(y); % compute the sum
48
Function Functions: feval
The feval function allows a function to be evaluated indirectly. Usefulness: Allows routines to be written to process an arbitrary f(x). Separates the reusable algorithm from the problem-specific code. feval is used extensively for function functions: - root-finding - curve-fitting - numerical quadrature - numerical solution of initial value problems Indirect Function Evaluation: >> fsum(’sin’,0,pi,5) % see next slide ans = 2.4142 >> fsum(’sincos’,0,pi,5) % see next slide
49
Function Function Example
function s = fsum(fun,a,b,n) % FSUM Computes the sum of function values, f(x), % at n equally distributed points % in an interval a <= x <= b % % Usage: s = fsum(fun,a,b,n) % Input: fun = (string) % name of the function to be evaluated % a,b= endpoints of the interval % n = number of points in the interval % create points in the interval x = linspace(a,b,n); % evaluate function at sample points y = feval(fun,x); % compute the sum s = sum(y); function y = sincos(x) % SINCOS Evaluates function % sin(x)*cos(x) for any input x % % Usage: y = sincos(x) % Input: x = angle in radians, % or vector of angles % in radians % Output: y = value of product % sin(x)*cos(x) for each % element in x y = sin(x).*cos(x);
50
Function-Functions: ODE Solver
MATLAB provides built-in functions to solve differential equations. ODE solve ode45 is an example of MATLAB's function-function. These functions work with MATLAB functions, or anonymous functions. >> dy ( x.^3 )./ ( exp(x) - 1 ); >> y = ode45(dy,[0.1 15],0); >> x = linspace(0.1,15,100); >> dydata = dy(x); >> plot(x,dydata, y.x, y.y)
51
Inline Function Objects
Matlab 7 introduced object-oriented programming extensions. Though OOP is an advanced and somewhat subtle way of programming, in-line function objects are simple to use and offer great program flexibility. Instead of function y = myFun(x) y = x.^2 - log(x); use myFun = inline( ’x.^2 - log(x)’ ); Both definitions of myFun allow expressions like z = myFun(3); s = linspace(1,5); t = myFun(s); Usefulness: • Eliminates need to write separate m-files for functions that evaluate a simple formula. • Useful in all situations where feval is used. You can use also anonymous functions.
52
Anonymous Functions: Example
Perform the following: >> ln >> ln(1) >> log(1) >> sqr x.^2 >> sqr(5) >> quad(sqr,0,1) >> sum_xy y) (5*x +2*y); >> sum_xy(5, 7) Define an anonymous function ln. Create an anonymous function that squares a number. Because sqr is a function handle, you can pass it in an argument list to other functions. Example of an anonymous function with a two input variables. Anonymous functions remain active until you clear them from your workspace or restart MATLAB.
53
Global Variables Communication of values via input and output variables workspace Communication of values via input and output variables and global variables shared by the workspace and Usefulness: • Allows bypassing of input parameters if no other mechanism (such as pass-through parameters) is available. • Provides a mechanism for maintaining program state (GUI applications) function
54
Example: Global Variables
55
Summary: Good Coding Practices
Create descriptive variable names and function names. Keep them reasonable in length. When possible, define the key variables you are going to use in a comment block at the top of the program. Unless self-explanatory, all lines and/or blocks of code must always be commented. When writing a function, an overall description of the function, preferably with its syntax, must always appear directly below the function statement. Indent and space blocks of code to improve organization and readability of the code. This facilitates code modification & debugging activities. Break up larger programs into a main program with calls to smaller, specialized programs. Use flowcharting and pseudo code when starting a project to help organize what you need to do.
56
Using Pseudo Code Pseudo code is like a recipe – tells you what to do, but doesn’t give you the specifics on how to do it. Constructing pseudo code Outline a set of statements describing the steps you will take to solve a problem Convert these steps into comments in an M-file Insert the appropriate MATLAB code into the file between the comment lines. Write a program to convert mph to km/h Get mph from user Apply conversion to km/h Return value to user % Input mph % Convert % Tell user mph = input(‘Enter the mph: ‘); kph = mph*1.609; s = [‘num2str(mph)’ mph = ‘,num2str(kph),’ km/h’]; disp(s);
57
Preallocating Loops and Arrays
Note that for and while loops that grow the size of a data structure each time through the loop can adversely affect performance and memory use. Repeatedly resizing arrays often requires that MATLAB spend extra time looking for larger contiguous blocks of memory and then moving the array into those blocks. You can often improve on code execution time by preallocating the maximum amount of space that would be required for the array ahead of time. Use the ones or zeros command to create an array equal to, or larger than, the size required.
58
Preallocating Arrays: Demo
Preallocation Testing Compute the sine of values ranging from 0 to 10 Loop method: Preallocated array method: Preallocating our y array ahead of time is more than 25 times faster than letting MATLAB dynamically grow the array in the loop!
59
Vectorizing Loops From the MATLAB Help System The MATLAB software uses a matrix language, which means it is designed for vector and matrix operations. You can often speed up your M-file code by using vectorizing algorithms that take advantage of this design. Vectorization means converting for and while loops to equivalent vector or matrix operations.
60
Vectorizing Loops: Demo
Speed Testing Loop method (see previous slides): Preallocation method (see previous slides): Vectorized method: The vectorized method is the fastest by far and is the way MATLAB is meant to be used!
61
Editor/Debugger
62
Using Debugger
63
Debugger Example
64
Debugger and Breakpoints
65
Debugger Example … continue
66
Code Checking with M-Lint
67
M-Lint Report
68
How to Measure Performance
Function cputime: returns the total CPU time (in seconds) used by your MATLAB application from the time it was started >> t = cputime; % code to be tested >> cputime - t Tic ja toc: the tic command starts a stopwatch timer, MATLAB executes the block of statements, and toc stops the timer Profiling tool profile: For each M-function, or MEX-function in the file, profile records information about execution time, number of calls, parent functions, child functions, code line hit count, and code line execution time. As an alternative to the profile function, select Desktop > Profiler to open the Profiler
69
Functions tic & toc The simples way to measure performance is using stopwatch timer: tic … toc. Example: measure the time spent in a for loop: tic; t=-2:.001:2; r=[ ]; s=[ ]; for (x=t) y=1+x^3+x^2; r=[r x]; s=[r y]; end toc function [r,s] = aika % see next slide t=-2:.001:2; r=[ ]; s=[ ]; for (x=t) y=1+x^3+x^2; r=[r x]; s=[r y]; end
70
Execution Time: The profiler
Profile execution time for function >> profile on -detail builtin; % records information about execution time, number of calls, % parent functions, child functions, code line hit count, % and code line execution time. % More information: help profile. >> [r,s]=aika; % Run the function code. >> profile report % Report in HTML format. >> profile viewer % Report in graphical format. >> profile off % Stops the Profiler. As an alternative to the profile function, select Desktop > Profiler to open the Profiler.
71
More Programming Demos
Some programming demos are available on the course web-page:
72
The rest of the course material is not required
That’s all. The rest of the course material is not required in examination.
73
L18: Handle Graphics Handle Graphics Animations Guide (GUI Tool)
Image Processing
74
Handle Graphics MATLAB uses a hierarchical graphics model
Graphics objects organised according to their dependencies: e.g. lines must be plotted on axes, axes must be positioned on figures Every object has a unique identifier, or handle Handles are returned by creating function ax(n)=subplot(3,2,n) h=plot(x,y) Handles can be used to identify an object in order to inspect (get) or modify (set) its properties at any time
75
Object Hierarchy root figure axes UI-control UI-menu UI-contextmenu
line light image patch surface rectangle text
76
Graphics Objects Each graphics object has properties that can be modified, e.g. for a line object: colour, width, line style, marker style, stacking order on plot,… Many properties can be modified via the figure window. Tools available depend upon the version running – greatly expanded in version 7. More useful to use command line – much faster, and can be included in scripts or functions to automate whole process.
77
Handle Graphics and Figure Window
Each object in a figure window is assigned and identified by a number called its handle. Objects are related through a hierarchy. Objects have a set of default properties. The properties may be changed using set().
78
Graphics Objects: Figure Windows
Object select Add/edit text zoom Add arrow & line 3D rotate
79
Examples of Graphics Objects
Figure Object UIControl Objects UIMenu Surface Patch Text
80
Graphics Objects: Object Handle
Properties of an object with handle H, can be inspected/modified by: >> value = get(H,'propertyname') >> set(H,'propertyname',value) All property values echoed to screen by: >> get(H) Three useful functions: gcf : get current figure – returns handle of current figure gca : get current axes – returns handle of current axes gco : get current object – returns handle of current object Can use these directly, instead of the handle.
81
Graphics Objects: Example
Current object is last created (usually), or last object clicked on with mouse. >> pp = get(gca,'position') pp = >> set(gca,'position',pp+[ ]) The code above first gets the position of the current axes – location of bottom left corner (x0, y0), width (dx) and height (dy) (in normalised units) – then resets the position so that the axes sit 0.1 units higher on the page and decreases their height by 0.1 units.
82
Graphics Objects: Example … continue
dy axis 'position' within the figure: (default units are 'normalized') dx x0 Figure's 'position' on screen is [x0 y0 dx dy] (default units are pixels) y0
83
Graphics Objects: Example … continue
axis position within the figure: it's 'position' (default units are 'normalized') Figure's default position on the page: it's 'paperposition' (default 'paperunits' are 'centimeters') A4 page
84
Parameter value pairs Many basic plotting commands accept parameter-value pairs to specify plotting characteristics: plot(x,y,'para1',value1,'para2',value2,…) Commonly used parameters : values 'linewidth' : in points, numeric (default =0.5) 'color' : 'r','g','b','c','k','m','y' – basic colours (strings) : [R,G,B] – red, green, blue components Range from 0 to 1 (0 to 100%), eg [0,0.5,1] 'marker' : shape of marker/symbol to plot '.' point, 'v' triangle, '^' triangle(up pointing),… 'markeredgecolor','markerfacecolor' : edge and body colours of plotting symbols 'markersize' : marker size in points (default = 6)
85
Adding Text to Figures Basic axis labels and title can be added via convenient functions: >> xlabel('x-axis label text') >> ylabel('y-axis label text') >> title('title text') Legends for line or symbol types are added via the legend function: >> legend('line 1 caption','line 2 caption',…) >> legend([h1,h2,…],'caption 1','caption 2',…)
86
Adding Text to Figures MATLAB uses a subset of TEX commands for mathematical symbols, greek characters etc. Text may be added at any location via the commands: >> text(x,y,'text to add') – adds text at the specified location (in data coordinates – locations outside the current axes limits are OK) >> gtext('text to add') – adds text at a location selected with the cursor
87
Example: Handle Graphics
>> clear; % puhdistetaan työtila >> close all; >> x= 0:.1:pi; % määritellään hilapisteet >> y1 = sin(x); % lasketaan piirrettävät funktiot >> y2 = cos(x); >> y3 = tan(x); >> figure(1) % määritellään ikkuna >> subplot(2,2,1) % määritellään kuvan paikka
88
Example ... continue >> h = plot(x,y1,x,y2,x,y3) % piirretään kuvaajat >> set(h,'LineWidth',2,... {'LineStyle'},{'--';':';'-.'}) % muokataan ulkoasua >> set(h,{'Color'},{'r';'g';'b'}) >> axis([0 pi -1 1]) >> set(gca,'XTick',[ ]) >> grid on % selitystekstejä >> xlabel('X') >> ylabel('Y') >> legend(h,'sin','cos','tan', 3) >> title(’\bf Trigonometric functions') >> [y,ix] = max(y1); >> text(x(ix),y,'Maximum \rightarrow',... 'HorizontalAlignment','right')
89
Example ... continue >> subplot(2,2,2)
>> plot(x,y1,'r--','LineWidth',2) >> title('Sine-function') >> axis([0 pi -1 1]) >> subplot(2,2,3) >> plot(x,y2,'g:','LineWidth',2) >> title(’Cosine-function') >> subplot(2,2,4) >> plot(x,y3,'b-.','LineWidth',2) >> title('Tangent-function') >> print -deps kuva1.eps % save figure into a file
90
Specialized Plotting Routines
91
3-D Meshes and Surfaces
92
3-D Meshes and Surfaces
93
Images [x,map]=imread('flowers.tif'); image(x) colormap(map)
a = magic(4); image(a); map = hsv(16); colormap(map) colorbar
94
Animation On the Fly Animation Frame by Frame Animation
95
Animation Matlab provides two ways of generating moving,
animated graphics: On the fly - Continually erase and then redraw the objects on the screen, making incremental changes with each redraw. Frame by frame capture and playback - Save a number of different pictures and then play them back as a movie.
96
Animation and Graphics Commands
line() % Create line object set() % Update object attributes drawnow() % Update figure window clock % Return current time etime() % Return elapsed time
97
On the Fly Animation Example for on the fly animation:
t = 0:0.01:10*pi; x = t.*sin(t); y = t.*cos(t); axislimits = [min(x) max(x) min(y) max(y) min(t) max(t)]; line_handle = plot3(x(1), y(1),t(1),'ko‘, … 'MarkerFaceColor',[ ], 'MarkerSize',12); set(line_handle, 'erasemode','xor'); axis(axislimits); grid on for i = 2:length(x) set(line_handle, 'xdata',x(i), 'ydata', y(i), 'zdata', t(i)); drawnow; end
98
Frame by Frame animation
Example for frame by frame movie creation and playing: [x,y] = meshgrid([-10:0.5:10]); for j = 1:15 z = bessel(0, (j-1)*0.2 + sqrt(x.^2 +y.^2)); surf(x,y,z) axis([ ]) M(j) = getframe; end frame_order = [1:15 14:-1:1]; number_repeats = 5; movie(M, [number_repeats frame_order]);
99
Example 1: Real Time Animation
nframes = 500 n = % pisteiden lukumäärä s = % liikkeen nopeusaskel x = rand(n,1)-0.5; y = rand(n,1)-0.5; h = plot(x,y,'.') axis([ ]) axis square grid off set(h,'EraseMode', 'xor', 'MarkerSize', 18) % Animaatio alkaa k = 0 while k < nframes k = k + 1 drawnow x = x + s*randn(n,1) y = y + s*randn(n,1) set(h, 'XData', x, 'YData', y) end
100
Example 2: Animation Using movie Function
>> nframes = 50 >> n = 20 >> x = rand(n,1)-0.5; >> y = rand(n,1)-0.5; >> h = plot(x,y,'.') >> set(h, 'MarkerSize', 18); >> axis([ ]) >> axis square >> grid off >> M = moviein(nframes); >> for k = 1:nframes >> x = x+s*randn(n,1); >> y = y+s*randn(n,1); >> set(h, 'XData',x, 'YData', y); >> M(:,k) = getframe; >> end >> movie(M);
101
Example 3: Brownian Motion
% Specify a number of points n =20; % Specify temperature or velocity. s=0.02; % Generate n random points with (x,y) coordinates between -1/2 and +1/2 x = rand(n,1)-0.5; y = rand(n,1)-0.5; % Plot the points in a square with sides at -1 and +1. figure(5); h = plot(x,y,'.'); axis([ ]) xlabel('X-Axis') ylabel('Y-Axis') title('Simulation of a Brownian Motion') axis square
102
... continue % grid off is the command to supress the grid grid off
set(h,'EraseMode','xor','MarkerSize',18) % Now begin the animation. fprintf('Wait until the animation is over.\n\n') temp = 1; while temp < 5000 drawnow x = x + s*randn(n,1); y = y + s*randn(n,1); set(h,'XData',x,'YData',y) temp = temp+ 1; end
103
GUIDE GUIDE is MATLAB’s Graphics User Interface (GUI)
Design Environment . GUIDE stores GUIs in two files, which are generated the first time you save or run the GUI: – .fig file - contains a complete description of the GUI figure layout and the components of the GUI. Changes to this file are made in the Layout Editor. – .m file - contains the code that controls the GUI. You can program the callbacks in this file using the M-file Editor
104
Creating a GUI Typical stages of creating a GUI are:
1. Designing the GUI 2. Laying out the GUI – Using the Layout Editor 3. Programming the GUI – Writing callbacks in the M-file Editor 4. Saving and Running the GUI
105
GUIDE: The Layout Editor
The Layout Editor looks like this:
106
Hands-On GUIDE Example
Example:
107
Writing Callbacks A callback is a sequence of commands that are execute when a graphics object is activated • Stored in the GUI’s M-file • Is a property of a graphics object (e.g. CreateFnc, ButtonDwnFnc, Callback, DeleteFnc) • Also called event handler in some programming languages A callback is usually made of the following stages: 1. Getting the handle of the object initiating the action (the object provides event / information / values) 2. Getting the handles of the objects being affected (the object that whose properties are to be changed) 3. Getting necessary information / values 4. Doing some calculations and processing 5. Setting relevant object properties to effect action
108
Writing Callbacks: Example
Callback from example: % --- Executes on button press in plot_button. function plot_button_Callback(hObject, eventdata, handles) % hObject handle to plot_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get user input from GUI f1 = str2double(get(handles.f1_input,'String')); f2 = str2double(get(handles.f2_input,'String')); t = eval(get(handles.t_input,'String')); % Calculate data… % Create frequency plot axes(handles.frequency_axes) % Select the proper axes axes(handles.frequency_axes) % Select the proper axes plot(f,m(1:257)) xlabel('Frequency'); set(handles.frequency_axes,'XMinorTick','on') grid on…
109
Further Information The Mathworks, Using Matlab Graphics The Mathworks, Creating Graphics User Interfaces The documents from Mathworks could be found on: Hands-On GUIDE Example:
110
Video Demo: Simple GUI
115
Programming Demos A Simple Sorting Program (Bubble Sort)
Bisection Method Trapezoidal Rule Gaussian Elimination Method Newton-Raphson Method 2D Ising Model A Simple GUI (also demo video)
116
Bubble Sort Algorithm Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list.
117
Bubble Sort Program
118
Function bisect function c = bisect(fn,a,b,tol) % BISECT: % Usage: c = bisect('fn',a,b,tol) % This function locates a root of the function fn on the interval % [a,b] to within a tolerance of tol. It is assumed that the function % has opposite signs at a and b. % Evaluate the function at the endpoints and check to see if it % changes sign. fa = feval(fn,a); fb = feval(fn,b); if fa*fb >= 0 error('The function must have opposite signs at a and b') end % The flag done is used to flag the unlikely event that we find % the root exactly before the interval has been sufficiently reduced. done = 0;
119
Function bisect … continue
% Bisect the interval c = (a+b)/2; % Main loop while abs(a-b) > 2*tol & ~done % Evaluate the function at the midpoint fc = feval(fn,c); if (fa*fc < 0) % The root is to the left of c b = c; fb = fc; elseif (fc*fb < 0) % The root is to the right of c a = c; fa = fc; else % We ended on the root done = 1; end
120
Using Function bisect >> fcn = inline( ’ sin(x.*x)’ ); Assuming that the file is named bisect.m, it can be run as follows: >> x = bisect('fcn',1,2,1e-6) x = >> sqrt(pi)-x ans = e-07 The help command will print the first comment block from an m-file: >> help bisect BISECT: c = bisect('fn',a,b,tol) This function locates a root of the function fn on the interval [a,b] to within a tolerance of tol. It is assumed that the function has opposite signs at a and b.
121
Integrating a Function Numerically: Trapezoidal Rule
122
Numerical Integration of Arbitrary f(x)
123
Numerical Integration of Arbitrary f(x)
124
Demos More programming demos are available on the course web-page:
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.