1. Trang chủ
  2. » Công Nghệ Thông Tin

Essential MATLAB for Engineers and Scientists PHẦN 8 pptx

44 315 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 44
Dung lượng 0,94 MB

Nội dung

Ch12-H8417 5/1/2007 11: 41 page 289 12 More graphics z = peaks(25); c(:,:,1) = rand(25); c(:,:,2) = rand(25); c(:,:,3) = rand(25); surf(z,c,’facecolor’,’interp’,’facelighting’,’phong’, ’edgecolor’,’none’) camlight right The possibilities for the facelighting property of the surface object are none, flat (uniform color across each facet), gouraud or phong. The last two are the names of lighting algorithms. Phong lighting generally produces better results, but takes longer to render than Gouraud lighting. Remember that you can see all a surface object’s properties by creating the object with a handle and using get on the object’s handle. This one’s quite stunning: [xy]=meshgrid(-8 : 0.5 : 8); r = sqrt(x.ˆ2 + y.ˆ2) + eps; z = sin(r) ./ r; surf(x,y,z,’facecolor’,’interp’,’edgecolor’,’none’, ’facelighting’,’phong’) colormap jet daspect([5 5 1]) axis tight view(-50, 30) camlight left For more information on lighting and the camera see the sections Lighting as a Visualization Tool and Defining the View in Using MATLAB: 3-D Visualization. 12.6 Saving, printing and exporting graphs 12.6.1 Saving and opening figure files You can save a figure generated during a MATLAB session so that you can open it in a subsequent session. Such a file has the .fig extension. ➤ Select Save from the figure window File menu. ➤ Make sure the Save as type is .fig. To open a figure file select Open from the File menu. 289 Ch12-H8417 5/1/2007 11: 41 page 290 Essential MATLAB for Engineers and Scientists 12.6.2 Printing a graph You can print everything inside a figure window frame, including axis labels and annotations: ➤ To print a figure select Print from the figure window File menu. ➤ If you have a black and white printer, colored lines and text are ‘dithered to gray’ which may not print very clearly in some cases. In that case select Page Setup from the figure File menu. Select the Lines and Text tab and click on the Black and white option for Convert solid colored lines to:. 12.6.3 Exporting a graph A figure may be exported in one of a number of graphics formats if you want to import it into another application, such as a text processor. You can also export it to the Windows clipboard and paste it from there into an application. To export to the clipboard: ➤ Select Copy Figure from the figure window’s Edit menu (this action copies to the clipboard). ➤ Before you copy to the clipboard you may need to adjust the figure’s set- tings. You can do this by selecting Preferences from the figure’s File menu. This action opens the Preferences panel, from which you can select Figure Copy Template Preferences and Copy Options Preferences to adjust the figure’s settings. You may also have to adjust further settings with Page Setup from the figure’s File menu. To export a figure to a file in a specific graphics format: ➤ Select Export from the figure’s File menu. This action invokes the Export dialogue box. ➤ Select a graphics format from the Save as type list, e.g. EMF (enhanced metafiles), JPEG, etc. You may need to experiment to find the best format for the target application you have in mind. For example, to insert a figure into a Word document, I find it much easier first to save it in EMF or JPEG format and then to insert the graphics file into the Word document, rather than to go the clipboard route (there are more settings to adjust that way). 290 Ch12-H8417 5/1/2007 11: 41 page 291 12 More graphics For further details consult the section Basic Printing and Exporting in Using MATLAB: Graphics. Summary ➤ MATLAB graphics objects are arranged in a parent–child hierarchy. ➤ A handle may be attached to a graphics object at creation; the handle may be used to manipulate the graphics object. ➤ If h is the handle of a graphics object, get(h) returns all the current values of the object’s properties. set(h) shows you all the possible values of the properties. ➤ The functions gcf, gca and gco return the handles of various graphics objects. ➤ Use set to change the properties of a graphics object. ➤ A graph may be edited to a limited extent in plot edit mode, selected from the figure window (Tools -> Edit Plot). More general editing can be done with the Property Editor (Edit -> Figure Properties from the figure window). ➤ The most versatile way to create animations is by using the Handle Graphics facilities. Other techniques involve comet plots and movies. ➤ Indexed coloring may be done with colormaps. ➤ Graphs saved to .fig files may be opened in subsequent MATLAB sessions. ➤ Graphs may be exported to the Windows clipboard, or to files in a variety of graphics formats. 291 Ch13-H8417 5/1/2007 11: 41 page 292 13 *Graphical User Interfaces (GUIs) The objectives of this chapter are to introduce you to the basic concepts involved in writing your own graphical user interfaces, including: ➤ Figure files. ➤ Application M-files. ➤ Callback functions. The script files we have written so far in this book have had no interaction with the user, except by means of the occasional input statement. Modern users, however, have grown accustomed to more sophisticated interaction with programs, by means of windows containing menus, buttons, drop-down lists, etc. This way of interacting with a program is called a graphical user interface, or GUI for short (pronounced ‘gooey’), as opposed to a text user interface by means of command-line based input statements. The MATLAB online documentation has a detailed description of how to write GUIs in MATLAB, to be found in Using MATLAB: Creating Graphical User Inter- faces. This chapter presents a few examples illustrating the basic concepts. Hahn, the original author (of the first two editions of this book) stated that he “spent a day or two reading MATLAB’s documentation in order to write the GUIs in this chapter.” He pointed out that he seldom had such fun programming! 13.1 Basic structure of a GUI ➤ MATLAB has a facility called GUIDE (Graphical User Interface Development Environment) for creating and implementing GUIs. You start it from the command line with the command guide. Ch13-H8417 5/1/2007 11: 41 page 293 13 Graphical User Interfaces (GUIs) ➤ The guide command opens an untitled figure which contains all the GUI tools needed to create and lay out the GUI components (e.g. pushbuttons, menus, radio buttons, popup menus, axes, etc.). These components are called uicontrols in MATLAB (for user interface controls). ➤ GUIDE generates two files that save and launch the GUI: a FIG-file and an application M-file. ➤ The FIG-file contains a complete description of the GUI figure, i.e. whatever uicontrols and axes are needed for your graphical interface. ➤ The application M-file (the file you run to launch the GUI) contains the functions required to launch and control the GUI. The application M-file does not contain the code that lays out the GUI components; this information is saved in the FIG-file. The GUI is controlled largely by means of callback functions, which are subfunctions in the application M-file. ➤ Callback functions are written by you and determine what action is taken when you interact with a GUI component, e.g. click a button. GUIDE gen- erates a callback function prototype for each GUI component you create. You then use the Editor to fill in the details. 13.2 A first example: getting the time For our first example we will create a GUI with a single pushbutton. When you click the button the current time should appear on the button (Figure 13.1). Go through the following steps: ➤ Run guide from the command line. This action opens the Layout Editor (Figure 13.2). ➤ We want to place a pushbutton in the layout area. Select the pushbutton icon in the component palette to the left of the layout area. The cursor changes to a cross. You can use the cross either to select the position of the top-left corner of the button (in which it has the default size), or you can set the size of the button by clicking and dragging the cursor to the bottom-right corner of the button. A button imaginatively names Push Button appears in the layout area. ➤ Select the pushbutton (click on it). Right-click for its context menu and select Inspect Properties. Use the Property Inspector to change the but- ton’s String property to Time. The text on the button in the layout area will change to Time. 293 Ch13-H8417 5/1/2007 11: 41 page 294 Essential MATLAB for Engineers and Scientists Figure 13.1 Click the button to see the time Figure 13.2 GUIDE Layout Editor 294 Ch13-H8417 5/1/2007 11: 41 page 295 13 Graphical User Interfaces (GUIs) Note that the Tag property of the button is set to pushbutton1. This is the name GUIDE will use for the button’s callback function when it generates the application M-file in a few minutes. If you want to use a more meaningful name when creating a GUI which may have many such buttons, now is the time to change the tag. If you change a component’s tag after generating the application M-file you have to change its callback function name by hand (and all references to the callback). You also have to change the name of the callback function in the component’s Callback property. For example, suppose you have generated an application M-file with the name myapp.m, with a pushbutton having the tag pushbutton1. The pushbutton’s Callback property will be something like myapp(’mybutton_Callback’,gcbo,[],guidata(gcbo)) If you want to change the tag of the pushbutton to Open, say, you will need to change its Callback property to myapp(’Open_Callback’,gcbo,[],guidata(gcbo)) ➤ Back in the Layout Editor select your button again and right-click for the context menu. Select Edit Callback. A dialog box appears for you to save your FIG-file. Choose a directory and give a filename of time.fig—make sure that the .fig extension is used. GUIDE now generates the application M-file (time.m), which the Editor opens for you at the place where you now have to insert the code for whatever action you want when the Time button is clicked: function varargout = pushbutton1_Callback(h, eventdata, handles, varargin) % Stub for Callback of the uicontrol handles. pushbutton1. disp(’pushbutton1 Callback not implemented yet.’) Note that the callback’s name is pushbutton1_Callback where pushbutton1 is the button’s Tag property. Note also that the statement disp(’pushbutton1 Callback not implemented yet.’) is automatically generated for you. ➤ If you are impatient to see what your GUI looks like at this stage click the Activate Figure button at the right-hand end of the Layout Editor toolbar. 295 Ch13-H8417 5/1/2007 11: 41 page 296 Essential MATLAB for Engineers and Scientists An untitled window should appear with a Time button in it. Click the Time button—the message pushbutton1 Callback not implemented yet should appear in the Command Window. ➤ Now go back to the (M-file) Editor to change the pushbutton1_Call back function. Insert the following lines of code, which are explained below: % get time d = clock; % convert time to string time = sprintf(’%02.0f:%02.0f:%02.0f’,d(4),d(5), d(6)); % change the String property of pushbutton1 set(gcbo,’String’,time) The function clock returns the date and time as a six-component vector in the format [year month day hour minute seconds] The sprintf statement converts the time into a string time in the usual format, e.g. 15:05:59 ➤ The last statement is the most important one as it is the basis of the button’s action: set(gcbo,’String’,time) It is the button’s String property which is displayed on the button in the GUI. It is therefore this property which we want to change to the current time when it is clicked. The command gcbo stands for ‘get callback object’, and returns the handle of the current callback object, i.e. the most recently activated uicontrol. In this case the current callback object is the button itself (it could have been some other GUI component). The set statement then changes the String property of the callback object to the string time which we have created. Easy! ➤ Save the application M-file and return to the Layout Editor. For complete- ness give the entire figure a name. Do this by right-clicking anywhere in the layout area outside the Time button. The context menu appears. Select Property Inspector. This time the Property Inspector is looking at the 296 Ch13-H8417 5/1/2007 11: 41 page 297 13 Graphical User Interfaces (GUIs) figure’s properties (instead of the pushbutton’s properties) as indicated at the top of its window. Change the Name property to something suitable (like Time). ➤ Finally, click Activate Figure again in the Layout Editor. Your GUI should now appear in a window entitled Time. When you click the button the current time should appear on the button. ➤ If you want to run your GUI from the command line, enter the application M-file name. 13.2.1 Exercise You may have noticed that graphics objects have a Visible property. See if you can write a GUI with a single button which disappears when you click on it! This exercise reminds me of a project my engineering friends had when I was a first- year student. They had to design a black box with a switch on the outside. When it was switched on a lid opened, and a hand came out of the box to switch if off … 13.3 Newton again Our next example is a GUI version of Newton’s method to find a square root: you enter the number to be square-rooted, press the Start button, and some iterations appear on the GUI (Figure 13.3). Figure 13.3 Square roots with Newton’s method. 297 Ch13-H8417 5/1/2007 11: 41 page 298 Essential MATLAB for Engineers and Scientists We will use the following uicontrols from the component palette in the Layout Editor: ➤ a static text control to display the instruction Enter number to square root and press Start: (static text is not interactive, so no callback function is generated for it); ➤ an edit text control for the user to enter the number to be square-rooted; ➤ a pushbutton to start Newton’s method; ➤ a static text control for the output, which will consist of several iterations. You can of course send the output to the command line with disp. ➤ We will also make the GUI window resizable (did you notice that you couldn’t resize the Time window in the previous example?). Proceed as follows: ➤ Run guide from the command line. When the Layout Editor starts right- click anywhere in the layout area to get the figure’s Property Inspector and set the figure’s Name property to Newton. ➤ Now let’s first make the GUI resizable. Select Tools in the Layout Editor’s toolbar and then Application Options. There are three Resize behav- ior options: Non-resizable (the default), Proportional and User-specified. Select Proportional. Note that under Proportional when you resize the win- dow the GUI components are also resized, although the font size of labels does not resize. ➤ Place a static text control for the instruction to the user in the layout area. Note that you can use the Alignment Tool in the Layout Editor toolbar to align controls accurately if you wish. You can also use the Snap to Grid option in the Layout menu. If Snap to Grid is checked then any object which is moved to within nine pixels of a grid line jumps to that line. You can change the grid spacing with Layout -> Grid and Rulers -> Grid size. Use the Property Inspector to change the static text control’s String property to Enter number to square root and press Start: ➤ Place an edit text control on the layout area for the user to input the number to be square-rooted. Set its String property to blank. Note that you don’t need to activate the Property Inspector for each control. Once the Property Inspector has been started it switches to whichever object you select in the layout area. The tag of this component will be edit1 since no other edit text components have been created. 298 [...]... 2: Write the formula for y = f(t) % y = (g/k) * t - (g/kˆ2) * ( 1 - exp(-k * t)); % % Step 3: Determine the velocity % v = diff(y,t); % % Step 4: Determine the acceleration % a = diff(v,t); % % Step 5: Print the v and a formulae and compare with % the published results % v, a % % Step 6: Determine a from published formula and v % a2 = g - k * v; 319 Essential MATLAB for Engineers and Scientists % Step... structure plan and the MATLAB code are as follows: % % Free fall analysis (saved as FFall.m): % Comparison of exact solutions of free % fall with zero, linear and quadratic % friction for t = 0 to 5 seconds % % Script by D T V September 2006 % 315 Essential MATLAB for Engineers and Scientists % Step 1: Specify constants % k = 0.2; % Friction coefficient provided in the problem statement g = 9 .81 ; % Acceleration... written for a unit of mass Let us also assume g = 9 .81 m/s2 and k = 0.2 for the air-drag parameter Finally, let us answer the following: (a) What is y in meters for t = 5 seconds of free fall for the three cases (b) What are the terminal speeds in meters per second for cases 2 and 3 for the specified air-drag parameter? (c) Is the terminal speed reached at t = 5 seconds? Note: The terminal speeds are g/k and. .. for the next number to be entered by the user These actions are achieved by the following code, which is explained below: function varargout = pushbutton1_Callback(h, eventdata, handles, varargin) % Stub for Callback of the uicontrol handles pushbutton1 a = str2num(get(handles.edit1,’String’)); x = a; % initial guess for i = 1 :8 x = (x + a/x)/2; str(i) = sprintf(’%g’,x); end 299 Essential MATLAB for. .. used for both the second and third cases Within the first half second from the time of release the three curves are not distinguishable illustrating the fact that it takes a little time before the friction effects are felt At the time of 5 seconds after release, the speed and the distance fallen are quite different It is not surprising that quadratic friction 317 Essential MATLAB for Engineers and Scientists. .. the GUI from being drawn all over from the command line Figure 13.4 Axes on a GUI 301 Essential MATLAB for Engineers and Scientists ➤ Place an axes component on the GUI Its HandleVisibility should be on ➤ Place a pushbutton (tag pushbutton1) on the GUI and change its String property to Plot Save the figure (if you have not already) under the name Plotter and generate the application M-file Edit the pushbutton’s... the importance of learning to use tools like MATLAB MATLAB and companion toolboxes provide engineers, scientists, mathematicians, and students of these fields with an environment for technical computing applications It is much more than a programming language like C, C++ or Fortran Technical computing includes mathematical computation, analysis, visualization, and algorithm development The MathWork website... problem of the cantilever beam The beam and its deflection under load is illustrated in Figure 14.1 below, which is generated by the script m-file created to solve the problem posed next Many structural mechanics formulae are available in Formulas for Stress and Strain, Fifth Edition by Raymond J Roark and Warren C Young, published by McGrawHill Book Company (1 982 ) For a uniformly loaded span of a cantilever... attached to a wall at x = 0 with the free end at x = L, the formula for the vertical displacement from y = 0 under the loaded condition with y the coordinate in the direction opposite that of the load can be written as follows: Y= y 24EI = − X4 − 4 X3 + 6 X2 , wL4 309 Essential MATLAB for Engineers and Scientists 1 Unloaded cantilever beam Uniformly loaded beam 0.5 0 Ϫ0.5 Y Ϫ1 Ϫ1.5 Ϫ2 Ϫ2.5 Ϫ3 Ϫ3.5 Ϫ4... Distance, y 100 80 60 40 20 0 0 1 2 3 4 5 Time, t Figure 14.3 Comparison of free-fall distance: Top curve is for no friction, middle curve is for linear friction and the bottom curve is for quadratic friction 50 45 40 35 Speed, v 30 25 20 15 10 5 0 0 1 2 3 4 5 Time,t Figure 14.4 Comparison of free-fall speed: Top curve is for no friction, middle curve is for linear friction and the bottom curve is for quadratic . menu. 289 Ch12-H8417 5/1/2007 11: 41 page 290 Essential MATLAB for Engineers and Scientists 12.6.2 Printing a graph You can print everything inside a figure window frame, including axis labels and annotations: ➤ To. button, and some iterations appear on the GUI (Figure 13.3). Figure 13.3 Square roots with Newton’s method. 297 Ch13-H8417 5/1/2007 11: 41 page 2 98 Essential MATLAB for Engineers and Scientists We. structural Ch14-H8417 5/1/2007 11: 42 page 3 08 Essential MATLAB for Engineers and Scientists element is the cantilever beam, which is one of the primary elements of engi- neered structures, e.g. buildings and

Ngày đăng: 12/08/2014, 16:22

TỪ KHÓA LIÊN QUAN