Sie sind auf Seite 1von 22

GUI Layout

GUIDE, the MATLAB graphical user interface development environment, provides a set of
tools for creating graphical user interfaces (GUIs). These tools simplify the process of
laying out and programming GUIs.

Using the GUIDE Layout Editor, you can populate a GUI by clicking and dragging GUI
componentssuch as axes, panels, buttons, text fields, sliders, and so oninto the layout
area. You also can create menus and context menus for the GUI. From the Layout Editor,
you can size the GUI, modify component look and feel, align components, set tab order,
view a hierarchical list of the component objects, and set GUI options.
GUI Programming
GUIDE automatically generates a program file containing MATLAB functions that controls
how the GUI operates. This code file provides code to initialize the GUI and contains a
framework for the GUI callbacksthe routines that execute when a user interacts with a
GUI component. Use the MATLAB Editor to add code to the callbacks to perform the
actions you want the GUI to perform.
[warning]MATLAB software provides a selection of standard dialog boxes that you can
create with a single function call. For information about these dialog boxes and the
functions used to create them, see Predefined Dialog Boxes in the GUI Development
section of the MATLAB Function Reference documentation.[/warning]
Matlab Quick Search:
gui matlab tutorial
matlab gui tutorials
matlab gui programming
matlab gui
gui matlab
MATLAB Gui Examples
Matlab GUI walkthrough
matlab gui guide
matlab guide tutorial
matlab gui layout example

Tags: gui, guide, Layout Editor, matlab, Predefined Dialog Boxes, programming
A GUI to Set Simulink Model Parameters Example 2
May 2nd, 2010 No Comments Posted in Examples
Running the Simulation from the GUI
The GUI Simulate and store results button callback runs the model simulation and stores
the results in the handles structure. Storing data in the handles structure simplifies the
process of passing data to other subfunction since this structure can be passed as an
argument.
When a user clicks the Simulate and store results button, the callback executes the
following steps:
Calls sim, which runs the simulation and returns the data that is used for plotting.
Creates a structure to save the results of the simulation, the current values of the
simulation parameters set by the GUI, and the run name and number.
Stores the structure in the handles structure.
Updates the list box String to list the most recent run.
Here is the Simulate and store results button callback:
1
2
3
function SimulateButton_Callback(hObject, eventdata, handles)
[timeVector,stateVector,outputVector] = sim('f14');
% Retrieve old results data structure
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

if isfield(handles,'ResultsData') &
~isempty(handles.ResultsData)
ResultsData = handles.ResultsData;
% Determine the maximum run number currently used.
maxNum = ResultsData(length(ResultsData)).RunNumber;
ResultNum = maxNum+1;
else % Set up the results data structure
ResultsData = struct('RunName',[],'RunNumber',[],...
'KiValue',[],'KfValue',[],'timeVector',[],...
'outputVector',[]);
ResultNum = 1;
end
if isequal(ResultNum,1),
% Enable the Plot and Remove buttons
set([handles.RemoveButton,handles.PlotButton],'Enable','on')
end
% Get Ki and Kf values to store with the data and put in the
results list.
Ki = get(handles.KiValueSlider,'Value');
Kf = get(handles.KfValueSlider,'Value');
ResultsData(ResultNum).RunName = ['Run',num2str(ResultNum)];
ResultsData(ResultNum).RunNumber = ResultNum;
ResultsData(ResultNum).KiValue = Ki;
ResultsData(ResultNum).KfValue = Kf;
ResultsData(ResultNum).timeVector = timeVector;
ResultsData(ResultNum).outputVector = outputVector;
% Build the new results list string for the listbox
ResultsStr = get(handles.ResultsList,'String');
if isequal(ResultNum,1)
ResultsStr = {['Run1',num2str(Kf),' ',num2str(Ki)]};
else
ResultsStr = [ResultsStr;...
{['Run',num2str(ResultNum),' ',num2str(Kf),' ', ...
num2str(Ki)]}];
end
set(handles.ResultsList,'String',ResultsStr);
% Store the new ResultsData
handles.ResultsData = ResultsData;
guidata(hObject, handles)
Removing Results from the List Box
The GUI Remove button callback deletes any selected item from the Results list list box. It
also deletes the corresponding run data from the handles structure. When a user clicks the
Remove button, the callback executes the following steps:
Determines which list box items are selected when a user clicks the Remove button and
removes those items from the list box String property by setting each item to the empty
matrix [].
Removes the deleted data from the handles structure.
Displays the string and disables the Remove and Plot buttons (using the Enable
property), if all the items in the list box are removed.
Save the changes to the handles structure (guidata).
Here is the Remove button callback:
1 function RemoveButton_Callback(hObject, eventdata, handles)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

currentVal = get(handles.ResultsList,'Value');
resultsStr = get(handles.ResultsList,'String');
numResults = size(resultsStr,1);
% Remove the data and list entry for the selected value
resultsStr(currentVal) =[];
handles.ResultsData(currentVal)=[];
% If there are no other entries, disable the Remove and Plot
button
% and change the list string to <empty>
if isequal(numResults,length(currentVal)),
resultsStr = {'<empty>'};
currentVal = 1;

set([handles.RemoveButton,handles.PlotButton],'Enable','off')
end
% Ensure that list box Value is valid, then reset Value and String
currentVal = min(currentVal,size(resultsStr,1));
set(handles.ResultsList,'Value',currentVal,'String',resultsStr)
% Store the new ResultsData
guidata(hObject, handles)
Plotting the Results Data
The GUI Plot button callback creates a plot of the run data and adds a legend. The data to
plot is passed to the callback in the handles structure, which also contains the gain
settings used when the simulation ran. When a user clicks the Plot button, the callback
executes the following steps:
Collects the data for each run selected in the Results list, including two variables (time
vector and output vector) and a color for each result run to plot.
Generates a string for the legend from the stored data.
Creates the figure and axes for plotting and saves the handles for use by the Close
button callback.
Plots the data, adds a legend, and makes the figure visible.
The figure that contains the plot is created as invisible and then made visible after adding
the plot and legend. To prevent this figure from becoming the target for plotting
commands issued at the command line or by other GUIs, its HandleVisibility and
IntegerHandle properties are set to off. This means the figure is also hidden from the plot
and legend commands.
Use the following steps to plot into a hidden figure:
Save the handle of the figure when you create it.
Create an axes, set its Parent property to the figure handle, and save the axes handle.
Create the plot (which is one or more line objects), save these line handles, and set their
Parent properties to the handle of the axes.
Make the figure visible.
Plot Button Callback Listing
Here is the Plot button callback.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

function PlotButton_Callback(hObject, eventdata, handles)
currentVal = get(handles.ResultsList,'Value');
% Get data to plot and generate command string with color
% specified
legendStr = cell(length(currentVal),1);
plotColor = {'b','g','r','c','m','y','k'};
for ctVal = 1:length(currentVal);
PlotData{(ctVal*3)-2} =
handles.ResultsData(currentVal(ctVal)).timeVector;
PlotData{(ctVal*3)-1} =
handles.ResultsData(currentVal(ctVal)).outputVector;
numColor = ctVal - 7*( floor((ctVal-1)/7) );
PlotData{ctVal*3} = plotColor{numColor};
legendStr{ctVal} = ...
[handles.ResultsData(currentVal(ctVal)).RunName,'; Kf=',...
num2str(handles.ResultsData(currentVal(ctVal)).KfValue),...
'; Ki=', ...
num2str(handles.ResultsData(currentVal(ctVal)).KiValue)];
end
% If necessary, create the plot figure and store in handles
% structure
if ~isfield(handles,'PlotFigure') ||...
~ishandle(handles.PlotFigure),
handles.PlotFigure = ...
figure('Name','F14 Simulation Output',...
'Visible','off','NumberTitle','off',...
'HandleVisibility','off','IntegerHandle','off');
handles.PlotAxes = axes('Parent',handles.PlotFigure);
guidata(hObject, handles)
end
% Plot data
pHandles = plot(PlotData{:},'Parent',handles.PlotAxes);
% Add a legend, and bring figure to the front
legend(pHandles(1:2:end),legendStr{:})
% Make the figure visible and bring it forward
figure(handles.PlotFigure)
The GUI Help Button
The GUI Help button callback displays an HTML file in the MATLAB Help browser. It uses
two commands:
The which command returns the full path to the file when it is on the MATLAB path
The web command displays the file in the Help browser.
This is the Help button callback.
1
2
3

function HelpButton_Callback(hObject, eventdata, handles)
HelpPath = which('f14ex_help.html');
web(HelpPath);
You can also display the help document in a Web browser or load an external URL. For a
description of these options, see the documentation for web.
Closing the GUI
The GUI Close button callback closes the plot figure, if one exists and then closes the GUI.
The handle of the plot figure and the GUI figure are available from the handles structure.
The callback executes two steps:
Checks to see if there is a PlotFigure field in the handles structure and if it contains a
valid figure handle (the user could have closed the figure manually).
Closes the GUI figure.
This is the Close button callback:
1
2
3
4
5
6
7

function CloseButton_Callback(hObject, eventdata, handles)
% Close the GUI and any plot window that is open
if isfield(handles,'PlotFigure') && ...
ishandle(handles.PlotFigure),
close(handles.PlotFigure);
end
close(handles.F14ControllerEditor);
The List Box Callback and Create Function
This GUI does not use the list box callback because the actions performed on list box
items are carried out by push buttons (Simulate and store results, Remove, and Plot).
GUIDE automatically inserts a callback stub when you add the list box and automatically
sets the Callback property to execute this subfunction whenever the callback is triggered
(which happens when users select an item in the list box).
In this example, there is no need for the list box callback to execute. You can delete it
from the GUI code file and at the same time also delete the Callback property string in the
Property Inspector so that the software does not attempt to execute the callback.

[important]For more information on how to trigger the list box callback, see the
description of list box.[/important]
Setting the Background to White
The list box create function enables you to determine the background color of the list box.
The following code shows the create function for the list box that is tagged ResultsList:
1
2
function ResultsList_CreateFcn(hObject, eventdata, handles)
% Hint: listbox controls usually have a white background, change
3
4
5
6
7
8
9
10

% 'usewhitebg' to 0 to use default. See ISPC and COMPUTER.
usewhitebg = 1;
if usewhitebg
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',...
get(0,'defaultUicontrolBackgroundColor'));
end
Matlab Quick Search:
matlab guide listbox example
matlab GUI listbox choices
MATLAB Legend Examples
matlab listbox
matlab how to make listbox values dependent on values entered in gui
find_system matlab
matlab GUI listbox tutorial
matlab listbox example
matlab listbox legend
matlab listbox properties

Tags: Enable, example, find_system, gui, guidata, HandleVisibility, IntegerHandle, legend, list
box, matlab,model_open, open_system, Parent, plot, Running
Simulation, set_param, sim, Simulate, simulation, simulink,str2double, web
A GUI to Set Simulink Model Parameters
May 2nd, 2010 No Comments Posted in Examples
About the Simulink Model Parameters Example
This example illustrates how to create a GUI that sets the parameters of a Simulink
model. In addition, the GUI can run the simulation and plot the results in a figure window.
The following figure shows the GUI after running three simulations with different values
for controller gains.

The example illustrates a number of GUI building techniques:
Opening and setting parameters on a Simulink model from a GUI.
Implementing sliders that operate in conjunction with text boxes, which display the
current value, as well as accepting user input.
Enabling and disabling controls, depending on the state of the GUI.
Managing a variety of shared data using the handles structure.
Directing graphics output to figures with hidden handles.
Adding a Help button that displays .html files in the MATLAB Help browser.
View and Run the Simulink Parameters GUI
If you are reading this document in the MATLAB Help browser, you can access the example
FIG-file and code file by clicking the following links. If you are reading this on the Web or
in PDF form, go to the corresponding section in the MATLAB Help Browser to use the links.
If you intend to modify the layout or code of this GUI example, first save a copy of its code
file and FIG-file to your current folder (you need write access to your current folder to do
this). Follow these steps to copy the example files to your current folder and then to open
them:
Click here to copy the files to your current folder.
Type guide f14ex or click here to open the FIG-file in GUIDE.
Type edit f14ex or click here to open the code file in the Editor.
You can view the properties of any component by double-clicking it in the Layout Editor to
open the Property Inspector for it. You can modify either the figure, the code, or both, and
then save the GUI in your current folder using File > Save as from GUIDE. This saves both
files, allowing you to rename them, if you choose.
To just inspect the GUI in GUIDE and run it, follow these steps instead:
Click here to add the example files to the MATLAB path (only for the current session).
Click here to run the f14ex GUI.
Click here to display the GUI in the GUIDE Layout Editor (read only).
Click here to display the GUI code file in the MATLAB Editor (read only).
[warning]Do not save GUI files to the examples folder where you found them or you will
overwrite the original files. If you want to save GUI files, use File > Save as from GUIDE,
which saves both the GUI FIG-file and the GUI code file.[/warning]
How to Use the Simulink Parameters GUI
[warning]You must have Simulink installed for this GUI to run. The first time you run the
GUI, Simulink opens (if it is not already running) and loads the f14 demo model. This can
take several seconds.[/warning]
The GUI has a Help button. Clicking it opens an HTML file, f14ex_help.html, in the Help
Browser. This file, which resides in the examples folder along with the GUI files, contains
the following five sections of help text:
F14 Controller Gain Editor
You can use the F14 Controller Gain Editor to analyze how changing the gains used in the
Proportional-Integral Controller affect the aircrafts angle of attack and the amount of G
force the pilot feels.
[warning]That the Simulink diagram f14.mdl must be open to run this GUI. If you close the
F14 Simulink model, the GUI reopens it whenever it requires the model to
execute.[/warning]
Changing the Controller Gains
You can change gains in two blocks:
The Proportional gain (Kf) in the Gain block
The Integral gain (Ki) in the Transfer Function block
You can change either of the gains in one of the two ways:
Move the slider associated with that gain.
Type a new value into the Current value edit field associated with that gain.
The blocks values are updated as soon as you enter the new value in the GUI.
Running the Simulation
Once you have set the gain values, you can run the simulation by clicking the Simulate and
store results button. The simulation time and output vectors are stored in the Results list.
Plotting the Results
You can generate a plot of one or more simulation results by selecting the row of results
(Run1, Run2, etc.) in the Results list that you want to plot and clicking the Plot button. If
you select multiple rows, the graph contains a plot of each result.
The graph is displayed in a figure, which is cleared each time you click the Plot button.
The figures handle is hidden so that only the GUI can display graphs in this window.
Removing Results
To remove a result from the Results list, select the row or rows you want to remove and
click the Remove button.
Running the GUI
The GUI is nonblocking and nonmodal because it is designed to be used as an analysis
tool.
GUI Options Settings
This GUI uses the following GUI option settings:
Resize behavior: Non-resizable
Command-line accessibility: Off
GUI Options selected:
Generate callback function prototypes
GUI allows only one instance to run
Opening the Simulink Block Diagrams
This example is designed to work with the f14 Simulink model. Because the GUI sets
parameters and runs the simulation, the f14 model must be open when the GUI is
displayed. When the GUI runs, the model_open subfunction executes. The purpose of the
subfunction is to:
Determine if the model is open (find_system).
Open the block diagram for the model and the subsystem where the parameters are
being set, if not open already (open_system).
Change the size of the controller Gain block so it can display the gain value (set_param).
Bring the GUI forward so it is displayed on top of the Simulink diagrams (figure).
Set the block parameters to match the current settings in the GUI.
Here is the code for the model_open subfunction:
1
2
3
4
5
6
7
8
9
10
11
12

function model_open(handles)
if isempty(find_system('Name','f14')),
open_system('f14'); open_system('f14/Controller')
set_param('f14/Controller/Gain','Position',[275 14 340 56])
figure(handles.F14ControllerEditor)
set_param('f14/Controller Gain','Gain',...
get(handles.KfCurrentValue,'String'))
set_param(...
'f14/Controller/Proportional plus integral compensator',...
'Numerator',...
get(handles.KiCurrentValue,'String'))
end
Programming the Slider and Edit Text Components
In the GUI, each slider is coupled to an edit text component so that:
The edit text displays the current value of the slider.
The user can enter a value into the edit text box and cause the slider to update to that
value.
Both components update the appropriate model parameters when activated by the user.
Slider Callback
The GUI uses two sliders to specify block gains because these components enable the
selection of continuous values within a specified range. When a user changes the slider
value, the callback executes the following steps:
Calls model_open to ensure that the Simulink model is open so that simulation
parameters can be set.
Gets the new slider value.
Sets the value of the Current value edit text component to match the slider.
Sets the appropriate block parameter to the new value (set_param).
Here is the callback for the Proportional (Kf) slider:
1
2
3
4
5
6
7
8
9
10

function KfValueSlider_Callback(hObject, eventdata, handles)
% Ensure model is open.
model_open(handles)
% Get the new value for the Kf Gain from the slider.
NewVal = get(hObject, 'Value');
% Set the value of the KfCurrentValue to the new value
% set by slider.
set(handles.KfCurrentValue,'String',NewVal)
% Set the Gain parameter of the Kf Gain Block to the new value.
set_param('f14/Controller/Gain','Gain',num2str(NewVal))
While a slider returns a number and the edit text requires a string, uicontrols
automatically convert the values to the correct type.
The callback for the Integral (Ki) slider follows an approach similar to the Proportional (Kf)
sliders callback.
Current Value Edit Text Callback
The edit text box enables users to enter a value for the respective parameter. When the
user clicks another component in the GUI after entering data into the text box, the edit
text callback executes the following steps:
Calls model_open to ensure that the Simulink model is open so that it can set simulation
parameters.
Converts the string returned by the edit box String property to a double (str2double).
Checks whether the value entered by the user is within the range of the slider:
If the value is out of range, the edit text String property is set to the value of the slider
(rejecting the number entered by the user).
If the value is in range, the slider Value property is updated to the new value.
Sets the appropriate block parameter to the new value (set_param).
Here is the callback for the Kf Current value text box:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

function KfCurrentValue_Callback(hObject, eventdata, handles)
% Ensure model is open.
model_open(handles)
% Get the new value for the Kf Gain.
NewStrVal = get(hObject, 'String');
NewVal = str2double(NewStrVal);
% Check that the entered value falls within the allowable range.
if isempty(NewVal) || (NewVal< -5) || (NewVal>0),
% Revert to last value, as indicated by KfValueSlider.
OldVal = get(handles.KfValueSlider,'Value');
set(hObject, 'String',OldVal)
else % Use new Kf value
% Set the value of the KfValueSlider to the new value.
set(handles.KfValueSlider,'Value',NewVal)
% Set the Gain parameter of the Kf Gain Block
% to the new value.
set_param('f14/Controller/Gain','Gain',NewStrVal)
end
The callback for the Ki Current value follows a similar approach.
Matlab Quick Search:
copyfile from folder to current directory matlab
run simulink from gui matlab
import parameters matlab gui modeling
simulink gui tutorial
set matlab property
running simulink from gui
path gain in matlab
matlab gui simulink tutorial
matlab gui override edit text
how to ouput parameters to matlab simuliink

Tags: Click here to add the example files to the MATLAB path, Click here to copy the files to your current
folder,Click here to display the GUI code file in the MATLAB Editor (read only), Click here to display the GUI
in the GUIDE Layout Editor (read only), click here to open the code file in the Editor, click here to open the
FIG-file in GUIDE,Click here to run the f14ex GUI, Enable, find_system, gui, GUI
building, guidata, HandleVisibility, IntegerHandle,legend, list
box, matlab, model, model_open, open_system, parameters, Parent, plot, set, set_param, sim,simulink, str
2double, web, which
Matlab Graphics Windows & the Figure
April 25th, 2010 No Comments Posted in Documents
Figures are the windows in which MATLAB displays graphics. Figures contain menus,
toolbars, user-interface objects, context menus, axes and, as axes children, all other
types of graphics objects.
MATLAB places no limits on the number of figures you can create. (Your computer systems
might impose limitations, however.)
Figures play two distinct roles in MATLAB:
Containing data graphs
Containing graphical user interfaces
Figures can contain both graphs and GUIs components at the same time. For example, a
GUI might be designed to plot data and therefore contain an axes as well as user interface
objects.
[note]See Example Using Figure Panels for an example of such a GUI.[/note]
The following diagram illustrates the types of objects that figures can contain.

Both figures and axes have children that act as containers. A uipanel can contain user
interface objects and be parented to a figure and group objects (hggroup and
hgtransform) can contain axes children (except light objects) and be parented to an axes.
See Objects That Can Contain Other Objects for more information.
Figures Used for Graphing Data
MATLAB functions that draw graphics (e.g., plot and surf) create figures automatically if
none exist. If there are multiple figures open, one figure is always designated as the
current figure, and is the target for graphics output.
The gcf command returns the handle of the current figure or creates a new figure if one
does not exist. For example, enter the following command to see a list of figure
properties:
1

get(gcf)
The root object CurrentFigure > property returns the handle of the current figure, if one
exists, or returns empty if there are no figures open:
1
2
3

get(0,'CurrentFigure')
ans =
[]
See Controlling Graphics Output for more information on how MATLAB determines where
to display graphics.
Figures that display graphs need to contain axes to provide the frame of reference for
objects such as lines and surfaces, which are used to represent data. These data
representing objects can be contained in group objects or contained directly in the axes.
See Example Transforming a Hierarchy of Objects for an example of how to use group
objects.
Figures can contain multiple axes arranged in various locations within the figure and can
be of various sizes. See Automatic Axes Resize and Multiple Axes per Figure for more
information on axes.
Figures Used for GUIs
GUIs range from sophisticated applications to simple warning dialog boxes. You can
modify many aspects of the figure to fit the intended use by setting figure properties. For
example, the following figure properties are often useful when creating GUIs:
Show or hide the figure menu, while displaying custom-designed menus (MenuBar).
Change the figure title (Name).
Control user access to the figure handle (HandleVisibility).
Create a callback that executes whenever the user resizes the figure (ResizeFcn).
Control display of the figure toolbar (Toolbar).
Assign a context menu (UIContextMenu).
Define callbacks that execute when users click drag or release the mouse over the figure
(WindowButtonDownFcn, WindowButtonMotionFcn, WindowButtonUpFcn). See also the
ButtonDownFcn property.
Specify whether the figure is modal (WindowStyle).
See the Figure Properties reference page for more information on figure characteristics
you can specify.
See the Creating Graphical User Interfaces documentation for more information about
using figure to create GUIs.
Root Object The Figure Parent
The parent of a figure is the root object. You cannot instantiate the root object because its
purpose is only to store information. It maintains information on the state of MATLAB,
your computer system, and some MATLAB defaults.
There is only one root object, and all other objects are its descendants. You do not create
the root object; it exists when you start MATLAB. You can, however, set the values of root
properties and thereby affect the graphics display.
[help]For more information, see Root Properties object properties.[/help]
More Information on Figures
See the figure reference page for information on creating figures.
See Callback Properties for Graphics Objects for information on figure events for which
you can define callbacks.
See Figure Properties for information on other figure properties.
Matlab Quick Search:
WindowsButtonDownFcn matlab
Figure Properties Matlab
matlab buttondownfcn
ButtonDownFcn
matlab resizefcn example
matlab window style
matlab windowbuttondownfcn example
matlab windowsbuttondownfcn
ResizeFcn function Matlab
surf matlab ButtonDownFcn

Tags: Automatic Axes Resize, ButtonDownFcn, Callback Properties for Graphics Objects, Controlling
Graphics Output, Creating Graphical User Interfaces, CurrentFigure >, Example Transforming a
Hierarchy of Objects,Example Using Figure Panels, figure, Figure Properties, gcf, Graphics, Graphics
Windows, gui, HandleVisibility,matlab, MenuBar, Multiple Axes per Figure, Name, Objects That Can
Contain Other Objects, plot, ResizeFcn, Root
Properties, surf, Toolbar, UIContextMenu, WindowButtonDownFcn, WindowButtonMotionFcn,WindowButton
UpFcn, windows, WindowStyle
Matlab Books and Software
April 16th, 2010 No Comments Posted in
Matlab simulink ebooks and examples

Tags: books, Debugger, development, digital image, digital signal, Functions, Functions graph, getting
started,Graphics, gui, magic Function, matlab 7, Matlab Books, matlab guide, matlab
program, simulink, software,student
MATLAB GUI (Graphical User Interface) Tutorial for Beginners
March 26th, 2010 No Comments Posted in Documents
[help]Why use a GUI in MATLAB?[/help] The main reason GUIs are used is because it makes
things simple for the end-users of the program. If GUIs were not used, people would have
to work from the command line interface, which can be extremely difficult and fustrating.
Imagine if you had to input text commands to operate your web browser (yes, your web
browser is a GUI too!).
It wouldn?t be very practical would it? In this tutorial, we will create a simple GUI that will
add together two numbers, displaying the answer in a designated text field.

This tutorial is written for those with little or no experience creating a MATLAB GUI
(Graphical User Interface). Basic knowledge of MATLAB is not required, but recommended.
MATLAB version 2007a is used in writing this tutorial. Both earlier versions and new
versions should be compatible as well (as long as it isnt too outdated). Lets get started!
Initializing GUIDE (GUI Creator)
First, open up MATLAB. Go to the command window and type in guide.

You should see the following screen appear. Choose the first option Blank GUI (Default).

You should now see the following screen (or something similar depending on what version
of MATLAB you are using and what the predesignated settings are):

Before adding components blindly, it is good to have a rough idea about how you want the
graphical part of the GUI to look like so that itll be easier to lay it out. Below is a sample
of what the finished GUI might look like.

Matlab Quick Search:
matlab gui tutorial
matlab tutorial for beginners
matlab gui tutorial for beginners
matlab tutorial gui
matlab gui tutorial deutsch
Mat Lab GUI Tutorial for Beginners
matlab simulink tutorial for beginner
tuto matlab GUI
manual for matlab gui
matlab user interface

Tags: beginner, graphical, Graphical user interface, gui, gui creator, GUIDE gui, matlab, matlab
gui, tutorial, user interface
Analysis of Functions, Interpolation, Curve Fitting, Integrals and
Differential Equations
March 23rd, 2010 No Comments Posted in Documents
In this tutorial we will deal with analysis of functions, interpolation, curve fitting, integrals
and differential equations. Firstly, we will need to use polynomials and therefore we have
to be familiar with the representation of these. A general polynomial looks like:
p(x)=anx
n
+ an-1x
n-1
+.+ a1x + a0 and is represented by a vector in Matlab:
p=[ a
n
a
n-1
....... a
1
a
0
]
Here we have a list of basic commands dealing with polynomials.
polyval(p,x): Calculates the value of polynomial p for different x. If x is a vector then the
polynomial is evaluated for each element in the vector x.
poly(A): Gives a vector that represents the characteristic polynomial for the matrix A.
roots(p): Gives a vector with the zeros for the polynomial p(x)=0.
polyder(p): Gives a vector that represents the time-derivative of the polynomial p(x). The
coefficients are sored in the vector p.
conv(p,q): Multiplies the polynomials p and q with each other. Returns a coefficient vector.
polyint(p): Integrates the polynomial p analytically and uses the constant of the integration
c. The constant c is assigned to 0, if it is not explicitly given.
residue(p,q): Makes a partial fraction expansion of p(x)/q(x).
Example 1: Zeros of a polynomial
Represent the polynomial p(x)=3x
3
+ 2x
2
-2x + 4 in Matlab and find its zeros. Lets plot
the function and check the zeros. This gives a quick idea of what the function looks like.
See the resulting figure below.
1
2
3

x=-10:0.1:10;
plot(x,3*x.^3+2*x.^2-2*x+4), title('p(x)=3*x^3+2*x^2-2*x+4')
xlabel('x'), grid
Define the polynomial. The coefficients in the polynomial are arranged in descending
order in the vector p. The orders that are nonzero in the polynomial will be represented by
zeros in the vector p.
1

p=[3 2 -2 4] % Represents the coefficients in p(x)
With polyval we can easily calculate the value of the polynomial in different x-values.
1
2

polyval(p,6), polyval(p,7), polyval(p, -5)
ans= 712 , ans = 1117 , ans = -311
[help]What do you think? Are these values correct, if we use the plot below? Make some
thinking and check your result.[/help]

Plot of a polynomial
Let us try some of the other functions that can be applied to polynomials, like polyder and
polyint. They perform the time-derivative and integrate the polynomials p(x)=3x
3
+ 2x
2
-
2x + 4. The time-derivative becomes: p(x)= 9x
2
+ 4x -2 and integration gives: P(x)=
(3/4)x
4
+ (2/3)x
3
x
2
+ 4x+C
Now compare what Matlab gives us:
1
2
3
4
5
6

C=1 % C is a integration constant.
Pder=polyder(p), Pint=polyint(p,C)
Pder =
9 4 -2
Pint =
0.7500 0.6667 -1.0000 4.0000 1.0000
[warning]That we only obtain the coefficients in the new polynomials. Introduce another
polynomial q(x)=x.[/warning]
1

q=[1 0]
Multiply the polynomial q(x) with p(x), it becomes: pq(x)= 3x
4
+ 2x
3
2x
2
+ 4x and
Matlab gives:
1
2
3

conv(p,q) % Performs a polynomial multiplication of p and q.

ans= 3 2 -2 4 0
Let us continue with other functions. Now, check the zeros in the polynomials. This is
done with the Matlab command root.
1
2
3
4
5

roots(p) % Gives a vector with zeros to the polynomial p(x).
ans =
-1.6022
0.4678 + 0.7832i
0.4678 - 0.7832i
Above we can see something quite obvious. There are 3 zeros to a third order polynomial.
It is nothing to be astounded by, but only one of these zeros is real. Can we foretell this
by looking at the plot in first figure in the tutorial. I would say yes, because if we zoom the
curve, we can find the zero-crossing. This gives us a real-valued zero. In our example
there is only one, but what happens to the other two zeros? Since they are complex-
conjugated, they are not visible.
Finally we will also take a look at the residue command. It makes a partial fraction
expansion of the polynomials p(x) and q(x). Look at the ratio q(x)/p(x)!
1
2
3
4
5
6
7
8
9
10
11
[ t,n,the_rest]=residue(q,p) % There are 3 output arguments from residue.
t =
-0.1090
0.0545 - 0.0687i
0.0545 + 0.0687i
n =
-1.6022
0.4678 + 0.7832i
0.4678 - 0.7832i
the_rest =
[]

A partial fraction expansion looks like: R(x)= t1/ ( x-n1) ) + t2/ ( x-n2) + t3/ ( x-n3) +
the_rest
Now let us define a function in Matlab. As you hopefully remember this is nothing more
than a m-file. We will call it func.m and it should be used together with an input argument
x. X is a real-valued argument.
1
2
3

% The function func.m created by MatlabCorner.Com
function f=func(x)
f=3*sin(x)-2+cos(x.^2);
We will now take a look at a plot of the function, but first we must decide what region we
are interested in. See the plot below.
1
2
3

x=-10:0.1:10;
plot(x,func(x)), grid on % Note that: fplot(@func,[-10,10])
title( 'func(x)') % works equally well.
The command fplot accepts a string as an input argument, but also a handle, @func. We
will also use handles later when dealing with figure windows for more advanced plotting
purposes, as well as when we work with GUI.

Regional Polynomial Plot
In the previous example the zeros for a polynomial were decided with the command roots.
Here on the other hand we have no polynomial, but only a function, and we can instead
use the command fzero. The fzero command uses a repetetive algorithm. We must always
add an initial guess and then the fzero tries to localize a zero closest to the guess.
Assume we would like to find the zero in the interval 0-1 in the example above. The
function has an infinite number of zeros outside this interval 0-1. Our guess becomes:
1

fzero(@funk, 0.5), fzero(@funk, 0.9), fzero(@funk, -1.5)
They all produce the same zero!
1

ans= 0.3423
Our three guesses seems to use the fact that all of them have the same sign of the time-
derivative, which and is why the algorithm converges toward 0.3423. If we change the
initial guess to be on the other side of the peak, fzero will give us a new answer (zero).
1 fzero(@funk, 1.5 )
2

ans = 1.7053
Matlab Quick Search:
matlab zeros
finite element analysis tutorial using mat lab& how to enter inputs (stiffness matrixes)
matlab function that takes 2 numbers as inputs calculates the product of the 2 numbes
takes this product and multiplies it by a random number generated by matlab rand
function and returns number as output
http://www.matlabtutorials.com/howto/gui

Das könnte Ihnen auch gefallen