












































































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!













































































MATLAB Programming
This window is the default layout of the MATLAB desktop. It is a set of tools for managing files, variables, and applications associated with MATLAB. The Command Window is used to enter MATLAB functions at the command line prompt >>. The Command History Window is used to view or execute previously run functions. The Current Directory/Workspace Window lists the foloders/files in the Current Directory (where you are working) or the values and attributes of the variables you have defined. The START button at the lower left gives you quick access to tools and more. The Current Directory line at the top tells you where MATLAB thinks your files are located. This should always point to the folder that you are working in so that your files are saved in your own directory. An examples would be to enter the pathname/ Users/Physics50/MATLAB/yourname or use the ... button to browse for a folder. This should always be done at the start of a new session. When you open a MATLAB document, it opens in the associated tool. If the tool is not already open, it opens when you open the document and appears in the position it occupied when last used. Figures open undocked, regardless of the last position occupied. How to open a document depends on the document type: M-file: Select File -> Open and select the M-file. It opens in the Editor/Debugger. Workspace variable: In the Workspace browser, double-click the variable. It opens in the Array Editor. At startup, MATLAB automatically executes the master M-file MATLABrc.m and, if it exists, startup.m. The file MATLABrc.m, which is in the local directory, is reserved for use by The MathWorks, and by the system manager on multiuser systems. The file startup.m is for you to specify startup options. For example, you can modify the default search path, predefine
The "e" notation is used for very large or very small numbers: -1.3412e+03 = -1.3412x10^3 =-1341. -1.3412e-01 = -1.3412x10-1^ =-0. All computations in MATLAB are done in in double precision, which means 15 significant figures. The format - how MATLAB prints numbers - is controlled by the "format" command:
a=pi (pi is a built-in constant) a = 3. format short e a a = 3.1416e+ format long e a a = 3.141592653589793e+ format long a a = 3. format short {this is the default format} a a = 3.
Variable Names Legal names consist of any combination of letters and digits, starting with a letter. Allowed: NetCost, Left2Pay, x3, X3, z25c Not allowed: Net-Cost, 2pay, %x, @sign Avoid these names: eps = 2.2204e-16 = 2-54^ = largest number such that 1 + eps is indistinguishable from 1 pi = 3.14159... = π Suppressing Output One often does not want to see the result of intermediate calculations. This can be accomplished by terminating the MATLAB statement with a semi-colon
x=-13; y=5+x, z=x^2+y y = - z = 161 Note that several statements can be placed on one line, separated by commas or semi-colons. Built-In Functions MATLAB has many built-in elementary functions, for example, sin, cos, tan, asin, acos, atan, atan sinh, cosh, tanh, asinh, acosh, atanh, sqrt, exp, log, log10, abs, sign, conj, imag, real, angle round, floor, fix, ceil, rem abs absolute value sqrt square root
rem remainder after division - rem(x,y)
1. Beginning to Use MATLAB MATLAB works with essentially only one kind of object a rectangular, numerical array of numbers, possibly complex, called a matrix In some situations, 1-by-1 matrices are interpreted as scalars and matrices with only one row or one column are interpreted as vectors. Matrices can be introduced into MATLAB in several different ways: - Entered by an explicit list of elements. - Generated by built-in statements and functions. - Created in M-files (MATLAB scripts). - Loaded from external data files. MATLAB contains no size or type declarations for variables. MATLAB allocates storage automatically, up to available memory. Vectors Vectors come in two flavors - row vectors and column vectors. In either case they are lists of numbers separated by either commas or spaces. The number of entries is known as the "length" of the vector and the entries are called "elements" or "components" of the vector. The entries must be enclosed by square brackets.
v = [1 3, sqrt(5)] v = 1.0000 3.0000 2. length(v) ans = 3 v2 = [3+ 4 5] v2 = 7 5 v3 = [3 +4 5] {spaces can be very important } v3 = 3 4 5
v+v3 {arithmetic can be done with vectors of the same length} ans = 4.0000 7.0000 7. v4 = 3v v4 = 3.0000 9.0000 6. v5 = 2v -3*v v5 = 7.0000 -6.0000 -10. v+v
??? Error using ==> plus Matrix dimensions must agree. In all vector arithmetic with vectors of equal length, the operations are carried out element-wise.
w = [1 2 3], z = [8 9] {build vectors from existing vectors} w = 1 2 3 z = 8 9 cd=[2*z,-w], sort(cd) {sort is a MATLAB command} cd = 16 18 -1 -2 - ans = -3 -2 -1 16 18 {in ascending order} w(2) = -2, w(3) {change or look at particular entries} w = 1 -2 3 ans = 3 The Colon Operator This a shortcut for producing row vectors. 1: ans = 1 2 3 4
c2 = [ 4 5] c2 = 3 4 5 c3 = 2c-3c2 {arithmetic OK if same length} c3 = -7. -6. -10. Transposing Transposing is the process of converting between row and column vectors. It is denoted by '. w = [1 -2 3] w = 1 -2 3 w' ans = 1
c=[1; 2; 3] c = 1 2 3 c' ans =1 2 3 x=[1+3i,2-2i] x = 1.0000 + 3.0000i 2.0000 - 2.0000i x' {give complex conjugate}
ans = 1.0000 - 3.0000i 2.0000 + 2.0000i
x.' {give transpose for complex vector} ans = 1.0000 + 3.0000i 2.0000 - 2.0000i Plotting Elementary Functions Suppose that we want to plot a graph of y = sin3πx for 0≤x≤1. We do this by sampling the function at a sufficiently large number of points and joining up the points (x,y) by straight lines. Suppose that we take N+1 points equally space a distance h apart: N=10; h=1/N; x=0:h:1; defines the set of points x=0,h,2h,....,1-h,1. The corresponding y-values are computed by y=sin(3pix); and finally, we plot the points with plot(x,y) The result is shown in the figure below where it is clear that the value of N chosen above is too small.
There are more plot symbols available. Use help plot or help shapes Multi-plots or several graphs on the same figure can be drawn using
plot(x,y,'r-',x,cos(3pix),'g--') A descriptive legend may be included with legend('Sin curve','Cos curve') which will give a list of line-styles, as they appeared in the plot command followed by a brief description. MATLAB places the legend on the graph. If the position is not convenient it can be moved around with the mouse. If we add title('Multi-plot') xlabel('x-axis') ylabel('y-axis') grid the final plot looks like
A call to plot clears the graphics window before plotting the current graph. This is not convenient if we want to add further graphics to the figure at some later stage. To stop the window being cleared:
plot(x,y,'r-'), hold Current plot held plot(x,0.5*y,'gx'), hold off " hold on " holds the current picture; " hold off " releases it (but does not clear the window, which can be done with the command clf ). " hold " on its own toggles the hold state. To obtain a printed copy of the figure use the command: print -f1 {f1 = figure 1} Alternatively, you can save the figure to a file for later printing (using another application) or editing. For example the following commands save the window as TIFF files with resolutions 300 DPI and 600 DPI respectively. print -dtiff -r300 test300.tiff print -dtiff -r600 test600.tiff
We often need to "zoom in" on some portion of a plot in order to see more detail. This is easily achieved using the command
zoom Pointing the mouse to the relevant position on the plot and clicking the mouse will zoom in by a factor of two. Clicking on the mouse while holding the command key down give a menu of options allowing restoration of the original figure or zooming out. zoom off turns off the zoom capability. The command clf clears the current figure window. The command close 1 closes the window labeled "Figure 1". To open a new figure window type figure or to get a window labeled "Figure 9", for example, type figure (9). If "Figure 9" already exists then this command will bring the window to the foreground and all subsequent plotting commands will be drawn in it. Once a plot has been created in the graphics window you might want to change the range of x and y values shown on the picture. clf, N = 100; h = 1/N; x = 0:h:1; y = sin(3pix); plot(x,y) axis([-0.5 1.5 -1.2 1.2]), grid The axis command has four parameters, the first two are the minimum and maximum values of x to use on the axis and the last
two are the minimum and maximum values of y to use on the axis. Note the square brackets. Script Files Script files are normal ASCII (text) files that contain MATLAB commands. It is essential that such files have names having an extension .m (e.g., scriptname.m) and, for this reason, they are commonly known as m-files. The commands in this file may then be executed using
scriptname Note: the command does not include the file name extension .m. It is only the output from the commands (and not the commands themselves) that are displayed on the screen. Script files are created with your favorite text editor such as BBEdit or TextWrangler. Type in your commands and then save (to a file with a .m extension. To see the commands in the command window prior to their execution: echo on and echo off will turn echoing off. Any text that follows % on a line is ignored. The main purpose of this facility is to enable comments to be included in the file to describe its purpose. In MATLAB, there are two types of script files, namely, programs and functions. We will discussion both of these types later. Products, Division and Powers of Vectors Scalar Product ()* We shall describe two ways in which a meaning may be attributed to the product of two vectors. In both cases the vectors concerned must have the same length. The first product is the standard scalar product. Suppose that u and v are two vectors of length n, u being a row vector and v a column vector:
An error results because w is not a column vector. Recall from earlier that transposing (with ') turns column vectors into row vectors and vice versa. So, to form the scalar product of two row vectors or two column vectors,
uw' % u and w are row vectors ans = 45 uu' % u is a row vector ans = 365 v'*z % v and z are column vectors ans = - We shall refer to the Euclidean length of a vector as the norm of a vector; it is denoted by the symbol u and defined by u = ui 2 i = 1 n
where n is its dimension. This can be computed in MATLAB in one of two ways:
[sqrt(uu'),norm(u)] ans = 19.1050 19. where norm is a built{in MATLAB function that accepts a vector as input and delivers a scalar as output. Dot Product (.) The second way of forming the product of two vectors of the same length is known as the Hadamard product. It is not often used in Mathematics but is an invaluable MATLAB feature. It involves vectors of the same type. If u and v are two vectors of the same type (both row vectors or both column vectors), the mathematical definition of this product, which we shall call the dot product, is the vector having the components
The result is a vector of the same length and type as u and v. Thus, we simply multiply the corresponding elements of two vectors. In MATLAB, the product is computed with the operator .* and, using the vectors w, z defined earlier
w.w ans = 4 1 9 w.z' ans = 14 6 15 Dot Division of Arrays (./) There is no mathematical definition for the division of one vector by another. However, in MATLAB, the operator ./ is defined to give element by element division|it is therefore only defined for vectors of the same size and type. a = 1:5, b=6:10, a./b a = 1 2 3 4 5 b = 6 7 8 9 10 ans = 0.1667 0.2857 0.3750 0.4444 0. a./a ans = 1 1 1 1 1 c = -2:2, a./c c = -2 -1 0 1 2 Warning: Divide by zero. ans = -0.5000 -2.0000 Inf 4.0000 2. The previous calculation required division by 0 - notice the Inf , denoting infinity, in the answer.