Programming
Transforming a MATLAB Program into a GUI Tool

Question Description

I need support with this Programming question so I can learn better.

every thing you need is in the file simply follow the steps.

Unformatted Attachment Preview

LENT c10.tex 28/11/2012 15: 36 Page 165 Transforming a MATLAB Program into a GUI Tool 10.1 Creating a GUI tool step by step 10.2 Further GUI design considerations CHAPTER 10 Let’s suppose we have developed a model for a system we want to study. The system could be a physical system modeled by the relevant physical laws, e.g., Newton’s second law of motion, the Schrödinger equation, Kirchoff’s circuit laws, Maxwell’s equation, or chemical reaction-rate equations. It could also be a financial, sociological, or economic system model. In any case, the model needs to be expressed in a mathematically precise form. The model will consist of mathematical relations—these could be algebraic equations, differential equations, matrix algebra, and so forth. The model will also have some parameters that characterize the specific characteristics of a particular system, e.g., masses, voltages, concentrations, spring constants, or initial velocities. The first task is to capture the mathematical model in a computational model expressed as a MATLAB program. This can often be a MATLAB script or function, which may call other user-written functions. Going from a model expressed mathematically to a computational model is itself challenging and involves some careful thinking about what one knows at the outset, what one doesn’t know, and how the relevant mathematics can be used to connect the two. The mathematical model must be transformed into a computational algorithm—a series of well-defined steps that proceeds from known quantities to find the desired unknown quantities. It also involves constructing the appropriate MATLAB data structures (e.g., numbers, arrays, strings, logical variables) to represent relevant quantities. One must make at least preliminary decisions about how the calculated results are to be displayed to the user. This could be a single number, a set of plots, or an animation. Often, the model performance can be compared to experimental data, a comparison that may allow refinement, or rejection, of the model. The previous several chapters have been designed to enable you to make such a computational model. It takes a reasonable amount of practice to get good at it. Proficiency is also helped by experience in solving problems in several domains. The purpose of this chapter is to describe how, given a successful (debugged) program— we will assume it’s in the form of a MATLAB script—one can construct a graphical user interface (GUI) and connect it to the program. The result of this process we call a MATLAB GUI tool. The tool allows the user to change both the parameters of the the model, and the way in which the results are displayed. The user can interact with the model through graphical objects like sliders and textboxes, and see the results in accessible and revealing graphical representations. A well-designed tool makes it easy for the user to explore the system behavior, gaining intuition and insight into the way the modeled system behaves. 165 www.it-ebooks.info LENT 166 c10.tex CHAPTER 10 28/11/2012 15: 36 Page 166 Transforming a MATLAB Program into a GUI Tool This is the purpose of the GUI tool; it’s a tool built to enable exploration that increases understanding. In the last chapter we introduced the GUIDE program for making GUIs, and learned how to communicate with GUI objects using the get and set commands. In this chapter we will describe a step-by-step procedure for transforming an existing MATLAB script into a GUI tool using GUIDE. The procedure described here does not cover every type of GUI tool that could be built. It will go a long way, however, and it will enable you to build a variety of very useful tools to explore the behavior of rather sophisticated computational models in a great variety of problem domains. We will, of course, start simply and add gradually. It is helpful to state the structure of the approach at the outset. The basic steps are shown below. Step 0: Write and debug the program that realizes the computational model as a MATLAB script file. Step 1: Plan the GUI. Design the layout and determine which variables are set through the GUI and how they are presented to the user. Design the output display. Step 2: Create the GUI with GUIDE. This will result in the GUIDE-generated *.fig and the GUI tool *.m files. Step 3: Transform the program into an appropriate function, called the “primary model function,” which will be invoked from within the GUI tool code. Step 4: Connect the function to the GUI. Add calls from the GUI tool code to the primary model function and synchronize the GUI objects. 10.1 Creating a GUI tool step by step Step 0: Write and debug the program In the interest of making the basic process clear, we consider a very simple model that consists of simply evaluating a mathematical function and plotting it appropriately. The following program will serve as our initial model program. %% plotDampedEfield % plot a damped sinusoidal electric field % with skin depth a % domain is 0 to 10 microns %% set parameters a=3; % skin depth (microns) E0=12; % magnitude of field at x=0 (V/micron) lambda=1; % period of oscillation (microns) xmin=0; xmax=10; Nx=200; www.it-ebooks.info LENT c10.tex 28/11/2012 15: 36 Page 167 10.1 Creating a GUI tool step by step %% initialize arrays x=linspace(xmin, xmax, Nx); E=zeros(1,Nx); %% calculate field k=2*pi/lambda; E=E0*cos(k*x).*exp(-x/a); %% plot results plot(x,E); axis([xmin, xmax, -E0, E0]); xlabel('x (microns)'); ylabel('E(V/micron)'); grid on The program above models the exponential damping of an electric field in a slightly conductive dielectric medium. (It doesn’t matter whether or not you know exactly what that means—the key here is the structure of the program.) Mathematically, the model amounts to simply tabulating the values of an exponentially damped sinusoid on a grid of x-values. We are keeping it simple to focus on the structure of the process rather than the physics or algorithms involved in the model. We’ve chosen to represent the function using two MATLAB vectors, x and E, as the key data structures. Notice that the program is broken up into four sections. There are clear blocks for (a) setting input parameters, (b) initializing arrays, (c) performing the calculation, and (d) displaying the results. Throughout this text, pulling numerical parameters up to the front of the program has been encouraged by admonition and example. This practice is all the more helpful when attaching the GUI to form a tool. Step 1: Plan the GUI The first step in actually making a GUI tool is planning the GUI. This is a process of design, which means there is not a single right answer and it’s okay to start with one design and decide to improve or alter it later. The key decision is which parameters to expose in the GUI. Looking at the program above, notice that there are six parameters set in the first executable section of the code: a, E0, lambda, xmin, xmax, and Nx. Which of these does one want the user of the tool to be able to alter through the graphical interface? Of course, one could decide that all should be GUI-exposed, but typically the purpose of the GUI is to allow the user to explore some of the parameter space of the problem but not necessarily all of it. The downside of exposing too much is a cluttered interface and the opportunity for the user to wander into a confusing part of parameter space. Notice that the parameters here naturally separate into two classes: the physical parameters a, E0, and lambda, and computational parameters xmin, xmax, and Nx. The latter change how the output is displayed, while the former reflect the underlying physics of the problem. Frequently one wants to select good computational parameters, and not expose them in www.it-ebooks.info 167 LENT 168 c10.tex CHAPTER 10 28/11/2012 15: 36 Page 168 Transforming a MATLAB Program into a GUI Tool skin depth a (microns) depthSlider plotAxes 3.0 depthText Damped E-Field Tool author F I G U R E 10.1 Basic plan for DampedEfieldTool. the GUI, so the user can focus on the model’s behavior and not be concerned with its implementation. For this example we decide to expose only the skin depth a that controls the strength of the exponential damping and leave the other numbers fixed by the program. That means that we want the user to be able to easily change a and see the result. We’ll choose a common GUI motif and use a synchronized slider and textbox to let the user control a, and an axes object on which to plot the resulting damped field. It’s often a good idea to actually sketch out the rough layout for the tool we want to build, before even starting up GUIDE. We decide on the name of the tool file, DampedEfieldTool, and include a more readable name on the tool, as well as credit for the author. It’s very helpful to decide on the Tag names for the GUI objects, and keep to the convention that the names have the form recommended in the preceding chapter: The “quantity name” should express either the variable associated with the element or the physical quantity itself. The “ObjectClass” is just a shorthand for precisely the sort of object it is. Examples of good Tag names are: xinitText, vinitSlider, animationCheckbox, methodPopup, plotPopup, componentListbox, or velocityOutputText. The most common error in this process is inconsistently spelling the Tag names. It is hugely helpful to stick to a naming convention, and this has proven to be a good one. More planning notes might include: what exactly is going to be plotted, the plotting domain (here the interval x = [xmin, xmax]), the minimum and maximum for each slider, and the initial value each parameter will have. Here we decide that initially the skin depth a will be set to 3 and widthSlider will go from 0 to 20 (Min and Max). Step 2: Create the GUI with GUIDE Now we can use GUIDE to lay out the graphical objects we need. Drag objects from the palette and position and size them according to the planned GUI layout. The initial layout is shown in Figure 10.2 for this example. www.it-ebooks.info LENT c10.tex 28/11/2012 15: 36 Page 169 10.1 Creating a GUI tool step by step F I G U R E 10.2 Initial layout for DampedEfieldTool in GUIDE. Next, set properties for each object using the Property Inspector. Double-click on each object in turn to edit its properties. For this example, Edit the slider label static text object: • Change FontSize to 12. • Click on the edit text icon near the String property and enter a two-line label: “skin depth a (microns).” See Figure 10.3. • Adjust the size of the object for readability. Edit the slider: • Change the Tag to “depthSlider.” • Change Max to 20. • Change Value to 3. Edit the textbox under the slider: • Change the Tag to “depthText.” • Change FontSize to 12. • Change String to “3” to match the value of the slider. • Adjust the size of the object (with the mouse) for readability. www.it-ebooks.info 169 LENT 170 c10.tex CHAPTER 10 28/11/2012 15: 36 Page 170 Transforming a MATLAB Program into a GUI Tool F I G U R E 10.3 Entering a multiline label as the String property. Edit the axes object: • Change the Tag to “plotAxes.” Edit the static text which functions as the tool title: • Change FontSize to 30. • Change String to “Damped E-Field Tool.” • Adjust the size of the object for readability. Edit the static text for the tool author: • Change String to your name. • Adjust the size of the object for readability. There is no need to set meaningful Tag names for objects that simply serve as labels. The objects that are crucial in this example are the slider, the associated textbox, and the axes object. Each will need to be addressed by the program, so we want to make sure they have clear Tag names, which will end up as field names in the handles structure. In GUIDE, save the GUI as DampedEfieldTool; GUIDE will generate the figure file DampedEfieldTool.fig and the m-file DampedEfieldTool.m, which will automatically be loaded into the Editor. The m-file will be edited in Step 4 below. Step 3: Transform the program into an appropriate function. a. Transform the script into a function. Load the working script file into the MATLAB editor and save the file under a new name that ends with the letter “F” (for “function”). In this example, the program was named plotDampedEfield, so it should be saved as a file with the name plotDampedEfieldF. This is the primary model function. www.it-ebooks.info LENT c10.tex 28/11/2012 15: 36 Page 171 10.1 Creating a GUI tool step by step Edit the first line of the new file so that it becomes a function declaration with the argument handles. In this example that means the first line should be: function plotDampedEfieldF(handles) b. Replace the assignment statements for those variables that should be exposed in the GUI with appropriate get commands. For this example, the plan is to expose the skin depth a. So the existing assignment statement a=3; should be replaced by a command that gets the value from the Value property of the depthSlider object. a=get(handles.depthSlider, 'Value'); Here it can be assumed that the slider has the up-to-date value of a. Synchronization of the slider value with the value in the textbox will be the responsibility of the GUI code (here DampedEfieldTool.m), which will be edited later. c. Direct graphical output to the appropriate axes object. By default, plot statements and related graphical statements will direct MATLAB to do the plotting on the current figure. This may or may not have the desired result. To assure that the plotting happens on the axes object of the GUI tool, add the handle of the axes object to the argument list of the plotting command. Most plotting-related commands will take the handle to an axes object as the first argument. For example, the command in the original program plot(x,E); should be replaced by plot(handles.plotAxes, x, E); For brevity, it is often easier to store the handle in a variable with a shorter name. So, for example, one might do the following. hax=handles.plotAxes; plot(hax, x, E); axis(hax, [xmin, xmax, -E0, E0]); xlabel(hax, 'x (microns)'); ylabel(hax, 'E(V/micron)'); grid(hax, 'on'); www.it-ebooks.info 171 LENT 172 c10.tex CHAPTER 10 28/11/2012 15: 36 Page 172 Transforming a MATLAB Program into a GUI Tool Although in this example there is only one axes object, frequently it’s helpful to have two or more axes objects in the GUI and direct the appropriate commands to each. A hypothetical example in a different context—plotting position on one axes object and energy on a second axes object—is shown as follows: hax=handles.positionAxes; haxe=handles.energyAxes; %% plot the position as a function of time on one axes plot(hax, t, x); axis(hax, [tmin, tmax, xmin, xmax]); xlabel(hax, 't (seconds)'); ylabel(hax, 'x(m)'); %% plot the Energy as a function of time on another axes plot(haxe, t, E); axis(haxe, [tmin, tmax, Emin, Emax]); xlabel(haxe, 't (seconds)'); ylabel(haxe, 'E(J)'); Back to the task of transitioning from a working program to a GUI tool. We started in the current example with the program plotDampedField shown on page 166. We’ve made three types of changes: (a) changed it from a script into a function, (b) changed the assignment statement for the variable a so that it gets the value from the slider, and (c) directed the plotting statements explicitly to the axes object. The result is the following function; the altered lines are shown in bold. function plotDampedEfieldF(handles) % plot a damped sinusoidal electric field % with skin depth a % domain is 0 to 10 microns % Author: T.A. Edison %% set parameters % skin depth (microns) a=get(handles.depthSlider,'Value'); E0=12; % magnitude of field at x=0 (V/micron) lambda=1; % period of oscillation (microns) xmin=0; xmax=10; Nx=200; %% initialize arrays x=linspace(xmin, xmax, Nx); E=zeros(1, Nx); www.it-ebooks.info LENT c10.tex 28/11/2012 15: 36 Page 173 10.1 Creating a GUI tool step by step %% calculate field k=2*pi/lambda; E=E0*cos(k*x).*exp(-x/a); %% plot results hax=handles.plotAxes; plot(hax, x, E); axis(hax, [xmin, xmax, -E0, E0]); xlabel(hax, 'x (microns)'); ylabel(hax, 'E(V/micron)'); grid(hax, 'on'); Step 4: Connect the function to the GUI The main GUI tool code is the file DampedEfieldTool.m, which was generated automatically by GUIDE and is loaded in the Editor (if not, please open it in the Editor). Run the program as-is by pressing the green Run button on the EDITOR tab. All the parts work but don’t accomplish anything useful. This program now needs to be edited to accomplish three things: a. Synchronize the slider and the associated textbox with each other. b. Execute primary model function plotDampedEfieldF(handles) whenever the user moves the slider or changes the number in the textbox. c. Execute the primary model function when the tool is first run. Examine the file DampedEfieldTool in the Editor. It consists of the following seven functions, only three of which will need to be changed. function function function function function function function DampedEfieldTool DampedEfieldTool_OpeningFcn DampedEfieldTool_OutputFcn depthSlider_Callback depthSlider_CreateFcn depthText_Callback depthText_CreateFcn CHANGE CHANGE CHANGE Altering the slider callback When the user moves the depthSlider and releases it, the function depthSlider_Callback is executed. The function has several arguments, including the handles structure, which we will use to communicate with GUI objects. Since the user has just changed the value of the slider, this function’s tasks are two: update the string shown in the depthText textbox, and then invoke the primary model function plotDampedEfieldF(handles). www.it-ebooks.info 173 LENT 174 c10.tex CHAPTER 10 28/11/2012 15: 36 Page 174 Transforming a MATLAB Program into a GUI Tool Updating the string in the textbox is the same process as was described on page 162. We add a fourth step to automatically invoke the primary model function with the new value. • Get the value of the slider. • Create the corresponding string. • Then set the String property of the textbox to this newly created string. • Finally, execute the function plotDampedEfieldF(handles) to recalculate and replot using the new value. Recall that within plotDampedEfieldF the new value of the width will be obtained (using get) from the widthSlider. The fully filled-out callback function for the slider now looks like this: function depthSlider_Callback(hObject, eventdata, handles) % a=get(handles.depthSlider, 'Value'); astr=num2str(a); set(handles.depthText, 'String', astr) plotDampedEfieldF(handles); Altering the textbox callback When the user edits the text in depthText and either presses or clicks somewhere else, the function depthText_Callback is executed. Since the user has just changed the string in the textbox, this function’s tasks are two: update the value of the depthSlider object to reflect the new value, and then invoke the function plotDampedEfieldF(handles). Updating the value of the slider is the same process as was described on page 163. Again, we add a fourth step to automatically invoke the primary model function with the new value. • Get the String of the textbox. • Create the corresponding number, using str2double. • Set the Value property of the slider to this newly calculated number. • Finally, execute the function plotDampedEfieldF(handles) to recalculate and replot using the new value. The fully filled-out callback function for the textbox now looks like this: function depthText_Callback(hObject, eventdata, handles) % astr=get(handles.depthText, 'String'); a ...
Purchase answer to see full attachment
Student has agreed that all tutoring, explanations, and answers provided by the tutor will be used to help in the learning process and in accordance with Studypool's honor code & terms of service.

Final Answer

Atta...

alvikhan (1)
University of Maryland

Anonymous
The tutor was pretty knowledgeable, efficient and polite. Great service!

Anonymous
Heard about Studypool for a while and finally tried it. Glad I did caus this was really helpful.

Anonymous
Just what I needed… fantastic!

Studypool
4.7
Trustpilot
4.5
Sitejabber
4.4