Matlab
Matlab
Matlab
Resources: intro 1. Matlab Primer: short and clear introduction. 2. Matlab on Athena (MIT computer services web page). 3. www.mathworks.com, Matlab: detailed online documentation. medium level 4. Matlab Guide D.J.Higan,N.J.Higan, SIAM, 2000. Intro to Matlab 6.0. more advanced 5. Numerical Methods with Matlab, G. Recktenwald, Prentice Hall. 6. Mastering Matlab 6, D.Hanselman, B.Littlefield, Prentice Hall 2001, comprehensive tutorial & reference. also 7. Lecture notes: 10.001 web page.
October-November 2002
Comparison with C.
Syntax is similar Language structure is similar to C:
MATLAB supports variables, arrays, structures, subroutines, files MATLAB does NOT support pointers and does not require variable declarations MATLAB has extra built-in tools to work with matrices/arrays
October-November 2002
MATLAB desktop (version 6): 1) Command window 2) Launch Pad / Workspace window 3) Command history / Current Directory window
October-November 2002
Workspace Maintenance
all the assigned variables reside in the workspace clear all - clears all the memory (workspace) clear xyz - removes xyz from the memory who - lists all the variables from the workspace whos - also gives the details
are: c2 Bytes 8 16 64 Class double array double array(complex) double array(complex)
>> who Your variables ans c1 >> whos Name Size ans 1x1 c1 1x1 c2 2x2
October-November 2002
Workspace Maintenance
save saves all workspace variables on disk in file matlab.mat save filename x y z - x, y, z are saved in file filename.mat load filename - loads contents of the filename.mat to the workspace load filename x y z - loads only x, y, z from filename.mat to the workspace Each array requires a continuous chunk of memory; use pack for memory defragmentation.
October-November 2002
Linear Algebra
Vector: an ordered set of real or complex numbers arranged in a row or column.
y = [ y1
y2 L yn ]
n-element row-vector (1 x n)
October-November 2002
Vector Operations
Addition/subtraction (element-wise, array operation: c = a + b ci = ai + bi, i = 1,,n d = a - b ci = ai - bi, i = 1,,n Multiplication/division by a scalar: b = a bi = ai b = a/ bi = ai/ Vector transpose, turns row into column and vise versa: x = [1, 2, 3] xT =
x1 x 2 x3
(xT)T = x
October-November 2002
Vector Operations
Vector inner (dot, scalar) product (vector/matrix operation): n a = x .y
a=
xi yi
i =1
a = yT . xT
x is a row vector
Vector Operations
Outer (tensor) product:
y1 y M = yx = 2 [x1 y3 y4 y1 x1 y x x4 ] = 2 1 y3 x1 y4 x1 y1 x2 y 2 x2 y3 x 2 y 4 x2 y1 x3 y2 x3 y3 x3 y4 x3 y1 x4 y 2 x4 y3 x 4 y 4 x4
x2
x3
Mij = xiyj
October-November 2002
Vector Norms
To compare two vectors a vector norm (analogous to length, size) is introduced: ||x||>||y|| norm of x is greater than norm of y Euclidian norm, length in nD (also called L2 norm): ||x||2 = (x12 + x22 + x32 + + xn2)1/2 ||x||1 = |x1| + |x2| + |x3| + + |xn| ||x||inf. = max(|x1|, |x2|, |x3|, |xn|) ||x||p = (x1p + x2p + x3p + + xnp)1/p
October-November 2002
(L1) (Lp)
A = [1 or A=[1 2 4 5 7 8
2 3; 4 5 6; 7 8 9] 3 6 9]
Spaces separate the elements, semicolons and new line symbols separate the rows.
October-November 2002
} }
Matrix Multiplication
Product of the two matrices A(nxm) and B(mxl) is matrix C(nxl):
Conjugate transpose: swaps the indices and changes the sign of imaginary part of each element. C = A C(i,j) = real( A(j,i) ) - i * imag( A(j,i) )
October-November 2002
Logical:
October-November 2002
Flow of Control
For loops. Syntax: for x = array (commands) end Example: >> for n = 1:10 x(n) = sin(n*pi/10); end
October-November 2002
Flow of Control
Nested loops, decrement loop. >> for n = 1:5 for m = 5:-1:1 A(n,m) = n^2 + m^2; end end Alternative: vectorized solution, much faster: assigns memory for x only once. >> n = 1:10; >> x = sin(n*pi/10)
October-November 2002
Flow of Control
While loops. Syntax: while expression (commands) end (commands) will be executed as long as all the elements of expression are true. Example: search for the smallest number EPS which if added to 1 will give the result greater than 1.
October-November 2002
Flow of Control
>> num = 0; EPS = 1; >> while (1+EPS)>1 EPS = EPS/2; num = num+1; end >> num num = 53 >> EPS = 2*EPS EPS = 2.2204e-16
October-November 2002
Flow of Control
If-Else-End constructions. Syntax: if expression1 (commands1: if expr-n1 is true) elseif expression2 (commands2: if expr-n2 is true) elseif expression3 (commands3: if expr-n3 is true) . . . . . . . . . . . . . . else (commands: if 1,2,..,n are false) end
October-November 2002
Flow of Control
Breaking out of the loop: >> EPS = 1; >> for num = 1:1000 EPS = EPS/2; if (1+EPS)<=1 EPS = EPS*2 break end end EPS = 2.2204e-16
October-November 2002
M-files
Script files & Function files Script files: contain a set of Matlab commands - programs. To execute the file: enter the file name.
% script M-file example.m comment line erasers = 4; pads = 6; tapes = 2; items = erasers + pads + tapes cost = erasers*25 + pads*52 + tapes*99 average_cost = cost/items >>example items = 12 cost = 610 average_cost = 50.833
October-November 2002
M-files
Interpreter actions while processing example statement: 1. Is example a current Matlab variable? 2. Is example a built-in Matlab command? 3. Is example an M-file? 4. Opens the file and evaluates commands as if they were entered from the command line. (i) all workspace variables are accessible to the commands form the M-file. (ii) all variables created by M-file will become a part of the workspace if declared global.
October-November 2002
M-files
Function files Analogous to functions in C. Communicate with the workspace only through variables passed to it and the output variables it creates. All internal variables are invisible to the main workspace. M-files name = functions name. The first line - function-declaration line function keyword output variable function name expected input arguments
function
October-November 2002
s=area(a,b,alpha)
Function M-files
function s=area(a,b,alpha) % AREA calculates triangles area given 2 sides & angle between them % AREA reads in two sides of the triangle and the angle between them % (in radians) and returns the area of the triangle. if a < 0 | b<0 error(a and b can not be negative.) end s = a*b*sin(alpha)/2;
searched and displayed by the lookfor command searched and displayed by the help command
Function M-files
Function M-files may call script files or other (sub)functions, the script file/subfunction being evaluated in the functions workspace. Function M-files may have zero input and output arguments. Functions may share variables. The variable must be declared as global in each desired workspace.
October-November 2002
Graphics
Each graph is created in a figure window By default only one figure window can be opened, thus the second graph will replace the first one To create a graph you run: Management functions (arranging the figure window(s)) Graph generation functions Annotation functions (formatting the graphs, optional)
October-November 2002
Graphics
Plotting functions: 3 categories
Management figure subplot zoom hold view rotated Generation 2-D plot polar fill plotyy 3-D plot3 surf, surf3 mesh, meshz contour, contour3 Annotation & characteristics xlabel, ylabel, zlabel text title legend box set grid
October-November 2002
Graphics management
figure(n) opens figure window number n, also makes window n default window; the new plot() command will replace the plot in the default window hold on holds the current window active, you may add curves using plot() command hold off releases the current window subplot(i,j,k) divides figure window into i x j array of sectors for plots; k number of the sector to put the plot in
October-November 2002
Graphics
Two-Dimensional Graphics: join-the-dots x-y plot >> x = [1.2 2.3 3.7 4.1 5.0 7.3]; >> y = [2.6 2.8 3.7 4.0 4.3 5.6]; >> plot(x,y) Syntax: plot(x,y,string). String (optional) stands for color, marker and plot style. Example: r*-- -red, asterisk at each data point, dashed line. Colors: r, g, b, c, m, y, k, w. Line styles: - solid, -- dashed, : dotted, -. dash-dot.
October-November 2002
Graphics
Plotting many curves: plot(x,y,r-,a,b,g--,.) Some other control strings: LineWidth,2,MarkerSize,7, MarkeFaceColor,r,... plot( ) -> loglog( ) changes lin-lin plot to log-log one.
October-November 2002
Graphics
Labels and title: xlabel(concentration) ylabel(viscosity) title(C() plot, PEO - H2O solution.) Axes: axis([xmin xmax ymin ymax]), xlim([xmin xmax]),axis tight, grid on, axis square, Also go to edit option of the plot window.
October-November 2002
Graphics
Adding text box at the position (x,y): text(x,y,here is the text); Multiple plots in a Figure: subplot(k,m,1), plot() subplot(k,m,2), plot() subplot(k,m,k*m), plot() k, m - number of lines and columns in the array of plots, 1,2,k*m - number of the plots in the array.
October-November 2002
Graphics
plot([x1 x2],[y1 y2]) plots a straight line form (x1,y1) to (y1,y2) Lets plot a set of straight lines: connecting (x1j,y1j) and (x2j,y2j) for j=1,,n. The plot instruction will be: plot([x1;x2],[y1;y2]). Say, x1=[1 3 5]; x2=x1; y1=[0 0 0]; y2=[3 6 2]; 3 vertical lines will be plotted.
October-November 2002
Three-dimensional Graphics
The 3D version of plot is: plot3(x1,y1,z1,S1,x2,y2,z2,S2,) 3 coordinates, control string, 3 coordinates... Example: sin(x), cos(x), x. Plots function of a function. plot3([x1;x2],[y1;y2],[z1;z2]) Arguments vectors of n elements each. x1, x2 store xcoordinates of the points, where lines 1,,n begin and end correspondingly, y1, y2 and z1, z2 do the same for y and z coordinates.
October-November 2002
Three-dimensional Graphics
3D, scalar functions of 2 variables, mesh plots: z = f(x,y) Plot of f(x,y) - surface in 3-d. 1. Create a mesh in x-y plane: >> x = x0:x1, y = y0:y1 >>[X, Y] = meshgrid(x,y) x has m and y has n elements, X & Y - matrices nxm, X consists of n row vectors x, Y of m column vectors y. Each pair X(i,j) & Y(i,j) gives coordinates in x-y space.
October-November 2002
Three-dimensional Graphics
X & Y may be treated as matrices or arrays. If z = f(x,y) = 3(x2+y)3: >>Z=3*(X.^2+Y).^3 % Matrix Z is created >>mesh(X,Y,Z)% Draws mesh plot of f(x,y) meshc - draws the underlying contour plot meshz - meshplot with zero plane surf(X,Y,Z) - surface plot: surface between the mesh points is filled in; surf(x,y,Z) and surf(Z) also work, same is true for mesh command. >>Z=X.^4+3*X.^2-2*X+6-2*Y.*X.^2+X.^2-2*Y;
October-November 2002