Introduction To MATLAB Interactive Graphics

Similar documents
INTRODUCTION TO MATLAB INTERACTIVE GRAPHICS EXERCISES

INTRODUCTION TO THE MATLAB APPLICATION DESIGNER EXERCISES

QUICK INTRODUCTION TO MATLAB PART I

There are two ways to launch Graphical User Interface (GUI). You can either

12 whereas if I terminate the expression with a semicolon, the printed output is suppressed.

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

Special Topics II: Graphical User Interfaces (GUIs)

PART 1 PROGRAMMING WITH MATHLAB

Computational Methods of Scientific Programming. Matlab Lecture 3 Lecturers Thomas A Herring Chris Hill

Building a Graphical User Interface

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

Dr Richard Greenaway

Programming 1. Script files. help cd Example:

Still More About Matlab GUI s (v. 1.3) Popup Menus. Popup Menu Exercise. Still More GUI Info - GE /29/2012. Copyright C. S. Tritt, Ph.D.

Signal and Systems. Matlab GUI based analysis. XpertSolver.com

Computational Methods of Scientific Programming

Basic Computer Programming (Processing)

MATLAB Introduction to MATLAB Programming

Lecture 1: Hello, MATLAB!

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

MATLAB Project: Getting Started with MATLAB

ECE Lesson Plan - Class 1 Fall, 2001

1. Register an account on: using your Oxford address

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Introduction to Scientific Computing with Matlab

Draw beautiful and intricate patterns with Python Turtle, while learning how to code with Python.

Lecture 12. Data Types and Strings

MATLAB Project: Getting Started with MATLAB

Digital Media. Seasons Assignment. 1. Copy and open the file seasonsbegin.fla from the Read folder.

Data Types and Variables in C language

MATH (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

AQA Decision 1 Algorithms. Section 1: Communicating an algorithm

% Edit the above text to modify the response to help Video_Player. % Last Modified by GUIDE v May :38:12

7 HANDLE GRAPHICS IN THIS CHAPTER 7.1 GRAPHICS OBJECTS 7.2 GRAPHICS OBJECTS HIERARCHY 7.3 GRAPHICS OBJECTS HANDLES 7.4 PROPERTIES 7.

CISC 1600 Lecture 3.1 Introduction to Processing

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

Part #10. AE0B17MTB Matlab. Miloslav Čapek Viktor Adler, Pavel Valtr, Filip Kozák

Expressions and Variables

Introduction to MATLAB

SPARK-PL: Introduction

Your First Windows Form

Introduction to MATLAB Programming. Chapter 3. Linguaggio Programmazione Matlab-Simulink (2017/2018)

The Department of Engineering Science The University of Auckland Welcome to ENGGEN 131 Engineering Computation and Software Development

Introduction to MATLAB

Arrays. Array Basics. Chapter 8 Spring 2017, CSUS. Chapter 8.1

SBT 645 Introduction to Scientific Computing in Sports Science #5

BUILDING A MATLAB GUI. Education Transfer Plan Seyyed Khandani, Ph.D. IISME 2014

MATLAB Second Seminar

Enumerated Types. CSE 114, Computer Science 1 Stony Brook University

How to succeed in Math 365

Step by step set of instructions to accomplish a task or solve a problem

LAB 1 General MATLAB Information 1

Introduction to Matlab. By: Hossein Hamooni Fall 2014

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us?

MATLAB TUTORIAL WORKSHEET

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++.

MAXQDA and Chapter 9 Coding Schemes

MATLAB SUMMARY FOR MATH2070/2970

Using Microsoft Word. Tables

CNBC Matlab Mini-Course

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

FLORIDA INTERNATIONAL UNIVERSITY EEL-6681 FUZZY SYSTEMS

Text & Design 2015 Wojciech Piskor

MATLAB GUIDE UMD PHYS401 SPRING 2011

In the first class, you'll learn how to create a simple single-view app, following a 3-step process:

MATLAB. Creating Graphical User Interfaces Version 7. The Language of Technical Computing

The Mathcad Workspace 7

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Introduction to MATLAB programming: Fundamentals

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window.

1 Introduction to Matlab

INTRODUCTION TO MATLAB

My First iphone App. 1. Tutorial Overview

Matlab Tutorial 1: Working with variables, arrays, and plotting

LAMPIRAN 1. Percobaan

Introduction to Matlab

An Introduction to Processing

MATLAB Introductory Course Computer Exercise Session

LAB 1 Binary Numbers/ Introduction to C. Rajesh Rajamani. ME 4231 Department of Mechanical Engineering University Of Minnesota

ORB Education Quality Teaching Resources

CMPT 100 : INTRODUCTION TO

Exercise 1 Using Boolean variables, incorporating JavaScript code into your HTML webpage and using the document object

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

Department of Chemical Engineering ChE-101: Approaches to Chemical Engineering Problem Solving MATLAB Tutorial Vb

MATLAB. MATLAB Review. MATLAB Basics: Variables. MATLAB Basics: Variables. MATLAB Basics: Subarrays. MATLAB Basics: Subarrays

MATLAB 1. Jeff Freymueller September 24, 2009

Computer Science Lab Exercise 2

My First Cocoa Program

The Language of Technical Computing. Computation. Visualization. Programming. Creating Graphical User Interfaces Version 1

Need help? Call: / DOCMAIL: PRINT DRIVER USER GUIDE

Display Input and Output (I/O)

Intermediate Programming, Spring 2017*

Chapter 2: Lists, Arrays and Dictionaries

Full file at

Downloaded from Chapter 2. Functions

3. Java - Language Constructs I

More on Plots. Dmitry Adamskiy 30 Nov 2011

Transcription:

Introduction To MATLAB Interactive Graphics Eric Peasley, Department of Engineering Science, University of Oxford version 3.0, 2017

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 Changing Object Properties...13 Other Handle Graphics Functions...13 Predefined Dialogue Boxes...14 Guide...15 Version 3.0 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 The function strcmp compares two strings strcmp(mystring,'hello world') %Compare two strings The result is either true or false. The case above will be false because of the capital letters in the original string. There is a case insensitive version that will give true. strcmpi(mystring,'hello world') %Case insensitive version The function can be used as the conditional part of a while loop or if statement. There are several other functions that can be used to compare two strings. To find out more, enter doc string comparisons in the MATLAB command window. 2

Converting Numbers into Strings There are several functions to convert numbers into strings. The most basic one is num2str. S = num2str(pi) % converts pi into a string S = num2str(pi,'%0.1f') % fixed point to one decimal place S = num2str(pi,'%0.2e') % exponential notation, 2 decimal place S = num2str(11,'%x') % 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('hexadecimal %x \nand fixed point %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 = 'hexadecimal b and fixed point 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 string 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 in s1 3

Cell Array Cell arrays are very similar to standard arrays and matrices, except that each of the elements is a cell that can hold data of different size and type. So for example, the first cell could be a string, the second could be a number etc. Elements of a standard array have to be of the same size and type. Cell arrays can be created in the same manner as matrices, except that you use curly brackets instead of square brackets. C = {'Time' 'Disturbance' ; 1:200 rand(1,200)} This produces a 2 by 2 cell array. The top two cells contain strings, the bottom two contain vectors. Cells can also contain other cell arrays and structures. Cell arrays can also be created by using indexing. MyCell{1} = 'Blue' MyCell{2} = 'Red' MyCell{3} = 'Green' MyCell is a 1 by 3 cell array. Each cell contains 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. [string1,matrix1] = C{[1 2],1} The contents of the first two cells in column one of the cell array is extracted. The first item is placed in variable string1, the second is placed into matrix1. 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 2],1) This creates a new cell array containing the first two cells in column one of C. You can write to multiple cells in one line. MyCell(4:6) = {'Cyan' 'Magenta' 'Yellow'} Adds three more colours to the cell array MyCell. 4

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. c3a = {c1 c2} Here c3a is a 1 by 2 cell array. Each cell contains one of the original 2 by 1 cell arrays. c3b = [c1 c2] in this case c3b is a 2 by 2 cell array. The two cell arrays have been concatenated into one cell array. An easy way to look at the content of a cell array is to double click on the variable in the Workspace window on the right of the Command Window. This opens the variable in the Variable Editor. 5

Structures A structure is like a cell array, but instead of using a number to refer to individual items, the items are given names. For example, suppose that we want to keep information about a chemical element. We 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. Chem.Name = 'Sodium'; Chem.Symbol = 'Na'; Chem.Atomic = 11 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 use a variable to specify which field you want. For example : S = 'Atomic'; AN = Chem.(S) If we just enter Chem.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'}; % Cell of field names for k = 1:3 FieldName = C{k}; % extract field name from cell array Field = Chem.(FieldName); % extract field from structure disp(field); % display contents of field. end 6

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 7

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: '); %Ask for an expression y = eval(a{1}); %Evaluate expression plot(x,y) catch err errordlg(err.message) %Error dialogue box end 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 called err, is a structure containing information about the error that has occurred. A field called message in this structure contains the error message. This is displayed in an error dialogue box. 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 a b c 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. 8

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 are composed of simpler graphic objects. You can compose your own graphics using these objects in what ever way you wish. Every graphical object 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 structure allocated to each object. The structure has a field for each property. Types of Graphic Object. There is a hierarchy of graphical objects within MATLAB. Root Figures Axes Ui Objects Plot Objects Primitive 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 also has properties that are inherited by its children below. The function groot returns the handle of the root. Figures Figures are the windows that contain the graphics. 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. 9

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 objects are the 2D graphs produced by plot, bar, semilog and the 3D graphs produced by surf, mesh and plot3 etc. Primitive Objects Then there are the low level graphical objects such as lines, text, rectangles and patches. A patch is a n sided shape, defined by the coordinates of the corners. 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 as 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, this is known as name-value pairs. You can put in as many name-value pairs as you like. There are two in the example below. hf = figure('position',[100,100,500,500],'color',[.2,.8,.8]) MATLAB is an American program, so you need to use color, the American spelling. If you change more than two properties, the statements lines can get very long. The normal practice is 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 Inspector 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. The properties of each type of object are listed in the MATLAB online documentation. To see the documentation on the figure properties, enter into the MATLAB command window doc figure properties This is a very extensive document. It is much easier to use the property inspector to find out about an objects properties. In the command window enter inspect(h) where h is the handle of the object. This will list all the properties of the object and there current value. You can use the inspector to change the value of a property. You can also use the inspector to find the online help for that property. Right click on the property and select What's This? This will take you directly to the description of the property in the online documentation. 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 a 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. If you click on a figure, then that becomes the current figure. Current Axes The current axes is similar to the current figure. If you create an object that needs to be within an 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 You can also select a different current axes by clicking on an 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') 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 There') 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

Changing Object Properties There are a number of ways to change the properties after it has been created. The original method used the function get to find a properties value and the function set to change the value. lw = get(hp,'linewidth') %Read line width of plot with handle hp set(hp,'linewidth',3) %Set line width of plot with handle hp Since MATLAB release R2014b, object handles are structures. So you no longer need to use the set and get functions to change object properties. The modern equivalent to the above is lw = hp.linewidth hp.linewidth = 3 Here are more examples figcolour = hf.color hf.color = 'w' %Read the colour of figure hf %Set the colour of figure hf to white Unfortunately, gcf is a function and not a structure. You can use gcf in get and set but you cannot use the structure notation. get(gcf,'color') get(gcf) set(gcf,'color','g') %Display colour of the current figure %Display all proprieties of the figure %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) delete(h) %clear current axes %clear axes with handle ha %clear current figure %clear figure hf %Delete object with handle h 13

Predefined Dialogue Boxes Often when you are developing a Graphical User Interface, 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 program 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, look in the MATLAB documentation. doc Dialog Boxes You will use several different predefine dialogue boxes in the exercises. 14

Guide Guide is a Computer Aided Design tool for MATLAB Graphical User Interfaces. It allows you to select different types of graphic objects and drag them into position on to a figure. The example below show a guide window containing a design for a temperature conversion GUI. This GUI uses two types of objects. The white boxes are Edit Text objects. Users can type into an edit text box. The words are Static Text objects. You can change the properties of an object by double clicking on an object. This opens the properties inspector. The callback function properties are important. They define the function that runs when you interact with an object. For example, when you enter text into a Edit Text box, a callback function is run. Guide will automatically set the name of the callback function for each of the interactive objects using the objects Tag property. You can change the Tag. 15

When you save your design, it is stored into a.fig file. At the same time, the associated.m file, the MATLAB program for the GUI is created and opened in the MATLAB editor. The program consists of the callback functions required to interact with the GUI. For example, the Temperature Converter GUI is called tconv for short. The design is saved into tconv.fig and the program is called tconv.m. The Tag property for the Celsius and Fahrenheit edit boxes has been changed to editc and editf respectively. The program tconv.m contains 7 functions. The top function is tconv() itself. You normally do not change the top level function. Then there are 2 functions for the figure and another 2 functions for each of the Edit Texts. function tconv_openingfcn(hobject, eventdata, handles, varargin) function varargout = tconv_outputfcn(hobject, eventdata, handles) function editc_callback(hobject, eventdata, handles) function editc_createfcn(hobject, eventdata, handles) function editf_callback(hobject, eventdata, handles) function editf_createfcn(hobject, eventdata, handles) In general, a GUI will have these types of function. OpeningFcn OutputFcn Callback CreateFcn This is called just before the GUI opens. This is used for returning data from the application. Executes when the user interacts with the object. e.g. Clicks on a button, moves a slider or enters text into an edit text. Executes when the object is created. Callback functions have a special form, with specific inputs. The two inputs that you need to use are :- hobject handles The handle of the object associated with the function. A structure containing the handles of all the objects in the GUI. The field name of each handle is the same as the Tag. You can add your own fields to the handles structure for your own data. Between functions calls, the handles structure is stored in the data property of the GUI's figure. So if you change the data in handles, you need to write the structure back into the data store, using the function guidata. For example. guidata(handles.figure1,handles); 16

For the Temperature Converter, the structure handles contains the following. Field Name figure1 editf editc text3 text2 text1 Output Description The figure handle The Fahrenheit Edit Text handle The Celsius Edit Text handle The handle of the static text Temperature Converter The handle of the static text Fahrenheit The handle of the static text Celsius What the GUI will return To get the program to work, you then insert your own code into the functions. To complete the Temperature Converter GUI, you would just add the following to the end of the function editc_callback. str = get(hobject,'string'); C = str2double(str); F = C*9/5+32; str = num2str(f); set(handles.editf,'string',str); % Get string from C Edit Text % Convert string to number % Convert Celsius to Fahrenheit % Convert number to string % Write str to F Edit Text. and then add the following to the end of the function editf_callback. str = get(hobject,'string'); F = str2double(str); C = (F-32)*5/9; str = num2str(c); set(handles.editc,'string',str); % Get string from F Edit Text % Convert string to number % Convert Fahrenheit to Celsius % Convert number to string % Write str to C Edit Text. 17