0% found this document useful (0 votes)
36 views

An Introduction To MATLAB Interactive Graphics

This document provides an introduction to key MATLAB concepts including data types, flow control, graphics handling, and dialog boxes. It discusses strings, cell arrays, structures, the switch and try/catch statements, global variables, graphic object types and functions, and predefined dialogue boxes. Various data type conversion and string formatting functions are also covered.

Uploaded by

AngelAldrina
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

An Introduction To MATLAB Interactive Graphics

This document provides an introduction to key MATLAB concepts including data types, flow control, graphics handling, and dialog boxes. It discusses strings, cell arrays, structures, the switch and try/catch statements, global variables, graphic object types and functions, and predefined dialogue boxes. Various data type conversion and string formatting functions are also covered.

Uploaded by

AngelAldrina
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

An Introduction to MATLAB

Interactive Graphics

Table of Contents
Data Types............................................................................................................................................2
Strings..............................................................................................................................................2
Cell Array.........................................................................................................................................4
Structures.........................................................................................................................................6
Flow Control.........................................................................................................................................7
Switch..............................................................................................................................................7
Try Catch.........................................................................................................................................8
Global Variables...................................................................................................................................8
Handle Graphics...................................................................................................................................9
Types of Graphic Object..................................................................................................................9
Object Creation..............................................................................................................................11
Get and Set Functions....................................................................................................................13
Other Handle Graphics Functions..................................................................................................13
Predefined Dialogue Boxes................................................................................................................14

Version 1.1
1

Data Types
Strings
A string is a data type that holds a piece of text. To create a string, place the text between single
quotes.
Mystring = 'Hello World'
Strings are arrays of characters. So you can concatenate them together just like you would
concatenate two arrays.
S1 = 'Hello'
S2 = 'World'
S = [ S1 ' ' S2]

String Comparison
strcmp(S,'Yes')

% compare two strings

The result is either true or false. So the function can be used as the conditional part of a while loop
or if statement.
strcmpi(S,'Yes')

%case insensitive version of above.

There are several other functions that can be used to compare two strings. In the MATLAB
documentation, go to
MATLAB
User Guide
Programming Fundamentals
Classes (Data Types)
Characters and Strings
String Comparisons

Converting Numbers into Strings


There are several functions to convert numbers into strings. The most basic one is num2str.
S = num2str(pi)
S = num2str(pi , '%0.1f')
S = num2str(pi , '%0.2e')
S = num2str(11,'%x')

% converts pi into a string


% fixed point to one decimal place
% exponential notation to two decimal place
% present as a hexadecimal number

Anybody that has used the C programming language will recognize the format strings as being the
same as used by the fprinf and sprintf functions. These functions are also available within
MATLAB.
S = sprintf('A hexadecimal number %x \nand a fixed point number %0.1f ',11,pi)
%x

A hexadecimal number should be inserted here.

\n

Start a new line of text.

%0.1f

Insert a fixed point number with just one decimal place.

The two end arguments contain the numbers to be inserted. So this produces
S=
A hexadecimal number b
and a fixed point number 3.1
You will find much more information about formatting with sprintf in the MATLAB
documentation.
doc sprintf

Converting Strings into Numbers


There is also a function for converting a string into a number.
N = str2double('3.142')

%Convert a string into a number

Evaluate a strings as MATLAB code


You can also use a string as a command to MATLAB
s1 = 'sqrt(9)'
A = eval(s1)

% String containing the MATLAB statement


% execute the MATLAB statement

Cell Array
Cell arrays are very similar to standard arrays and matrices, except that each of the elements of a
cell array can be of a different size and type while the elements of a standard array have to be of the
same size and type,. Cells can be created in the same manner as matrices, except that you use curly
brackets instead of square brackets.
C = { 'Hello' rand(2) ; pi 'World'}
This produces 2 by 2 cell array. Two of the cells contain strings, one contains a single number and
another contains a 2 by 2 array of random numbers. Cells can also contain other cells and
structures.
Cells can also be created by using indexing.
S{1} = 'Blue'
S{2} = 'Red'
S{3} = 'Green'
S is a one by three cell array. Each element of S is a string.

Contents Indexing
Indexing using curly brackets refers to the content of cells.
A = C{1,1}
Here the contents of a particular cell is extracted and placed into the variable A.
If you want to extract the contents of several cells into variables at once, you need to provide a
variable name for the contents of each cell.
[A , B] = C{1,:}
The contents of each cell in the top row of the cell array is extracted. The first item is placed in A,
the second is placed into B.

Cell Indexing
Instead of extracting the contents of cells, you may want to create a sub cell array containing just
the specified cells. Indexing using round brackets refers to the cells themselves.
NewCell = C(1,:)
will create a new cell array containing all the cells in row one of C.

Cell Concatenation
Suppose that you create two 2 by 1 cell arrays.
c1 = {'one' ; 1}
c2 = {'two' ; 2}
There are two ways that you can merge the two cells into a single cell array.
c3 = {c1 c2}
Here c3 is a 1 by 2 cell array. Each cell contains one of the original 2 by 1 cell arrays.
c3 = [c1 c2]
in this case c3 is a 2 by 2 cell array. The two cell arrays have been concatenated into one cell array.

Structures
A structure is like a cell array, but instead of using a number to refers to individual items, the items
are given names. For example, suppose that I want to keep information about a chemical element.
I could use a cell array.
E{1} = 'Sodium'
E{2} = 'Na'
E{3} = '11'

%Name
%Symbol
%Atomic Number

However, we would have to remember that the Name is in the first element and the Symbol is in the
second element etc. If we use a structure instead, then all this information is far more obvious.
E.Name = 'Sodium'
E.Symbol = 'Na'
E.Atomic = 11

%Name
%Symbol
%Atomic Number

Each item in a structure is called a field. To access an individual field you use the name of the
structure and the name of the field separated by a full stop. A field can contain a number, a string,
an array, a cell array, or another structure.

Dynamic Field Names


You can still use a variable to specify which field we want. It is more difficult that indexing an
array. For example :
S = 'Atomic'
AN = E.(S)
If we just enter E.S, then MATLAB would look for a field called S in the structure. By placing
brackets around the variable S, the contents of brackets are evaluated before being used as a field
name.
The code below shows how to use this feature to access a structure in a for loop.
C = {'Name' 'Symbol' 'Atomic'};
for k = 1:3
FieldName = C{k};
Field = E.(FieldName);
disp(Field);
end

% Cell of field names


% extract field name from cell array
% extract field from structure
% display contents of field.

Flow Control
Switch
A switch statement uses the value of a variable to selects which code to execute.
For example
switch(DayNumber)
case 1
Day = 'Monday';
case 2
Day = 'Tuesday';
case 3
Day = 'Wednesday';
case 4
Day = 'Thursday';
case 5
Day = 'Friday';
case 6
Day = 'Saturday';
case 7
Day = 'Sunday';
otherwise
Day = [];
errordlg('Invalid day number');
end
If DayNumber is 1, Day is set to Monday, if DayNumber is 2, Day is set to Tuesday etc.
If Daynumber is not in the range 1 to 7, then the statements after otherwise are executed.
You can put several lines of code for each case if required. You can also execute the same code for
several different numbers. For example
switch(DayNumber)
case {1,2,3,4,5}
DayType = 'Week Day';
case {6,7}
DayType = 'Weekend';
end

Try Catch
Try and catch are used for error recovery. Interactive programs can generate errors because the user
makes a mistake. The aim is to catch those errors and do something sensible, rather than crash the
program. You place the vulnerable code in the try part and then the catch part will only execute if
an error occurs in the try part. For example
x = linspace(-1,1,100);

% Generate x at 100 points

try
A = inputdlg('Enter an expression');
y = eval(A{1});
plot(x,y)
catch err
errordlg(err.message);
end

% Ask user for an expression


% evaluate the expression
%Error dialogue box

In the try part the program tries to plot an expression entered by the user. It is quite possible that the
user will enter an invalid expression and cause an error. If an error does occur, the the program will
immediately jump to the catch part. The variable err after catch is optional.

Global Variables
When you write a MATLAB function, any variables within the function are local to that function.
This means that they can only be used within the function itself and cannot be accessed in any other
function or the command window. Global variables can be be accessed in several functions and
the command window. To make a variable global, you declare that it is global at the top of your
function.
global x y z
You must declare a variable as global in every function where you want to use it. This also applies
to the command window. You will not be able to see any global variables within the command
window until you declare the variable as global within the command window. Any declaration of
global variables within a function must be at the beginning of the function.

Handle Graphics
Sometimes you need to produce graphics that are different or more complex than the graphs
obtained by the standard plot functions. When you use the plot function in MATLAB, the graphics
produced is composed of simpler graphic objects. You can compose your own graphics using these
objects in what every way you wish.
Every graphical objects has a extensive selection of properties that can be configured to your own
requirements. To access these properties you use the objects handle. A graphics handle is a number
allocated to each object that uniquely identifies it.

Types of Graphic Object.


There is a hierarchy of graphical objects within MATLAB.
Root

Figures

Axes

Plot Objects

Ui Objects

Core Objects

Root
At the top is the root, which is not really a graphics object at all. It is just a starting point for
everything else. The root has a handle of zero. The root also has properties that are inherited by its
children below.
Figures
Figures are the windows that contain the graphics. Figures have integer handles. The first figure
will have the handle one, the second two etc.
All object below figures will have fractional handles. The handles use the whole range of a double
precision floating point number. So don't try to type them in yourself. Store the handle in a
variable and use the variable.
9

Axes
An axes is like the paper that a graph is plotted onto. There can be several axes in a figure. Each
axes in a figure is a child of the figure and the figure is a parent of the axes.
UI Objects
The other type of object that you can put directly into a figure are the User Interface (UI) objects
such as push buttons, sliders and check boxes.
Plot Objects
Plot object are the 2D graphs produced by plot, bar, semilog and the 3D graphs produced by surf,
mesh and plot3 etc.
Core Objects
Then there are the low level core graphical objects such as lines, text, rectangles and patches. These
are all children of an axes.

Example of a MATLAB figure

10

Object Creation
There is a function for each type of object that will create that particular object. For example
hf = figure
Will create a figure and the variable hf will contain the handle of the figure. At the same time that
you create a figure, you can set object properties.
hf = figure('Position',[100,100,500,500])
Which will create a 500 by 500 pixel figure, 100 pixels from the bottom and left of the screen.
Although there are many different object creation functions, they are all similar in the way that you
use them. In the general form of the function, you specify the name of the property and then the
value you want to assign to the property. You can put in as many name value pairs as you like.
hf = figure('Position',[100,100,500,500], 'Color',[.2,.8,.8])
If you change more than two properties, the statements lines can get very long. The normal practice
is then to split the statement over several lines using ellipses(...), so that there is one property per
line.
hf = figure('Position',[100,100,500,500],
'Color',[.2,.8,.8],
'Resize','off')

Property Help
A figure has over sixty different properties. Other objects have a similar amount. So it is fairly
unlikely that you will remember the names of all the properties and how to use them. However, all
the properties of each type of object are listed in the MATLAB online documentation, in a form that
makes it very easy to find the particular property you are looking for. Run help and click on the
MATLAB book in the contents. In the right hand side at the top, click on
Handle Graphics
Object properties
Then click on the figure tab on the top row of tabs. On the left you will then see a alphabetically
ordered list of all the figure properties. Click on any of the properties to see a description of the
property on the right. The hierarchical tree diagram at the top of the pages shows that a figure can
be the parent of an axes. On the tree click on axes. You will then see properties of an axes. On the
tree, click on Plot Objects then on lineseries. This will then show you the properties of a line plot,
as produced by the plot command.

11

Current Figure
When you create an axes, it is put into the current figure. MATLAB keeps the handle of the current
figure. If you create a new figure, that becomes the current figure. You can change the current
figure using the figure function.
figure(hf)
ha=axes;

%Change current figure to hf


%Create new axes in hf with handle ha.

You can also find the handle of the current figure with the the function gcf.
hcf = gcf

% Get current figure.

If no figure exists when you create an axes, a figure will automatically be created and become the
current figure.

Current Axes
The current axes is similar to the current figure. If you create an object that needs to be within a
axes, it is put into the current axes. The current axes is the last axes created or you can switch the
current axes using the axes function.
axes(ha)
gca

%Change current axes to ha


% Get handle of current axes

Simplified Calling Syntax


To make things easier to use, some functions have a simplified form. For example, to write the text
Hello world on an axes at positions (0.5, 0.5), I could use
text('Position',[0.5 0.5],'String','Hello world');
However, in practice you will always want to specify the string and the position. So there is a
simper way of doing this.
text(0.5,0.5,'Hello world');
Other functions have to be entered in a simpler form. For example, you would not want to enter a
plot function in this form.
plot('XData',x,'YData',y,'Color','r') % does not work.
However, the plot functions does create a graphical object, so it does have a handle, and you can use
property value pairs.
hp = plot(x,y,'r','LineWidth',2);

12

Get and Set Functions


The get function is used to read the properties of an object with a particular handle.
lw = get(hp,'LineWidth');
figcolour = get(hf,'Color');
get(gcf,'Color')
get(gcf);

%Read the line width of plot with handle hp


%Read the colour of figure hf
%Display colour of the current figure
%Display all proprieties of the current figure

The set function is used to change the properties.


set(hp,'LineWidth',3);
set(hf,'Color','w');
set(gcf,'Color','w');

%Set the line width of plot with handle hp to 3


%Set the colour of figure hf to white
%Set the colour of the current figure

Other Handle Graphics Functions


ishandle(h)

%Test if h is a graphics handle

Returns true if h is the handle of a graphical object. Can be used in the condition part of if and
while.
cla
cla(ha)
clf
clf(hf)

%clear current axes


%clear axes with handle ha
%clear current figure
%clear figure hf

delete(h)

%Delete object with handle h

13

Predefined Dialogue Boxes


Often when you are developing a GUI, you want to bring up a small window to display a message,
ask for some input or the name of a file. You could write your own GUI to do this. However,
MATLAB includes many different types of dialogue boxes ready for you to use. To see how these
work, try the following.
msgbox('Hello World')
msgbox('Hello World','My Title')
a = questdlg('Are you happy')
There are many other types of predefine dialogue boxes. To see the full list boxes, look in the
MATLAB documentation.
Help
MATLAB
Functions
GUI Development
Predefined Dialog Boxes
You will use several different predefine dialogue boxes in the exercises.

14

You might also like