Outline 110112 NatSciLab - Numerical Software Introduction to MATLAB Onur Oktay Jacobs University Bremen Spring 2010
Outline 1.m files 2 Programming Branching (if, switch) Loops (for, while) 3 Anonymous functions 4 Basic Graphing Curve plotting (plot,plot3,contour) Surface plotting (surf, mesh) 5 Efficient coding - Vectorization
Outline 1.m files 2 Programming Branching (if, switch) Loops (for, while) 3 Anonymous functions 4 Basic Graphing Curve plotting (plot,plot3,contour) Surface plotting (surf, mesh) 5 Efficient coding - Vectorization
.m files An m-file is a plain text file that contains MATLAB commands, with the filename extension.m. There are 2 types of m-files, scripts and functions. You can start an m-file by typing >> edit filename An m-file should be saved in the current directory or in the path in order to be executed. The path is just a list of directories in which MATLAB will look for files. Use editpath command to see and change the path. There is no need to compile m-files.
Script.m files The contents of a script m-file are literally interpreted as if they were typed at the prompt. If you want to repeat a group of lines various times, it is more convenient to write and save those lines in a script than using the prompt. Type >> run filename at the command line to run the script filename.m Some good reasons to use scripts are - Revising a group of more than four or five lines. - Reproducing your work at a later time. - Running a CPU-intensive job in the background.
Function.m files Function m-files are used to write and store often complicated numerical functions. Each function starts with a line such as function [out1,out2] = myfun(in1,in2,in3) The variables in1, in2, in3 are input arguments, and out1, out2 are output arguments. You can have as many input and output arguments as you like. Most of the functions built into MATLAB (except core math functions) are themselves m-files, which you can read and copy.
Function.m files A simple example of a function m-file: quadformula.m function [x1,x2] = quadformula(a,b,c) d = sqrt(bˆ2-4 a c); x1 = (- b + d) / (2 a); x2 = (- b - d) / (2 a); On the prompt, type >> [r1,r2] = quadformula(1,-2,1) r1 = 1 r2 = 1
Function.m files - Subfunctions A single m-file may hold more than one function definition. The function header at the first line of an m-file defines the primary function. All others are subfunctions. function [x1,x2] = quadformula(a,b,c) % primary function d = discrim(a,b,c); x1 = (-b + d) / (2*a); x2 = (-b - d) / (2*a); end function D = discrim(a,b,c) % subfunction D = sqrt(bˆ2-4*a*c); end
Function.m files - defaults nargin: Number of input arguments. Set default values for the inputs that are not provided. nargout: Number of output arguments. Set default action if one or more outputs are not called. An example: sincab.m function y = sincab(t,a,b) if nargin< 2; a=1; end % default value a=1 if nargin< 3; b=2; end % default value b=2 y = sin(t.ˆa)./(t.ˆb); if nargout==0; % default action: plot if no output is called figure; plot(t,y); end end
Script or Function? Functions have their own local workspace. Scripts use the main workspace. Function Script Q1 No Yes Q2 No Yes Q1: Are the variables in the main workspace visible? Q2: When executed, do the variables created appear in the main workspace? Functions are faster than scripts. - Functions are compiled into memory when executed for the first time. Subsequent invocations skip this interpretation step. - No matter how many times you execute the same script, MATLAB must spend time parsing your syntax. Functions require all inputs and outputs to be stated. Use scripts for attention-free execution.
Outline 1.m files 2 Programming Branching (if, switch) Loops (for, while) 3 Anonymous functions 4 Basic Graphing Curve plotting (plot,plot3,contour) Surface plotting (surf, mesh) 5 Efficient coding - Vectorization
if/else structure if (condition 1 true) statement 1 elseif (condition 2 true) statement 2 elseif (condition 3 true) statement 3. else default statement end
factorialscript.m Example if isreal(x) % if x is not real error ( x cannot be a complex number ); elseif (x < 0) error ( x cannot be a negative number ); elseif (x > 1000) error( x is too large ); elseif (x > 0) & (x = round(x)) % if x is not equal to round(x) disp( decimal part of x will be ignored ); factorial = prod(1:x); else factorial = prod(1:x); end
switch/case structure switch variable case value1 statement 1 case value2 statement 2 case value3 statement 3. otherwise default statement end equivalent to if variable == value1; statement 1 elseif variable == value2; statement 2 elseif variable == value3; statement 3. else default statement end Note: Unlike the C language switch statement, the MATLAB switch does not fall through. If the first case statement is true, the other case statements do not execute.
switch/case switch mod(x,6) case 0 xnew = x/6; case {1, 5} xnew = xˆ2-1; case 4 xnew = x/2; otherwise xnew = xˆ2 + 2; end if (mod(x,6)==0) xnew = x/6; elseif (mod(x,6)==1) (mod(x,6)==5) xnew = xˆ2-1; elseif (mod(x,6)==4) xnew = x/2; else xnew = xˆ2 + 2; end
Loops: for & while structure for var = vector statement end Use if it is necessary to repeat the statement a fixed number of times. Example: find sum of all prime numbers < 100 x = 1:100; s = 0; for k = 1:100; s = s + x(k)*isprime(x(k)); end structure while (condition true) statement end Use if it is necessary to repeat the statement based on a condition. Example: find sum of all prime numbers < 100 x = 1; s = 0; while (x < 100) s = s + x * isprime(x); x=x+1; end
Loops: for & while Its a good idea to limit the number of repetitions to avoid infinite loops. Use for loops rather than while loops. Maxiter = 100; % Number of repetitions for n = 1:Maxiter x = pi sin(x); end Use break. A break immediately ends the loop, and jumps to the first line after the loop. n = 0; Maxiter = 100; % Number of repetitions while (err > 0.01) err = abs(pi sin(x) - x); x = pi sin(x); n = n+1; % loop counter if n>maxiter, break, end end
Outline 1.m files 2 Programming Branching (if, switch) Loops (for, while) 3 Anonymous functions 4 Basic Graphing Curve plotting (plot,plot3,contour) Surface plotting (surf, mesh) 5 Efficient coding - Vectorization
Anonymous functions We can quickly form functions at the command line. For example, let f(x) = 2e x x 2 cos(x) + 5x log(x) Usage g(x, y, z) = e xy/z y sin(z)/x + log(z). fhandle = @(argument list)(expression) >> f = @(x)( 2*exp(x) (x.ˆ2).*cos(x) + 5*x.*log(x) ); >> g = @(x,y,z)( exp(x.*y)./z y.*sin(z)./ x + log(z) ); Alternatively, we can use inline >> f = inline( 2*exp(x) (x.ˆ2).*cos(x) + 5*x.*log(x), x ); >> g = inline( exp(x.*y)./z y.*sin(z)./ x + log(z), x, y, z ); Make your functions array-smart by inserting a dot before *, /,ˆ
Anonymous functions We cannot add or multiply anonymous functions. >> f+f returns an error message. x is a numerical array f(x) is a numerical array. We can, for example >> x = ones(2,3); y = rand(2,3); >> sumfxfy = f(x)+f(y); prodfxfy = f(x).*f(y); We can form anonymous functions with outside parameters >> h = @(x)( a*cos(x) + b*sin(x)); >> h(2) returns an error message if a and b are not defined. >> a=0.3; b=0.5; h(2) Multiple anonymous functions can be used together. For example, if π F(x, t) = e u2 /t sin(x u)du, 0 we can >> F = @(x,t)( quad( @(u)(exp(-(u.ˆ2)./t).*sin(x-u)),0,pi) );
Outline 1.m files 2 Programming Branching (if, switch) Loops (for, while) 3 Anonymous functions 4 Basic Graphing Curve plotting (plot,plot3,contour) Surface plotting (surf, mesh) 5 Efficient coding - Vectorization
Some Graphing Commands Curve graphing commands plot ezplot: plot for anonymous functions. plot3: plot curves in 3D space. Surface graphing commands surf, mesh: surface graphing in 3D. ezsurf, ezmesh: surface graphing for anonymous functions. colorbar, colormap: show/change color scaling. pcolor: top view of a colored surface. contour, ezcontour: contour plot of surfaces Figure properties and annotation figure: open a new empty figure window. hold on, hold off, grid on, grid off subplot: multiple graphs in one figure. axis, xlim, ylim: axis limits. title, xlabel, ylabel: graph and axis labels. legend: display/edit the legend for graphs with multiple curves.
plot plot uses line segments to connect points given by two vectors of the same length. Usage plot(x,y, color-style-marker ) x is a vector of length N, which keeps the x-coordinates. y is a vector of length N, which keeps the y-coordinates. color-style-marker [OPTIONAL] is a string that gives the color, style, marker type of the plot. Default value is b, if not provided. if x & y doesn t have the same length, plot(x,y) causes an error message. y can be a r N array. In this case, plot(x,y) plots each row of y versus x. x must always be a vector.
plot Here is a simple example. >> t = pi*(0:0.02:2); >> plot(t,sin(t)) Suppose you want to put a marker at each data point. >> plot(t,sin(t), o ) Also draw a cosine curve, make it red to distinguish. >> plot(t,cos(t), r ) The sine curve is erased. hold on to keep the previously drawn graphs. >> plot(t,sin(t), o ) >> hold on >> plot(t,cos(t), r ) >> hold off You can plot multiple curves at once: >> figure % forms a new empty figure >> plot(t, [t; t.ˆ2; t.ˆ3] ) MATLAB automatically assigns different colors to the curves.
plot - color, line style, marker Type Values Meanings Values Meanings Color c cyan g green m magenta b blue y yellow w white r red k black Line - solid : dotted style dashed.- dash-dot Marker + plus mark ˆ filled upward triangle type o unfilled circle v filled downward triangle * asterisk > filled right-pointing triangle x letter x < filled left-pointing triangle s filled square p filled pentagram d filled diamond h filled hexagram
ezplot For anonymous functions, we use ezplot. Usage ezplot(f, [xmin xmax]) f is an anonymous function handle. xmin, xmax [OPTIONAL] are x-axis boundaries of the graph. % plots f=f(x) on the given interval % if f=f(x,y) of 2 variables, plots the curve given by f(x, y) = 0. ezplot(x,y, [tmin,tmax]) x,y are anonymous functions of a single common variable t. tmin, tmax [OPTIONAL] are the limits of t. % plots the parametric curve x=x(t), y=y(t) for t [tmin,tmax] For example, >> f = @(x)( exp(3*sin(x)-cos(2*x)) ); >> ezplot(f, [0 4] ) % plots of f on [0,4]. >> g = @(x,y)(x.ˆ4 + y.ˆ4-1); >> ezplot( g, [-1 1] ) % plots the contour g(x, y) = 0 on [-1,1].
subplot We use subplot to form a single figure with multiple graphs. Usage subplot(m,n,k) m: number of rows in the figure. n: number of columns in the figure. k: position of the graph in the figure. Counting is done from left right, top bottom. For instance, subplot(3,4,1) subplot(3,4,2) subplot(3,4,3) subplot(3,4,4) subplot(3,4,5) subplot(3,4,6) subplot(3,4,7) subplot(3,4,8) subplot(3,4,9) subplot(3,4,10) subplot(3,4,11) subplot(3,4,12)
subplot and annotation Example: >> t = pi*(0:0.02:2); f = t.*sin(t); >> f1= @(x)( sin(x) + x.*cos(x) ); >> subplot(2,2,1) % start working on the 1st cell in the figure >> plot(t,f) >> axis( [0 2*pi -5 2] ) % set axis limits >> title( Graph of f(t) = t sin(t) ); % sets a title to the graph >> xlabel( time ); ylabel( velocity ); % label the axes >> >> subplot(2,2,3) % start working on the 3rd cell in the figure >> ezplot(f1,[0 2*pi]) >> xlabel( time ); ylabel( acceleration ); >> subplot(2,2,[2,4]) % merge 2nd & 4th cells >> plot3(cos(t),sin(t),sin(3*t))
surf, mesh surf (mesh) forms a 3D shaded surface (wireframed mesh) from a matrix of z-coordinates by linear interpolation. Usage surf(x,y,z) Z is a matrix defining the z-coordinates of a surface. X,Y [OPTIONAL] are matrices defining the x,y-coordinates. mesh has the same usage. X & Y can be vectors, length(x) = n and length(y) = m, where [m,n] = size(z). the vertices of the surface faces are (X(j), Y(i), Z(i,j)) triples. To form X & Y matrices for arbitrary domains, use meshgrid
ezsurf, ezmesh For anonymous functions, use ezsurf (ezmesh) Usage ezsurf(f, [xmin xmax ymin ymax]) f is an anonymous function handle. xmin, xmax, ymin, ymax [OPTIONAL] are boundaries of the xy-plane. Default values xmin = ymin = -2*pi, xmax = ymax = 2*pi, if not entered % plots f=f(x,y) on the given interval ezsurf(x,y,z, [tmin,tmax,smin,smax]) x,y,z are anonymous functions of two common variables t,s. tmin, tmax, smin, smax [OPTIONAL] are the limits of t,s. Default values tmin = smin = -2*pi, tmax = smax = 2*pi, if not entered % plots the parametric surface x = x(s,t), y = y(s,t), z = z(s,t) for t [tmin,tmax], s [smin,smax] ezmesh has the same usage.
Example >> figure; ezsurf (@(x,y)sin(x.ˆ2+y), [0 pi 0 2*pi] ) >> f = @(x,y)( sin(x.ˆ2+y) ); >> x = pi*(0:0.02:1); y = 2*x; >> [X,Y] = meshgrid(x,y); % form a grid of points in the xy-plane >> Z = f(x,y); >> figure; surf(x,y,z) >> colorbar % display the colorbar in the figure >> colormap gray % change the color scaling The coloring is determined by shading in between the data points: >> shading flat >> shading interp
surf - shading flat shading: each face/ mesh line has constant color determined by one boundary point. interpolated shading: the color is determined by interpolation of the boundary values. It makes smoother pictures, but can be very slow to render, particularly on printers. faceted shading: uses flat shading for the faces and black for the edges.
Outline 1.m files 2 Programming Branching (if, switch) Loops (for, while) 3 Anonymous functions 4 Basic Graphing Curve plotting (plot,plot3,contour) Surface plotting (surf, mesh) 5 Efficient coding - Vectorization
How to make your code run faster: Vectorization: Rewrite loops by indexing and matrix operations. Because Matlab is optimized for matrix operations. Matlab s core strength is the efficient handling of vector and matrix operations. Loops slow down Matlab. Pre-allocate memory hhen forming large arrays/matrices. For example, use zeros to make a matrix of the desired size. Because, repeatedly resizing arrays requires that MATLAB spend extra time looking for larger contiguous blocks of memory and then moving the array into those blocks. Use built-in functions. Use functions rather than scripts. Because, a function is parsed into the memory at the first time it is executed/modified. A script is parsed one line at a time, each time it is executed. Parsing/interpretation require extra time.
Vectorization - Indexing Example: x is a vector and we want to compute a matrix D = [d ij ] such that d ij = e x i sin x j. The standard programming involves two nested loops. >> n = length(x); >> D = zeros(n); % preallocate memory for D >> for j = 1:n >> for i = 1:n >> D(i,j) = exp(x(i))*sin(x(j)); >> end >> end We can vectorize as follows. >> n = length(x); >> ind = ones(n,1)*(1:n); % forms an nxn index matrix. >> X = x(ind); >> D = exp(x).*sin(x. );
Vectorization - Index Masks Example: A is a numerical array/matrix. We want to set A ij = 0 if A ij < 0.05 The standard programming involves two nested loops. >> [m n] = size(a); >> for j=1:m >> for k=1:n >> if abs(a(j,k))<0.05, A(j,k)=0, end >> end >> end We can vectorize as follows. >> mask = (abs(a)>=0.05); % form a logical index mask >> A = A.*mask;
Recommended Reading Scientific Computing with MATLAB and Octave by Quarteroni & Saleri, Chapter 3, Sections 3.1 and 3.4.