Baixe o app para aproveitar ainda mais
Prévia do material em texto
Math 1322, Fall 2002 Introduction to Matlab: Basic Commands You should look at Sections 1.1-1.3 of the Matlab reference book ( byUsing Matlab in Calculus Gary Jensen), preferably with Matlab running in front of you. Do not worry about remembering each and every command. Try to get an overview of the basics and what topics are referred to in the book so you can return to them when needed. The material there will probably be easier to read if you go through these notes first. Availability Matlab is available on PC's in the Artsci Computing Center in Eads and in the Center for Engineering Computing. It should also be available on the computers at Cornerstone and in the Residential Computing Facilities. Starting Matlab on a PC If there is a Matlab icon on the desktop, double click on it If not, use the menus: Start, Programs, Matlab You will then be in the Matlab workspace where you can enter commands Quitting Matlab You can use the menus: File, Exit Matlab OR, just type: quit Help See p.1 of Using Matlab in Calculus Numbers, Arrays, Variables Matlab “thinks” in terms of numbers arraysand . For example a = [1 3 5 7] An array containing 4 numbers (called its or elements members or ). An array with a single row (or column)components is sometimes also called a . vector mostlyWe use arrays with just one row in Calculus I-II The same array in Matlab can also be entered with commas: a = [1,3,5,7] But when Matlab an array on screen, it always displays omits commas and brackets b = An array with 2 rows and 3 columns.1 3 52 1 4” • Names If we like, we can give arrays more imaginative than “a” or “b” . For examplenames evens = [8, 6, 4, 2, 0] or time_intervals = [1, 3, 5, 7, 8, 6, 4, 2, 0] (Blank spaces are not allowed in names: use an underscore character to connect the parts) “a” , “evens” and “time_intervals” are examples of in Matlab. A variablevariable names can refer either to a number or an array: b = 7 a = [1, 3, 5, 7] ( Actually, we can also think of 7 as being an array: the 1-element “array” [7] .) Names in Matlab are “Evens” is different from “evens”case sensitive for example, Names can be up to 19 characters, must start with a letter, and can't contain punctuation symbols. A good name for a variable can remind you about what information it contains. For example, if we measure the room temperature (F° each hour for 6 hours, we might enterÑ the data in an array called “tempdata” : tempdata = [68,72,84,87,90,94] In Matlab, there are certain built-in for examplespecial variable names pi you can guess! i, j he complex number (which we won't use)both stand for t È " ans the variable that “holds” the number or array which resulted from the most recent Matlab calculation You can preempt these names and use them for your own variables if you want. For example, you're allowed to define a variable pi = 17.634 but this isn't a wise practice! Format Matlab normally displays 4 digits (although it carries about 16 digits in its internal calculations). The commands format long will display more digits format short returns the display to the shorter display help format displays some of the other format options Creating Arrays You can in Matlab in several ways:create an array 1) by directly typing it in a = [1, 3, 5, 7] (or a = [1 3 5 7] without commas, if you like) a = [1,3,5 ; 7,8,9] to create The semicolon " ; " starts a new1 3 57 8 9” • row as you enter the numbers 2) by specifying the “stepsize” from one element to the next a = [1:2:7] T : start with 1, increase in 2,his means steps of size and end with 7, giving a = [1, 3, 5, 7] again. If you like, you can leave off the brackets and simply enter a = 1:2:7 a = 1:4 If the stepsize is omitted, it is assumed to be 1, so creates the array a = [1, 2, 3, 4] For example, we could create b = [8, 6, 4, 2, 0] by typing it in directly, or by typing b = 8: 2:0 Negative stepsizes are allowed. This command means: start at 8, in steps of size 2, stop at 0decrease Notice that b = [8: 2 1] produces the array b = [8,6,4,2,0] since adding À same 2 to 0 would go past the stopping value 1 Þ last number created before the stopping value 1 c = 0:50:100000 creates the array c = [0,50,100,150, ... ,100000] (The “ ... ” is not part of Matlab: in these notes it just means “and so on.”) It would be very time-consuming to enter the whole array by actually typing all the entries. This array “c” is very long (how many elements does it have?). If all these elements are displayed on the screen, it's a lot of clutter you don't need to see. How to avoid this? When there's a semicolon “ ; ” at the end of a command, Matlab creates the variable in memory but doesn't produce a display. A wiser command, therefore, would probably be: c = 0:50:100000; 3) By specifying the number of elements in the array In 2) we specified the stepsize (and the number of elements in the array is whatever it turns out to be). An alternative is to specify the number of (equally-spaced) elements in the array (and then the stepsize is whatever it turns out to be). The command a = linspace(1,5,7) creates an array of equally spaced ("linearly7 points spaced") from 1 to 5. Notice that these seven numbers divide the interval [ 1,5 ] into equal subintervals.six Rounded to 4 decimal places, a = [1.0000 1.6667 2.3333 3.0000 3.6667 4.3333 5.0000] (As usual, Matlab omits the brackets in its display.) 3) By “piecing together” two arrays you have already defined If you already have a = [1, 3, 5] and b = [2, 4, 6], you can use the commands: c = [a b] to create c = [1, 3, 5, 2, 4, 6] or c = [b a] to create [2, 4, 6, 1, 3, 5] or c = [b ; a] to create (when a,b have the same length)2 4 61 3 5” • During a long Matlab session you might have defined many variables. The following commands are useful to “know what you've got” and to “clean up”: The command: who lists all the current user-defined variables clear a causes Matlab to “forget a” or “undefine” a clear a b causes Matlab to undefine a and b (note: no comma!) clear causes Matlab to “undefine” user-definedall variables: CAUTION! Exercise You want to divide the interval [1, 7] into 10 equal subintervals. In differentthree ways, create an array called “endpoints” which lists, in order of increasing size, the endpoints of all the subintervals. Arithmetic using numbers and arrays We can multiply an array by a number: If a = [2, 4, 6] then 2*a = [4, 8, 12] If a and b have the e can add and subtract arrays:same number of elements, w If a = [2, 4, 6] and b = [1, 3, 7] then a + b = [3, 1 ,13] and a b = [1, 7 , 1] We are also able to multiply and divide in arrays by using thethe elements commands “ .* ” and “ ./ ” (note the dots (periods) in front of * and / ) If a = [2, 4, 6] and b = [1, 3, 7] then a.*b = [2, 12, 42] and a./b = [2.000, 1.333 , 0.8571] (rounded to 4 places) We can also exponentiate the elements (note the “dot” again in the command) If a = [2, 4, 6] then a .^2 = [4 ,16, 36] and 2 .^a = [4,16,64] If b = [1, 2, 3] then a .^b = [2,16,216] and b .^a = [1, 16, 729] Note: Between , we do not need the “dot”: 2*3 2/3 and 2^3 work fine (although 2.*3numbers ß 2./3 and 2.^3 will also work since 2 and 3 can be thought of as the arrays [2] and [3] ). For the arrays a,b above, the commands and a^b (without the “dot”) will produce errora*ba/bß messages. The operations * and / (without the “dot”) are used between arrays in Matlabcertain to do something quite different and irrelevant for now. ) Exercise Let a = [1,2,3]. In which of the following can the “ ” be safely omitted? What do youÞ get in each case? 2 a a .^2 2 .^a 2 .*a a ./2Þ 2 /a max(a) .*aÞ Built-in Functions Matlab has the usual list of built-in functions, just like a calculator. These include, for example: trig functions sin, cos, tan, etc. (when using trig functions, Matlab works in radians.)always inverse trig functions asin, acos, atan, etc. exponential and log functions exp(x) is ex “log” in Matlab means “base e.” Matlab's “log” isalways called “ ln ” in most elementary calculus texts) To find a logarithm in base 10, use the command log10(x) exp(1) = ? Exercises (by hand): log(exp( )) = ?# exp(log10(1)) = ? exp(log( )) = ?$ absolute value abs(x) is xl l square root sqrt( x ) is the nonnegative square root of x. help elfun displays a more complete list of built-in functions (“elfun” = “elementary functions” ) Using the built-in functions The built-in functions can be applied to numbers (like sin(2)) just as on a calculator, but toalso arrays, giving a new array as the answer. if a = [1,4,9] then sin(a) = [sin(1),sin(4),sin(9)] = [.8415, .7568, .4121] (rounded) and sqrt(a) = [1 2 3] if a = linspace(0, 2*pi, 5) then sin(a) = [0,1,0, 1,0] ( ) explain why if a = linspace(0, 5, 7) then (sin(a)) .^2 + (cos(a)) .^2 = [1,1,1,1,1,1,1] ( )explain if a = [ 3,4, 1, 5] then abs(a) = [3,4,1,5] The are some other useful functions that also apply to arrays: if a = [ 7,3,5] sum adds the elements: sum(a) = 1 length counts the elements: length(a) = 3 max gives the biggest element: max(a)=5 min gives the smallest element: min(a)= 7 abs kills the “ ” signs: abs(a) = [7, 3, 5] mean averages the elements: mean(a) = 0.3333 (rounded) sort sorts into increasing order: sort( a) = [ 5, 3, 7] Exercises 1. Suppose a = [1,3, 7,5]. By hand, find length(a) max(abs(a)) max(a)*min(a) length(max(a)) Check your answers by using Matlab. 2. Suppose you give the following commands: a = linspace(1,4,4) à b = 4: 2: 3 à max(b .^a) min (b.^a); ans .^2 Note: you can put more than one command on a line they are separated by a semicolon What then would be the values of ans.^2 ? sum(a.*b) ? 3. Let a = 1:5. How do you create b = the array of reciprocals of elements of a ? Making Simple Plots If you want to plot the graph of a function y = f(x) by hand, one way is make a list of the x-values compute the corresponding y-values plot the pairs (x,y) on a set of coordinate axes connect the points Every graphing device does it just like that, connecting the plotted points with straight line segments. If the x-values are very close together, then you can't see that the curve really consists of straight line segments it looks like a circle, a parabola, or whatever. Matlab does the same thing. To plot the graph of over (say) the interval [ ], we can do the followingC œ 0ÐBÑ œ #ß #B"B# commands one after the other: x = linspace( 2,2,5) pick an array of 5 equally spaced x-values between 2 to 2 y = x ./ (1 + x .^2) compute the y values: note the “ . ” plot (x,y) plot the points and connect them Matlab automatically picks an appropriate window size and scale on the axes and supplies tick marks. The graph appears in a new "figure" window. This graph looks pretty bad (angular) because we used so few points. It looks fine if we use more points, as x = linspace( 2,2,50) pick an array of 50 x-values; using a lot more than 50 wouldn't improve the picture noticeably y = x ./ (1 + x .^2) compute the y values: after changing x, you need to enter this command again to compute the y valuesnew plot (x,y) plot the curve The plot command can contain several functions, all to be graphed on the same screen. If we want the graphs of f(x) = and g(x) = on the same screen, we also definex x1+x 1+x# # # z = x.^2 ./ (1+x .^2) Notice we use a different letter for the output array z because we don't want to overwrite the array y that we also need plot (x,y,x,z) The command plot ( x, y, '--',x,z) creates a dashed plot for the curve y = f(x).first Replacing ' --' with ' : ' makes a dotted graph. This is handy to distinguish the two graphs if you don't have a color printer. The command help plot shows you some of the extra plotting “bells and whistles” There are many additional commands for enhancing the picture. Here are a few. x=linspace( 2,2,50); z=x.^2./(1+x.^2); plot (x,y,x,z,':') xlabel ('x=time') ; ylabel('y') adds the text in quotes to axes; DO THIS ON ALL YOUR GRAPHS! Note there are two commands here one for each axis. title ('Ron Freiwald,Two Graphs') adds text in quotes as a title at the top of the figure. ALWAYS PUT YOUR NAME AND A TITLE ON YOUR GRAPHS grid on adds a horizontal and vertical grid to the picture, and grid off removes them legend('x/(1+x^2)','x^2/(1+x^2)') labels the graphs (keep the commands in the same order as they were graphed) You can also by using the buttons onadd text, arrows, and straight line segments to your graphs the toolbar in the figure window. Experiment ! If you want to put several graphs on the same screen but with separate commands, you have to tell Matlab to "hold" the current screen, using the command hold on holds the current graphing window for more graphs hold off “releases” the current graphing window so that it can be overwritten. clf erases the last picture (“clear last figure”) Printing graphs Use the printer icon on the toolbar, or the menu commands: file, print Example x=linspace(0,2*pi,50); y=sin(x); plot(x,y,'+') plots only the data points (without connections), using a “+” for each point plot(x,y,'+',x,y) plots the data points as +'s; graphs the curve bythen connecting the points. You end up with the curve with the data points highlighted as well Example t=linspace(0,2*pi,50); x=cos(t); y=sin(t); plot(x,y); Here x,y are given in terms of a 3rd variable or "parameter" t. The points (x,y) are evaluated for each t value and then the points (x,y) are plotted. The axes are x and y: t doesn't appear in the picture. If you were only interested in the picture, you could omit the definitions of x and y and, after line 1, simply command plot(cos(t),sin(t)) The graph is to be a circle. (Why? For any t, if you compute x^2+y^2 by hand, whatsupposed do you get? ) However, the picture an ellipse! That's because of Matlab's scaling: the units are oflooks like unequal lengths on the axes. Sometimes that's very convenient, but it does distort shapes. The unequal scaling also distorts slopes. If you give the commands hold on plot (t,t) you add a line of slope 1 (why?) to the picture but it doesn't look like it's at 45° inclination to the horizontal. If you want shapes and slopes not distorted, then axis equal creates equal scales on the axes, and axis normal returns to the Matlab's original scaling. To see other axis commands that are available, use help axis Also see , especially the reference on p. 17 to"axis tick marks."Using Matlab in Calculus Exercise 1) Plot the graph of the function y = f(x) = 3x+5 for x over the interval [ 2,4]. 2) How many points did you use in your array of x-values? Was this the most efficient choice? Why or why not? Making a table of values of a function We may want to make a table of values for a function, or to put into a table the data collected from some experiment. For example, suppose we want to make a table of the values of y = f(x) = x for x = 1,2,...5.# We can start by making a chart with the x-values in one row and the y-values in the second row: x = 1:10 ; y = x.^2 ; chart = [x ; y] Note the semicolon “;” used to start a second row in chart The result is chart = (1 2 3 4 51 4 9 16 25” • As usual, Matlab displays on screen without the brackets.) If we'd prefer a table with vertical columns, use the Matlab command table = chart ' The operation prime “ ' ” creates the transposed array; the first row of chart column becomes the first of table, etc., so table = 1 1 2 4 3 9 4 16 5 25 Ô ×Ö ÙÖ ÙÖ ÙÖ ÙÕ Ø Writing M-files (script files) It can be awkward to correct errors made in the Matlab workspace, especially if a calculation is long and previous commands have scrolled off the screen as you executed new ones. You have probably noticed already that you can't just use the mouse to move to an old command and edit it. The best you can do is to use the “up-arrow” key “ ” to move back through the “history list” ofÅ earlier commands until you “resurrect” the old command you'd like to edit. Therefore, except for very simple jobs, we usually write our instructions to Matlab in a separate file and then have Matlab run the whole sequence of commands (the “program”) at one time. If an error turns up, we go back to the file, make and save the corrections, and execute the file again. These files are called “script files” because they are written in ordinary text: you could, in fact, create them on any word processor, you save the file as a file. When you createprovided text and save these files through Matlab, you provide a name (like, say, myfile1 ) and Matlab automatically adds extension “.m” to the name to identify the file as a Matlab file. Its full, official name would be and so these files are also referred to as “m-files.”myfile1.m To create an m-file in Matlab use the “blank white sheet" icon at the upper left of the toolbar to open a new (empty) Matlab m-file. (Or, use the menu commands: file, new, m-file ) A window will open for Matlab Editor/Debugger. Simply type your commands there. For example, enter the lines t = linspace(0,2*pi,50); %Choose 50 equally spaced points between 0,2*pi x = cos (t); %Compute cos of each point y = sin (t); %Compute sin of each point plot (x,y); %Plot the points and connect the dots (Note: Matlab ignores anything on a line following a “ % ” symbol. This lets you add comments on some of the lines in your m-file as illustrated above.) To save your m-file, Use the “Save” icon on the toolbar (looks like a “diskette”), or use the menu commands: file, save Either way, for a new file, you'll be asked to give the file a name for example myfile1 (Don't include “.m” as part of the name; Matlab will automatically add the extension “.m” ) You should save the work in the suggested folder "Work," since that's where Matlab .normally looks to find m-files Note: files left in the Work directory on computers in Eads 14 (and perhaps elsewhere on campus) will be each day. This is to prevent a buildup of clutter on the hard drive, anderased also as antiviral protection. Anything you want to keep should be insaved on your own diskette the a: drive You can copy the files you want from the Work directory to the a: drive before you leave. Or you can also choose to save files directly to the a: drive during the original save process. To run your m-file (program), from the toolbar select: tools, run Alternately, you can return to the Matlab workspace window and simply enter the name of your file to execute it: say, myfile1 Note: If you do this, Matlab , , . If itwill by default look in the Work folder to find this file can't find it because, say, you saved the file instead on your a: drive then you'll get an error message. If possible, keep your m-files in the Work folder during a working session. You see your instructor to learn how to direct Matlab to look instead on the a: drive for your m-files. Or, to make Matlab go to the a: drive to find this file, you can use the command a:myfile1 The script will in the Matlab workspace area. You will get an error message (sometimesrun rather cryptic!) if something's wrong somewhere in the script you wrote. In that case, find the error, correct it in the script file, , and run it again.save it again then If a program isn't working and you run out of time, it's useful to save a copy of the file. It's very hard for anyone else to try to help if they can't see the exact file that was creating the problem. Writing script files 1) lets you keep the sequence of commands right in front of you 2) makes it easier to correct mistakes 3) makes it easier to modify the script to run a slightly different version another time 4) allows you to save your work and open it again later. From inside Matlab, you can open an m-file you've previously saved by using the “open” icon (looks like an opening folder” on the toolbar, or by using the menu commands: file, open You should then see the available list of files in the “Work” folder and can select the file you want. If you forget the name of a file and are in the Matlab workspace, the command what lists all the m-files in the current directory ( the "Work" directoryœ unless you have changed it). Interrupting Matlab Sometimes an error of a misjudgment sends Matlab into a long calculation that you want to interrupt: Use the key combination Ctrl-C to stop Matlab's calculation. Miscellaneous If you're entering a line that's too long to fit on the screen, you can continue it to the next line: use periods ( ... ) at end of your typing to continue to the next line.three
Compartilhar