MATLAB Introductory Course: Notes

27
Course Notes Getting Started with MATLAB PsiPhiETC January 1, 2012

description

These are course notes for Getting Started with MATLAB prepared by PsiPhiETC (www.psiphi.in). The course includes interactive computations, programming, graphics, simulink and GUI development. These notes can be read along with course slides available on website.

Transcript of MATLAB Introductory Course: Notes

Page 1: MATLAB Introductory Course: Notes

Course Notes

Getting Started with MATLAB

PsiPhiETC

January 1, 2012

Page 2: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 1

Contents1 Motivation 1

1.1 Why this course? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 What is MATLAB? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.3 Features of MATLAB! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.4 Course Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.5 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.6 Desktop Tools & Development Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.7 Ways to Get Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.8 Some General Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.9 Vectors and Scalars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.10 Simple Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.11 MATLAB Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.12 Matlab Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.13 MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

2 Interactive Computations 32.1 Matrix Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.2 Matrix Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.3 Matrix Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.4 Matrix Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.5 Elementary Maths Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.6 Character Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.7 Saving and Loading Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

3 Programming in MATLAB 43.1 Script Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43.2 Function Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53.3 Control Flow: if-elseif-else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53.4 Control Flow: for loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53.5 Control Flow: while loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63.6 Control Flow: switch-case-otherwise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63.7 break, continue, return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73.8 Interactive Input: input, keyboard and pause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73.9 Input/Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

4 Creating Graphics Programmatically 74.1 Figure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74.2 Setting Figure Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84.3 Axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84.4 Setting Axes Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84.5 Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84.6 Setting Plot Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84.7 Overlay Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94.8 Putting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94.9 Axis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94.10 Legend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104.11 Subplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104.12 Findobj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 3: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 2

5 Creating Graphics Interactively 105.1 Graphics Objects Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105.2 Plotting Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115.3 Figure Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115.4 Plotting Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115.5 Figure Palette: New Subplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115.6 Figure Palette: Variables and Plot Catalog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115.7 Figure Palette: Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115.8 Plot Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115.9 Property Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115.10 Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125.11 Exporting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125.12 Saving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

6 Publishing Report 126.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126.2 Code Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126.3 Document Title and Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126.4 Section and Section Titles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136.5 Other Text Markup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136.6 More Text Markup. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136.7 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136.8 Displaying Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146.9 Example File for Publishing Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

7 Building GUI 147.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147.2 GUIDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147.3 Creating Simple GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157.4 Creating Simple GUI. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157.5 Programming Simple GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

8 Simulink 168.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168.2 User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168.3 Example 1: Sine Wave and its Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168.4 Example: Spring Mass System (Direct Approach) . . . . . . . . . . . . . . . . . . . . . . . . . . . 168.5 Example: Spring Mass System (Transfer Function) . . . . . . . . . . . . . . . . . . . . . . . . . . 178.6 Example: Capacitor Charging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

9 Homework 19

List of Figures1 Sine wave and its Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 Spring Mass System (Direct Approach) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 Spring Mass System (Transfer Function) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 Capacitor Charging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

List of Tables

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 4: MATLAB Introductory Course: Notes

1 Motivation

1.1 Why this course?This, Getting Started With MATLAB, is an introductory course designed for newcomer to the MATLAB. Thenewcomer may be interested in MATLAB for (i) completing his current assignment (ii) curiosity (iii) desire forvalue addition. The course objective is to initiate participant into MATLAB and then develop a belief for self-learning.

1.2 What is MATLAB?The MATLAB is language of high-performance scientific computing. The MATLAB system integrates computation,visualization and programming in an easy to use environment. Major components of the system are (i) desktop toolsand development environment (ii) mathematical function library (iii) programming (iv) graphics and (v) externalinterface.

1.3 Features of MATLAB!The MATLAB provides multiple features to the user. Some of these features are (i) extensive library of in-built math-ematical functions (ii) interactive computations through command window (iii) programming of complex problems(iv) graphics for data analysis and visualization (v) creation of graphical use interface e.g. GUIDE (vi) specializedtoolboxes like Simulink.

1.4 Course ContentsThe major topics to be covered in the course are (i) introduction (ii) interactive computations (iii) programmingand scripts (iv) programming and functions (v) graphics (vi publishing report (vii) basics of graphical user inter-face development and Simulink. The references textbook is latest edition of Getting Started with MATLAB byRudra Pratap [5] (low price edition is available). Other good references are Getting Started Guide [2] and CreatingGraphical User Interface [1]. MATLAB help is an indispensable source for learning.

1.5 InstallationThe MATLAB is available for all major computing platforms (Windows, Unix, Mac). The MATLAB environmentis almost similar for Windows and Unix (except some operating system dependent feature). The official websiteis http://www.mathworks.com. Read installation instructions carefully before starting installation. Checkinstallation once it is completed.

1.6 Desktop Tools & Development EnvironmentThe reference for this topic is Chapter 7 of Getting Started Guide [2]. The default desktop layout contains Menu Baron top, Tool Bar just below menu bar, a folder browser and launchpad on bottom left with name Start. The desktopcontains panels for different activities and are named as (i) command window (ii) current folder (iii) workspace and(iv) command history. Top right of each panel gives option for minimizing, maximizing, un-docking and closing.To revert back to default desktop layout follow Menubar > Desktop > Desktop Layout > Default. The desktoplayout may be changed by File > Preference.

The current folder panel is used for managing files. It show contents of present working directory (pwd) andyou can create new files or folders. The search feature allow you to search files. It provide advance features in theform of reports for code analyzer report, dependency report etc. Also, you can see different attributes (e.g. file size)of files and sort file according to different options.

The command window is main window of MATLAB Desktop. It is used for entering variable, running script andfunctions and for interactive computations. The pwd command return present working directory. The ls commandlists directory contents on Unix and dir command lists directory contents in Windows. In command window, trymagic(3), x=2, y=x*x etc.

Page 5: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 2

The commands that we type in command window are stored in command history. The commands may beexecuted from here. You may select and execute multiple commands from command history. See the context menu(by selecting and right click) for more options.

The workspace is used to see variable defined in the MATLAB session. The command who displays the variablenames and whos displays the attributes of these variables.

The MATLAB Editor is used for creating new files or opening existing files.

1.7 Ways to Get HelpThe MATLAB provides excellent and extensive documentation in the form of help. There are multiple ways to gethelp. The Help Browser in MATLAB Desktop can be used for browsing and searching almost all topics. You maylook at demos for quick overview. In our view, beginners to MATLAB are very likely to get lost in extensive helptopics. The help shall be used whenever a requirement arises.

The commands lookfor, help and which are very handy. The lookfor ‘keyword’ returns name and brief descriptionof functions relevant to ‘keyword’. The help ‘FunctionName’ returns the help of ‘FunctionName’. The which‘FunctionName’ returns path of directory that contains the ‘FunctionName’. The section titled ‘Using Built-inFunction and On-line Help’ in Rudra Pratap [5] is strongly recommended.

1.8 Some General CommandsThe clc is for clearing command window. The clear is for clearing workspace variable. The clear var1 var2 var3clears var1, var2 and var3. The clear all clears all the workspace variables. The cd is used for changing directoryand mkdir for making new directory. When we call a function from command window the MATLAB search for thisfunction in pwd and others directories on MATLABPATH. The path returns the directories MATLABPATH. Youmay add new directory by using addpath DirectoryPath. The copyfile source destination copies a file from source todestination. The delete shall be used carefully as it delete file permanently. The diary is used for recording MATLABsession and quit for quitting MATLAB. To recall a command from history just enter one (or more) character andpress up arrow key (smart recall). See help on various command for details.

1.9 Vectors and ScalarsThe variable name shall start with an alphabet, and can have a sequence of alphabets, digits and underscore (_ ).The vector is contained in square brackets [ ]. The elements in a row vector are are separated by column separator,a comma or blank space. The elements in a column vector are separated by row separator, semicolon. Example,RowVector=[1, 2, 3], ColumnVector=[1;2;3]. A column vector can be converted into row vector by transposeoperator, ’ e.g. v=u’, and vice-versa. If a vector is too long, it can be continued to next line by using ellipsis, . . . .The semicolon at the end of command suppresses display of output in command window. A colon operator, : isused for defining a vector whose first element (a), last element (b) and increment (∆) between successive elementsis known e.g. v = a : ∆ : b. The ∆ can be positive (b > a) or negative (b < a) and if it is not specified then it takesdefault value of 1. The linspace (a,b,n) is used for defining a vector of n linearly spaced elements with a as firstelement and b as last element. The vector operators are + for addition, - for subtraction, cross for cross product, dotfor dot product, .* for component wise product, ./ for component wise division and .ˆ for component wise power.The functions sin, cos, log, sqrt etc can take scalar as well as vector arguments. The format is used for changingformat of number displayed in command window.

1.10 Simple PlotsMATLAB Graphics is very powerful and user-friendly. Let y be a vector of length n. The plot(y) plots the points(i, yi), where yi is the ith element of y, and connect these points by solid straight line. Let x be another vectorof length n. The plot(x,y) plots the points (xi, yi), where xi & yi are the ith element of x & y, and connectthese points by straight line. The title(’TitleString’) insert title, xlabel(’XLabelString’) insert label on x-axis andylabel(’YLabelString’) insert label on y-axis. The command grid on | off is used for making grid on or off.

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 6: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 3

1.11 MATLAB EditorThe Editor is used for creating new files and/or opening existing files. Use File > New , File > Open or editFileName. This will open file in MATLAB Editor. The Editor contains menu bar on top, tool bar below menu bar,editing space in the middle, line numbers on the left, code analysis message bar on right, document bar at bottomleft and status bar at bottom right.

1.12 Matlab ScriptThe MATLAB scripts are defined in .m file. A script file contains comments and valid MATLAB commands andexpressions. The comment starts with a percentage character, %, and it can appear anywhere in a line. The contentsof a line immediately after % is comment. The Editor display comments in green color. The MATLAB keywordsare displayed in blue color. The script can be executed by Green Arrow toolbar.

The first comment line is called H1 line. This line shall describe what script do. The lookfor command returnsthe H1 line.

The script file also contain help giving usage details etc. The comment lines following H1 line constitutes helpand these lines are returned by help command. The help starts from H1 line and end at first blank line following H1.

1.13 MATLAB FunctionsThe MATLAB functions are defined in .m file with file name same as function name.

The first line declare the function and starts with keyword function. The syntax of this line is, function [ar-gout]=FunctionName(argin), where argin is the input argument and argout is output argument. The input argu-ment(s) are passed by value. The variables defined within he function are local to it. It shall be kept in mind thatFunctionName shall not conflict with name of in-built functions. The exist function of MATLAB is used to findwhether FunctionName already exist or not.

The first comment line following function decleration is called H1 line. This line shall describe what thisfunction do. The lookfor command returns the H1 line.

The function file also contain help giving details of syntax, usage, example and brief description. The commentlines following H1 line constitutes help and these lines are returned by help command. The help starts from H1 lineand end at first blank line following H1.

2 Interactive Computations

2.1 Matrix CreationThe strength of MATLAB is it highly efficient matrix computation algorithms. The simplest way of matrix creationis to enter its element from command line. The matrix is enclosed in square bracket []. Its elements are entered rowwise. The columns in a row are separated by space of comma (recommended). The rows are separated by semicolon(;). If entries does not fit into a line then use ellipsis (. . . ) for continumation.

2.2 Matrix IndexingFor a matrix A(i, j) = aij . The [m,n]=size (A) returns number of rows as m and number of columns as n. To geta submatrix, use A(m1 : m2, n1 : n2), where row number varies from m1 to m2 and column number varies fromn1 to n2. To get all the rows, use A(:, n1 : n2), and to get all the columns, use A(m1 : m2, :). The end is numberof rows when used at rows place and number of columns when used at columns place e.g. A(:,k:end) is submatrixwith all rows and column number k to last column.

2.3 Matrix ManipulationLet A be a matrix with m row and n column. To replace a single element (say A(i,j)) by a scalar (say b), simplyuse A(i, j) = b. To replace ith row (A(i,:)) by a row vector (v1×n), use A(i, :) = v1×n. To replace jth column

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 7: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 4

(A(:,j)) by a column vector (vm×1), use A(:, j) = vm×1. For replacing a submatrix, use A(m1 : m2, n1 : n2) =B(m2−m1)×(n2−n1). The matrix A can be appended by adding a row or column of appropriate size. The way todo so is A=[A, vm×1], A=[A; v1×n]. To delete a row or column, replace it by empty matrix ([]) e.g. A(m,:)=[],A(:,n)=[]. The MATLAB provided inbuilt functions for creating matrix with all elements zeros (zeros(m,n)), matrixwith all elements ones (ones(m,n)), identity matrix (eye(m,n)) etc. The function magic(n) generates a magic squareof size n.

2.4 Matrix OperationsThe arithmetic operations, +, - and * are as usual. The A/B is equal to AB−1. The ^ is power operation formatrix. The element wise operation for multiplication, division and power are, .*, ./, and .^ , respectively. Theelement wise relational operations on matrix are <, >, <=, >=, ==, ≈=. Let A and B are of size m× n. The ARELationalOPeration B is matrix of size m × n, with element value 1 when relation is true and 0 when relation isfalse. The element wise logical operation on matrices are AND (&), OR (|) and NOT (≈). TheA LOGicalOPerationB is matrix of size m × n, with element value 1 when operation returns true and 0 when operation returns false.Apart from, these operations, there are logical functions like all, any, exists, isempty, isinf, isnan. See help on thesefunctions.

2.5 Elementary Maths FunctionsThe MATLAB has inbuilt definition of almost all elementary maths function. You can directly call these functionsfrom command window, script or function files. To get list of elementary functions, type help elfun. Some examplesare trigonometric functions (sin, cos, tan, asin, acos, atan, sinh, . . . ), exponential functions (exp, log,. . . ), algebraicfunctions (sqrt, nthroot, . . . ), complex number functions (abs, angle, conj, img, real), round-off functions (floor,ceil, fix, mod, rem). Most of these functions take scalar as well as vector arguments. The functions expm, sqrtm,takes matrix as argument. See help on these functions for usage and other details.

2.6 Character StringsThe string in MATLAB is a sequence of characters in single quote. The function eval takes a string (a valid MAT-LAB expression) argument and evaluate it. The num2str is used for converting a number to string and str2num isused for converting a string to number. The lower converts upper case alphabets to lower case and upper do the con-verse. The strcmp and strncmp is used for comparing two strings. The strcat is for string concatenation. The findstrfinds one string within another. Observe how string and numbers are displayed differently on command window.See online help for details.

2.7 Saving and Loading DataThere are various ways to save data to file and load data from file. The function save saves data from workspaceto file (matlab.mat). This file name and variable to be saved into it can be specified as argument to save. The loadfunction load data from file to workspace. The load can be used for .mat file as well any other ASCII file (providedit every row has same number of columns). See online help on save and load for details.

3 Programming in MATLAB

3.1 Script FilesThe MATLAB provides programming features for solving complex problems. The script files are simplest way tolearn these programming features. The script file contains sequence of valid MATLAB commands and expressions.The name of script file shall start with a letter and can have letters, digits and underscore (_). The filename shallnot clash with names of built-in functions. Use exits to find whether a built-in with same name exist or not. Thename of any variable shall not be same as name of script file. The script file works on global workspace variable i.e.workspace variable are accessible to script and vice versa. Given below is example script file from reference [5].

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 8: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 5

1 % solvex.m (Ref: RP)2 % 5 x1+2r x2+r x3=23 % 3 x1+6 x2+(2r-1) x3=34 % 2 x1+(r-1) x2+3r x3=55 A=[5, 2*r,r;3, 6, 2*r-1; 2, r-1, 3*r];6 b=[2;3;5];7 x=A\b

3.2 Function FilesThe function file is one of the key feature of MATLAB. It begin with a function definition line with syntax,

1 function [argout] = FunctionName (argin)

Here, function is MATLAB keyword. The argout is list of output variables. FinctionName is the name of function.The function file must be saved with same name as FunctionName with extension .m. The argin is the list of commaseparated input arguments. Other features are H1 line, comment lines used by online help and body of the function.You are strongly recommended to read section titled ‘Writing good function’ in reference [5]. A function shall bebased on good pseudo-code and shall have features like readability, modularity, robustness and expandability. Givenbelow is example function file, solvexf.m, from reference [5].

1 function [det_A, x]=solvexf(r)2 % SOLVEXF solves a 3x3 matrix eqn with parameter r3 % This is the function file solvexf.m4 % To call this function, type:5 % [det_A,x]=solvexf(r)6 % r is input and det_A and x are o/p7

8 A=[5, 2*r, r; 3,6, 2*r-1; 2, r-1, 3*r];9 b=[2;3;5];

10 det_A=det(A);11 x=A\b;

3.3 Control Flow: if-elseif-elseThis construction provides logical branching for computation. The syntax is,

1 if expression2 statements3 elseif expression4 statements5 else6 statements7 end

Given below is an example from MATLAB on-line help on if.

1 if I == J2 A(I,J) = 2;3 elseif abs(I-J) == 14 A(I,J) = -1;5 else6 A(I,J) = 0;7 end

3.4 Control Flow: for loopsThe for loop is used to repeat statement(s) for a fixed number of times. The syntax of the for loop is,

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 9: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 6

1 for variable = expression2 statement(s)3 end

The columns of the expression are stored one at a time in the variable and then the following statements, up to theend, are executed. The for loops can be nested, but every for must be matched with an end. Given below is theexample that find sum of first 100 natural numbers,

1 sum=0;2 for i=1:1003 sum=sum+i;4 end

3.5 Control Flow: while loopsThe while loop is generally used to execute statement(s) for an indefinite number of times until condition specifiedby while is no longer satisfied. The general form of a while loop is:

1 while expression2 statements3 end

Given below is an example of while loop,

1 v=1; num=1; i=1;2 while (num≤4096)3 v=[v;num];4 i=i+1;5 num=2^i;6 end7 v

3.6 Control Flow: switch-case-otherwiseThe switch-case-otherwise construction provides logical branching for computation. A flag is used as a switch andthe values of the flag make up different cases for execution. The general syntax is:

1 switch flag2 case value13 block 1 computation4 case value25 block 2 computation6 otherwise7 last block computation8 end

Given below is an example of switch-case,

1 color= input('color= ','s');2 switch color3 case 'red'4 c=[1, 0, 0];5 case 'green'6 c=[0, 1, 0];7 case 'blue'8 c=[0, 0, 1];9 otherwise

10 error('invalid choice')11 end

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 10: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 7

3.7 break, continue, returnThe command break inside a for or while loop terminates the execution of the loop. The command continue passcontrol to the next iteration of for or while loop. The command return simply returns the control to the invokingfunction.

3.8 Interactive Input: input, keyboard and pauseThe MATLAB provides facility for taking input interactively from command window. The command input (’string’)displays the text in string on command window and waits for the user to give keyboard input. The input (’string’,’s’) saves the user input in string. Given below are two examples:

1 Age=input('Age Plz?')2 Name=input('Name Plz?', 's')

The command keyboard returns control from script/function to keyboard. The command window prompt changesto k�. At this point, you can check variable already computed, change their values, and issue any valid MATLABcommands. The control is returned to script/function by typing the word return and then pressing enter key.

The command pause temporarily halts the current process. It can be used with or without optional argument.

3.9 Input/OutputThe MATLAB supports standard C-language file I/O function for reading from and writing to files. The fopen opensan existing file or creates a new file and fclose closes an opened file. The fprintf is used for writing formatted datato file and fscanf for reading formatted data from file. The sprintf writes data in formatted string and sscanf readsstring in specified format. The fgetl reads a line from a file discarding new-line character whereas fgets reads a linefrom a file including new-line character. Given below is a script file from reference [5].

1 % TEMPTABLE - generates and writes a temperature table2 % Script file to generate a Fahrenheight-Celsius temperature table. The table is written in ...

file named 'Temperature.table'3 %-----------------------------------------------------------4 F=-40:5:100;5 C=(F-32)*5/9;6 t=[F;C];7 fid=fopen('Temperature.table','w');8 fprintf(fid,' Temperature Table \n ');9 fprintf(fid,' Fahernheight Celsius \n');

10 fprintf(fid,' %4i %8.2f\n',t)11 fclose(fid)

4 Creating Graphics Programmatically

4.1 FigureThe command figure opens a new figure window and returns its handles (an object that is used to see or changeproperties of figure window). You can open multiple figure windows, each having separate handle, at the same time.The figure that is visible and is above others on screen is called current figure. The command figure (h), make thefigure with handle h as current figure. The command gcf returns the handle of current figure. Some of the figureproperties are its color, name, position, etc. The position is specified by a vector of size four. First two elementsgives x and y coordinates of lower left corner. Third element is width of figure window and fourth element is itsheight. The figure window has a menubar. You can hide/display this by setting Menubar property to ‘none’/‘figure’.To change the figure properties, follow, Edit > Figure Properties > More Properties.

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 11: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 8

4.2 Setting Figure PropertiesYou can see figure properties by get (h) command, where h is figure handle. The properties are displayed in ‘Prop-ertyName’, ‘PropertyValue’ pair. The active property is displayed in curly braces {} and alternative property isseparated by or symbol (|). The figure properties can be changed by set command. The syntax of this command isset (h, ‘PropertyName’, ‘PropertyValue’). Given below is code for changing some of the figure properties.

1 h=figure;2 set (h,'Name','myName');3 set (h,'NumberTitle','off');4 set (h,'Menubar','none');5 set (h,'Color',[1,0,0]);6 set (h, 'Position', [500,200,400,300]);

4.3 AxesThe axes command creates an axis in current figure (or in figure whose handle is passed as an argument to axes)and returns its handle. If no figure windows are opened then it opens a figure window and draw axes in it. Theaxes command can take ‘PropertyName’, ‘PropertyValue’ pairs to set axes properties. Lome of these properties arePosition, Color, FontSize, FontWeight, LineWidth, XGrid, YGrid, XLim, YLim, XTick, YTick, XTickLabel, YTickLabeletc. These properties can be seen by using get command or by following, Edit > Axes Properties (Select Axes) >More Properties.

4.4 Setting Axes PropertiesThe procedure to change axes properties is similar to that of figure. Use the get and set command for doing so.Given below is an example code:

1 a=axes;2 set (a, 'Color' , [1,1,0])3 set (a, 'LineWidth' , 3)4 set (a, 'XGrid' , 'on')5 set (a, 'YLim' , [-1, 1])6 set (a, 'XTick' , [0.2,0.6,0.9])7 set (a,'XTickLabel',{0.2,'six',0.9} )8 set (a, 'YTick' , [0.3,0.6,0.9])9 set (a,'YTickLabel',{'y1',0.6,'y_2'} )

4.5 PlotThe function plot creates linear plot and return handle to it. The plot (y) plots the columns of y versus their index. Theplot (x,y) plot vector y versus vector x. Various colors, line types, and may be specified by using plot (x,y,’LineSpec’),where ’LineSpec’ gives line specification in terms of it color, type and marker (see online help on plot for details).The plot also takes variable argument input in the form of ’PropertyName’, ’PropertyValue’ pair to control plotproperties. Given below is one example of plot,

1 x=0:10;2 y=x.^2;3 plot(x,y,'r-*', 'Linewidth', 3, 'MarkerSize', 12)

4.6 Setting Plot PropertiesThe plot properties (line series properties) can be changed interactively by following Edit > Current Object Proper-ties (Select Plot) > more properties. These properties can also be changed by get and set command. This method isuseful when properties are changed programmatically. Given below is simple example code:

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 12: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 9

1 x=0:10;y=x.^2;2 p=plot(x,y);3 set(p , 'Color' , [0,1,0]);4 set(p , 'LineWidth' , 3);5 set(p , 'LineStyle' , '-');6 set(p , 'Marker' , 'o');7 set(p , 'MarkerSize' , 12);

4.7 Overlay PlotSometime we need to put multiple (line) plots on the same axes. MATLAB provides three facilities for doing so.The plot with syntax, plot ( x1,y1,’LS1’, x2,y2,’LS2’), plots y1 vs x1 and y2 vs x2 on the same axes. The ’LS1’and ’LS2’ are line specifications for these plots. Another method is to use hold on | off. In this method, generatesfirst plot by using plot (x1,y1,’LS’, ’PropName’, PropValue), call hold on, and then plot second plot by plot (x2,y2,’LS’, ’PropName’, PropValue). Call hold off at the end. The hold command holds the properties of current plot forthe next plot. The third method is to use line (x, y, ’PropName’, PropValue). Given below is an example code:

1 x1=-5:5; y1=x1.^2;2 x2=-5:5; y2=x2.^3;3 p1=plot(x1,y1,'r-*');4 set(p1,'Linewidth',3);5 hold on;6 p2=plot(x2,y2,'b:o');7 set(p2,'Linewidth',4);8 hold off; grid on;9 set(gca,'Linewidth',2);

4.8 Putting TextThe text command is used for text annotation (putting text on the plot). The text (x,y,’string’) put the text object,‘string’, at position (x,y) and return its handle. The text properties can be specified by using text(x,y,’string’,’PropertyName’,PropertyValue). The properties can be changed by using get, set commands. The properties can also be changed byEdit > Current Object Properties (Select Text Object) > More Properties. The text can also be inserted by usingInsert > Text Box. Use gtext (’string’) to place ‘string, a place selected by mouse. The ginput command is used toget coordinates of a point selected by the mouse. Given below is the example code.

1 x=0:10;y=x.^2;plot(x,y);2 t=text(1,20, 'P(1,20)');3 set(t,'FontSize',14);4 [x1,y1]=ginput(1);5 t1=text(x1,y1,'(x1,y1)')6 gtext('gtext','FontSize',14);

4.9 AxisThe plot command set x and y axis scaling to suitable values (on the bases of input data). The axis command is usedto control axis scaling and appearance. The axis ([xmin xmax ymin ymax]) sets scaling for the x- and y-axes. Thiscan also be changed by editing figure properties, Edit > Current Object Properties > Select Axes. The axis equal,axis square, axis normal, axis tight, axis auto are few flavors of axis (see online help on axis). The axis can also beused for semi-control, e.g. axis (xmin, inf, -inf, ymax). Given below is the example code,

1 x=linspace(0,2*pi,100);2 y=sin(x);3 plot(x,y);4 axis([0,2*pi,-1,1]);

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 13: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 10

4.10 LegendThe legend command put legend on the plot. It can be called as legend (’string’), legend (’string1’,’string2’,. . . ) orlegend (’string1’,’string2’,. . . , ’PropertyName’, PropertyValue). The MATLAB put legend at a place it find mostsuitable. The legend location can be changed by changing its ‘Location’ property. The legend properties can bechanged interactively by following Edit > Current Object Properties (Select Legend) > More properties sequence.The object properties can also be changed through context menu, select and right mouse click. Given below is theexample code:

1 x1=-5:5; y1=x1.^2;2 x2=-5:5; y2=x1.^3;3 p=plot(x1,y1,'r',x2,y2,'g');4 set(p,'Linewidth',4);5 l=legend('data x1-y1', 'data x2-y2');6 set(l,'Location','NorthWest');

4.11 SubplotThe command subplot divides figure widow into multiple parts so that multiple plots can be accommodated into it.The h=subplot (m,n,p) breaks the figure window into an m-by-n matrix of small axes, selects the p-th axes for forthe current plot, and returns the axis handle. Given below is an example code:

1 x1=-5:5; y1=x1.^2;2 x2=-5:5; y2=x2.^3;3 subplot (1,2,1);4 plot (x1,y1,'g','Linewidth',3);5 subplot (1,2,2);6 plot(x2,y2,'r','Linewidth',3);

4.12 FindobjMany times we are interested to change an object’s property but we do not know its handle. The command findobjreturns the object having a specified property. The h=findobj (’P1Name’, P1Value, . . . ) returns the handles of theobjects whose property values matches. The h=findobj (ObjectHandles, ’P1Name’, P1Value,. . . ) restricts the searchto the objects listed in ObjectHandles and their descendents. See online help for more details on findobj.

1 x1=-5:5; y1=x1.^2;2 x2=-5:5; y2=x2.^3;3 plot (x1,y1,'r',x2,y2,'g');4 h1=findobj('Color','r');5 set(h1,'Linewidth',3);6 h2=findobj('Color','g');7 set(h2,'Color','b');

5 Creating Graphics InteractivelyThe reference for this part is Getting Started Guide [2].

5.1 Graphics Objects HierarchyGraphics objects are the basic drawing elements used by MATLAB to display data. Each instance of an object isassociated with a unique identifier called a handle. The graphical objects are arranged hierarchically. The childrenof a figure are User Interface objects, Axes and hidden annotation axes. The plot objects are children of axes.

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 14: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 11

5.2 Plotting ProcessThe plotting process involves creating graphs, exploring data, editing graph components, annotating graphs, printingand exporting graphs, adding and removing graphical contents and finally saving graph for re-use.

5.3 Figure ToolsThe figure tools can be accessed from figure window. Some of these tools are zoom, pan, data cursor, basic fittingand data statistics. The zoom tool is for zooming in or out particular area of the figure. It is possible to zoomhorizontally or vertically, independently. The pan tool is for translation. The data cursor displays the data at themouse location. The basic fitting tool provides facilities for various type of data fitting including linear, quadraticetc. The data statistics tools is for checking statistical properties of data like mean, median, standard deviation etc.

5.4 Plotting ToolsPlotting tools are used to perform multitude of plot related tasks. Some of these tasks are seeing and setting proper-ties of graphics objects, annotate graphs with text, arrows, etc, create and arrange subplots in the figure etc. Thesetools can be grouped into three groups, Figure Palette, Plot Browser and Property Editor. These tools can bedisplayed by selecting these tools from View > menu. These tools can also be started by MATLAB commands,figurepalette, plotbrowser, and propertyeditor.

5.5 Figure Palette: New SubplotsYou can create subplots by making use of Figure Palette. Select desired number of rows and columns. Effectively,it is same as using subplot (m,n, p) interactively.

5.6 Figure Palette: Variables and Plot CatalogThe Figure Palette provides features for interactive plotting. Let x and y, be two vectors of same size available inworkspace. These variables are also visible in Figure Palette. Two plot, x vs y, select these variable and right click(to see context menu). The context menu displays various options that can be directly used by selection. However,if more options are required then click the Plot Catalog option from the context menu. This catalog gives all theavailable options and one of them can be used for plotting.

5.7 Figure Palette: AnnotationsThe Figure Palette can also be used for inserting annotations like line, arrow, text box, text arrow etc.

5.8 Plot BrowserThe Plot Browser plotting tool is used for selecting/deselecting various plot objects. This tool also allow additionof new variable by Add Data option. The Plot Browser is very useful for changing properties of plot objects. Selectobject from Plot Browser, go to Property Editor and change properties of selected object. You may select more thanone object and change their common properties simultaneously.

5.9 Property EditorThe Property Editor can be used to change properties of any graphics object. Select the object, go to the PropertyEditor and change properties. The common properties of the object are displayed on property editor. All propertiescan be viewed and changed by selecting More properties option from Property Editor. The object properties canalso be changed through context menu (select object and right click).

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 15: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 12

5.10 PrintingThe graphics can be printed on a standard printer. To see print preview, File > Print Preview. The print previewgives various options like placement of figure on paper, paper size and orientation, linewidth for lines, font name,font size etc for text, header text, color scale, background color etc. These options can also be saved in StyleSheetfor future use. These properties can also be changed by print and related commands.

5.11 ExportingThe figure can also be exported into various file formats like fig, png, jpg etc. Select File > Export Setup. TheExport Setup gives various options for changing figure properties before export. These properties are related topaper size, fonts, lines etc. Change these properties as required and export figure in desired format. The saveas andprint commands can also be used for exporting figure.

5.12 SavingThe MATLAB provides two options for saving figures for reuse. These options are to save figure as .fig file andgenerate M file. These options can be accessed from File menu. The .fig file stores data, graphics objects and theirproperties. This file can be opened with MATLAB for exact creation of figure. The M file stores graphics objectand their properties in the form of MATLAB function file. To recreate the figure you need to have data along withgenerated function file. The saveas can also be used for saving figure into .fig file.

6 Publishing Report

6.1 IntroductionYou can create formatted reports in HTML, LATEX PDF or MS Word using MATLAB 7’s built in publisher. Thisis the fastest way to communicate your work to others. To publish a report, you need to create a script, enable cellmode from cell menu, divide script into ‘code cells’, insert text markup for formatting, edit publish configuration(if required) and finally publish the report. These actions can be carried out interactively or programmatically. Seeonline help on publish for details.

6.2 Code CellsA ‘code cell’ is a set of related commands that form one unit of computations. The beginning of a cell is markedby double percentage character (%%). A cell continues until beginning of another cell is encountered. Observe thechange in color and cell separation line in editor. You can evaluate cells individually (Ctrl+Enter). Given below isexample code displaying two cells:

1 %% Create vectors2 theta=linspace(0,10*pi,200);3 r=exp(-theta/10);4 %% Plot using polar plot5 polar(theta,r);

6.3 Document Title and IntroductionThe report title is specified in first code cell (starting from first line) of script. The text after %% in first cellis displayed as document title. The comment line (%) immediately following title line is displayed as documentintroductory text. To separate introductory text from rest of the document, you must put a line with double percent-age (%%) after the introductory text. The document contents are automatically generated and displayed after theintroductory text. Given below is an example code:

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 16: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 13

1 %% This is the Title2 % Introductory text3 % Introductory text4 %%

6.4 Section and Section TitlesThe document sections and cells are related to each other. You can create new cell that starts a new section byputting %% followed by section title (in the same line) . You can also create new cell in existing section by putting%% followed by nothing (blank). You can create new section in existing cell by putting %%% followed by sectiontitle in same line. These three methods are shown in example code given below:

1 %% New Section with New Cell2 % double percentage followed by section title3 %%4 % To create New Cell in Existing Section:5 % double percentage followed by nothing6 %%% New Section in Existing Cell7 % triple percentage followed by section title

6.5 Other Text MarkupThe text markup (formatted text) can be inserted in comment lines. You can create bold text by *bold text *, italictext by _ italic text_ and monospace text by |monospace text|. The bulleted list can be created by putting * in frontof items. The numbered lists can be produced by putting # in front of items. The hyperlinked text can be created by< www.psiphi.in>. These can be inserted by Cell > Insert Markup. Given below is the example code:

1 %% Other Text Markup2 % *bold text* , _italic text_ , | monospace text |3 %4 % * Item 15 % * Item 26 %7 % # Item 18 % # Item 29 %

10 % <www.psiphi.in>

6.6 More Text Markup. . .You can insert image into report by <<IMAGE.JPG>> (the IMAGE.JPG shall be present in folder where report isgenerated, see section 6.7). The TEX equations can be inserted like $$ eπi + 1 = 0 $$. You can also insert LATEXand HTML stuff into your report.

6.7 ConfigurationThe configuration toolbar (adjacent to publish tool bar) can be used to change configuration of the published report.You can change output setting in the form of output file format (HTML, PDF, DOC, PPT) and output file folder.The figure setting can changed in the form of image size and format. The code setting allow inclusion/non-inclusionof code and maximum number of code lines you want to include. These configuration setting can also be controlledby publish command.

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 17: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 14

6.8 Displaying ResultsThe published report contains title, introductory text, list of contents, section title and section introduction, MAT-LAB code, generated figures and output. The output displayed on command window is also displayed in report.You can use disp command to display results in report. The sprintf is very useful in displaying formatted output inreport. Given below is example code:

1 %% Displaying Output2 phi=1.618;3 PHI=(1+sqrt(5))/2;4 s=sprintf('phi=%5.3f, PHI=%10.8f',phi,PHI);5 disp(s);6 disp(PHI);7 phi

6.9 Example File for Publishing Report

1 %% Document Title2 % Introductory text3 %% Section4 % Section introduction5 %% Other Text Markup6 % *bold text* , _italic text_ , |monospace text|7 % <www.psiphi.in>8 %% More Text Markup9 % The TeX equations can be inserted like:

10 % $$\phi=\frac{1+\sqrt{5}}{2}$$11 %% Displaying Output12 phi=1.618; PHI=(1+sqrt(5))/2;13 s=sprintf('phi=%5.3f, PHI=%10.8f',phi,PHI);14 disp(s); disp(PHI); phi15 %% Plot16 theta=linspace(0,10*pi,200);17 r=exp(-theta/10); polar(theta,r);

7 Building GUI

7.1 IntroductionThe Graphical User Interface (GUI) is the graphical display for performing tasks interactively. In general, a mouseclick on GUI element trigger an event and GUI program calls a function (called callback function) to complete thetask assigned to GUI element. The MATLAB provides two ways for creating GUI. The Graphical User Interfacedevelopment Environment (GUIDE) is a user friendly interface to create GUI interactively. Another way to createGUI is doing so programmatically.

7.2 GUIDEThe GUIDE can be opened by guide command or GUIDE toolbar on MATLAB Desktop. You can open existingGUI or create new GUI. You can open blank (default) or one of the available template. The GUIDE interfacecontains menu bar on the top. Help menu show MATLAB help for GUIDE. The toolbar is shown just below menubar. The Layout editor is shown on the left side of interface. Use File > Preference > GUIDE > Show Names inComponent palette > OK to show name of components on editor. The GUIDE Layout Editor help you in creatingcomponents like axes, push button, static text, pop-up menu etc. The GUI is created in grid portion of interface. TheGUI size can be changed by dragging lower-right corner of the editor.

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 18: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 15

7.3 Creating Simple GUIThe MATLAB simple_ gui is a demo program for building GUI. Type simple_ gui in command window. It willopen a GUI containing axes, pushbutton, static text and pop-up menu. Try various options to learn about this menu.You can edit simple_ gui.m to see the GUI code. We will create the same GUI by making use of GUIDE. Add GUIcomponents (axes, three push buttons, static text and pop-up menu) by draging them to editing space. You can alignpushbuttons by following Align Pushbuttons > Tools > Align Objects .

7.4 Creating Simple GUI. . .The properties of GUI components can be viewed and changed through property inspector. Open property inspectorby View > Property Inspector. Now select particular component (the property inspector will show the properties ofselected component) and view its properties. Change string of pushbutton (Select Push Button > String > Changeit), pop-up menu (Select Popup Menu > String > Components in different lines) and static text (Select Static Text> String > Change it). Now save your GUI with name SimpleGUI. This step creates a .fig (that contains a completedescription of the GUI layout) and an .m file (that contains the code that controls the GUI, including the callbacksfor its components). These files are created in same directory.

7.5 Programming Simple GUIThe most important part of GUI development is programming it. The GUI components have callback functionsthat are called particular event is triggered. The GUI can be programmed directly by modifying .m file. You canview the callback functions of various components from context menu (select+right click). See MATLAB help andsimple_ gui.m for details of how GUI is programmed. Two important functions that need to be programmed areOpeningFunction and CallbackFunction (for GUI components). Given below is excerpt from simple_ gui.m.

opening function (FileName_OpeningFcn),

% Create the data to plot.handles.peaks=peaks(35);handles.membrane=membrane;[x,y] = meshgrid(-8:.5:8);r = sqrt(x.^2+y.^2) + eps;sinc = sin(r)./r;handles.sinc = sinc;% Set the current data value.handles.current_data = handles.peaks;surf(handles.current_data)

Select popup menu in GUIDE Layout Editor, right click, view callbacks, callback.

% Determine the selected data set.str = get(hObject, ’String’);val = get(hObject,’Value’);% Set current data to the selected data set.switch str{val};case ’Peaks’ % User selects peaks.

handles.current_data = handles.peaks;case ’Membrane’ % User selects membrane.

handles.current_data = handles.membrane;case ’Sinc’ % User selects sinc.

handles.current_data = handles.sinc;end% Save the handles structure.guidata(hObject,handles)

Pushbutton surf callback:

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 19: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 16

% Display surf plot of the currently selected data.surf(handles.current_data);

Pushbutton mesh callback:

% Display mesh plot of the currently selected data.mesh(handles.current_data);

Pushbutton contour callback:

% Display contour plot of the currently selected data.contour(handles.current_data);

8 SimulinkThe reference for this section is Getting Started Guide for Simulink [3] and MATLAB online help.

8.1 IntroductionSimulink is used for modeling, simulation and analysis of dynamic systems. It is tightly integrated with the MAT-LAB environment. Simulink provides a GUI for building models as block diagrams. It also includes a comprehen-sive block library of sinks, sources, linear and nonlinear components, and connectors. You can also create your ownblocks. After the model is defined, it can be simulated by using a choice of mathematical integration methods, eitherfrom the Simulink menus or by entering commands in the MATLAB Command Window. Simulation results canbe seen by using scopes and can be put in the MATLAB workspace for post processing and visualization. Modelanalysis tools include linearization and trimming tools, which can be accessed from the MATLAB command line,plus the many tools in MATLAB and its application toolboxes.

8.2 User InterfaceThe Simulink can be started by simulink command or by clicking Simulink icon in MATLAB toolbar. The userinterface consists of Simulink Library Browser and Simulink Model Window. The Simulink Library Browser haveCommonly Used Blocks (Scope), Continuous (Derivative, Integrator, Transfer Function), Discontinuities, Discrete,Logic and Bit Operation, Lookup Tables (sin, cos), Math Operations (Gain, Sum, Product), Sources (Sine wave,step), Sinks (Scope, To Workspace), Signal Routing (Mux) etc. The Simulink Model Window contains blockdiagram, set configuration parameters, start-stop, save, print etc.

8.3 Example 1: Sine Wave and its Integration

Displays: (1) sin (2)∫ tt0

sin τ dτ . Blocks: (1) Sine Wave (2) Integrator (3) Mux (4) Scope. Steps: (1) Start simulink(2) File → New → Model , save with some name (3) Library → Source → Sine Wave , drag to Model Window,Similarly, Sink→ Scope, Continuous→ Integrator, Signal Routing→Mux (4) Connect blocks: input port, outputport, Select first block → hold Ctrl key → Select 2nd block (branch). The block diagram is given in figure 1.Simulation: Simulation→ Configuration→ Parameters , change stop time to 20. Simulation→ Start. See scope(Zoom, Parameter Data History for exporting data). Modifying block properties, adding comments.

8.4 Example: Spring Mass System (Direct Approach)This example demonstrates step response of a second order spring-mass-damper system. The model is given byequation given below:

mx+ cx+ kx = f(t)

x =1m

(f(t)− cx− kx)

Where x is displacement, t is time,m is mass, c is damping coefficient, k is spring constant and f is forcing function.

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 20: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 17

Figure 1: Sine wave and its Integration

1. Create new model and drag: Sources→ Step, Math Operation→ Gain, Math Operation→ Sum, Continuous→ Integrator, Sinks→ Scope, Sinks→ To Workspace.

2. Connect these blocks as in figure 2. Use Ctrl+F for flip and Ctrl+R to rotate.

3. Enter the values of the parameters for each block eg. set m = 2.0, c = 0.7, k = 1.

4. Double click the simout block and set variables for workspace

5. Run the simulation

6. MATLAB command widow, who, plot

7. Repeat (3)-(5) for underdamped, overdamped and critically damped systems

Figure 2: Spring Mass System (Direct Approach)

8.5 Example: Spring Mass System (Transfer Function)1. Create new model and drag: Sources → Step, Continuous → Transfer Function, Sinks → Scope, Sinks →

Save Output To File.

2. Connect these blocks as in figure 3.

3. Double click the transfer function block and enter numerator, denominator (eg. setm = 2.0, c = 0.7, k = 1).

4. Double click the save output to file block and set filepath and filename (MAT file)

5. Run the simulation

6. MATLAB command widow, load mat file, who, plot

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 21: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 18

Figure 3: Spring Mass System (Transfer Function)

8.6 Example: Capacitor ChargingThis example demonstrates capacitor charging. The model is equation equation given below:

V = − 1RC

V +1RC

u

Where V is voltage, t is time, R is resistance, C is capacitance, and u is unit step function. The Laplace transformof above equation is given by:

V (s) =1s

(1RC

U(s)− 1RC

V (s))

1. Create new model and drag: Sources → Step, Math Operation → Gain, Math Operation → Gain, MathOperation→ Sum, Continuous→ Integrator, Sinks→ Scope

2. Connect these blocks as in figure 4. Use Ctrl+F for flip and Ctrl+R to rotate.

3. Edit the step block and enter final value as 10

4. Edit the Gain1 block and set gain as 1/R ∗ C (we will enter these from workspace)

5. Edit the summing block and change it sign from + to -

6. Change configuration parameters (1) Type: fixed (2) Fixed Step Size: 0.01 (3) Solver: ode3 (Bogacki-Shampine)

7. MATLAB command widow, R=1, C=1; Run the simulation

8. View results in scope.

9. Use sim command to execute and plot for different values of C

Figure 4: Capacitor Charging

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 22: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 19

9 Homework1. What does the name MATLAB stand for?

2. Every programming language has its own set of advantages and disadvantages. List some of the advantagesand disadvantages of using Matlab.

3. Name three ways that it’s possible to get help from within Matlab.

4. Rudra Pratap: Arithmetic Operations: Compute the following quantities:

(a) 25

25−1 and compare with (1− 125 )−1.

(b) 3√

5−1(√

5+1)2− 1.

(c) Area=πr2 with r = π1/3 − 1. (π is pi in MATLAB).

5. Rudra Pratap: Exponential and Logarithms: The mathematical quantities ex, ln(x) and log x are calcu-lated with exp(x), log(x), and log10(x) respectively. Calculate the following quantities:

(a) e3, ln(e3), log10(e3), and log10(105).

(b) eπ√

163.

(c) Solve 3x = 17 for x and check the result. (The solution is x = ln 17ln3 . You can verify the result by direct

substitution.)

6. Rudra Pratap: Trigonometry: The basic MATLAB trig functions are sin, cos, tan, cot, sec, and csc. Theinverses, e.g. arcsin, arctan, etc., are calculated with asin, atan, etc. The same is true for hyperbolic functions.The inverse function atan2 takes two arguments, y and x, and gives the four-quadrant inverse tangent. Theargument of these functions must be in radians. Calculate the following quantities:

(a) sin π6 , cosπ, and tan π

2

(b) sin2 π6 + cos2 π

6

(c) y = cosh2x− sinh2x, with x = 32π.

7. Rudra Pratap: Equation of a straight line: The equation of a straight line is y = mx + c, where m andc are constants. Compute the y-coordinates of a line with slope m = 0.5 and the intercept c = −2 at thefollowing x-coordinates: x = 0, 1.5, 3, 4, 5, 7, 9, and 10.

8. Rudra Pratap: Multiply, divide, and exponentiate vectors: Create a vector t with 10 elements: 1, 2, 3, . . . ,10. Now compute the following quantities:

(a) x = t sin(t)

(b) y = t−1t+1

(c) z = sin(t2)t2

9. Rudra Pratap: Points on a circle: All points with coordinates x = r cos θ and y = r sin θ, where r is aconstant, lies on a circle with radius r, i.e. they satisfy the equation x2 + y2 = r2. Create a column vector forθ with the values 0, π/4, π/2, 3π/4, π, and 5π/4. Take r = 2 and compute the column vectors x and y. Nowcheck that x and y indeed satisfies the equation of a circle, by computing the radius r =

√(x2 + y2).

10. Rudra Pratap: A simple line plot: Plot y = sinx, 0 ≤ x ≤ 2π, taking 100 linearly spaced points in thegiven interval. Label the axes and put “Plot created by yourname” in the title.

11. Rudra Pratap: Line-styles: Make the same plot as above, but rather than displaying the graph as a curve,show the unconnected data points. To display the data points with small circles, use plot(x,y,’o’). Nowcombine the two plots with the command plot(x,y,x,y,’o’) to show the line through the data points as well asthe distinct data points.

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 23: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 20

12. Rudra Pratap: An exponentially decaying sine plot: Plot y = e−0.4x sinx, 0 ≤ x ≤ 4π, taking 10,50, and 100 points in the interval. [Be careful about computing y. You need array multiplication betweenexp(−0.4 ∗ x) and sin(x)].

13. Rudra Pratap: On-line help: Type help plot on the MATLAB prompt and hit return. Read through theon-line help on plot.

14. Rudra Pratap: Overlay Plots: Plot y = cosx and z = 1− x2

2 + x4

24 for 0 ≤ x ≤ π on the same plot. [Hint:you can use plot(x,y,x,z,’–’) or you can plot the first curve, use the hold on command, and then plot secondcurve on top of the first one.]

15. Rudra Pratap: Show center of the circle: Given below is content of script file circle.m

1 \% CIRCLE- A script file to draw a unit circle2 \% File written by Rudra Pratap. Last modified 6/28/983 \% ---------------------------4 theta=linspace(0,2*pi,100); \%create vector theta5 x=cos(theta); \%generate x-coordinates6 y=sin(theta); \%generate y-coordinates7 plot(x,y); \%plot the circle8 axis('equal'); \%set equal scale on axes9 title('Circle of unit radius'); \%put a title

Modify the script file circle.m to show the center of the circle on the plot, too. Show the center point with a“+”.

16. Rudra Pratap: Change the radius of the circle: Modify the script file circle.m to draw a circle of arbitraryradius as follows:

(a) Include the following command in the script file before the first executable line (theta=. . . ) to ask theuser input (r) on the screen: r=input(’Enter the radius of the circle: ’)

(b) Modify the x- and y- coordinate calculations accordingly.

(c) Save and execute the file. When asked, enter the value of radius and press return.

17. Rudra Pratap: Variables in the workspace: All the variables created by a script file are left in the globalworkspace. You can get information about them and access them, too:

(a) Type who to see the variable present in the workspace. You should see the variables r, theta, x and y inthe list.

(b) Type whos to get more information about the variables and workspace.

(c) Type [theta’ x’ y’] to see the values of θ, x and y listed as three columns. See the use of transposeoperator (’).

18. Rudra Pratap: H1 Line: The first commented line before any executable statement in a script file is calledH1 line. It is this line that is searched by the lookfor command. Since the lookfor command is used to lookfor M-files with keywords in their description, you should put keywords in H1 line of all M files you create.Type lookfor unit to see what MATLAB comes up with. Does it list the script file you just created?

19. Rudra Pratap: Convert Temperature: Write a function that outputs a conversion table for Celsius andFahrenheit temperatures. The input of the function should be two temperatures: Ti and Tf , specifying thelower and upper range of the table in Celsius. The output should be a two column matrix: the first columnshowing the temperature in Celsius from Ti to Tf in the increments of 1◦C and the second column showingcorresponding temperature in Fahrenheit. To do this (i) create the column vector C from Ti to Tf with thecommand C=[Ti:Tf]’, (ii) calculate the corresponding numbers in Fahrenheit using the formula F = 9

5C+32,and (iii) make the final matrix with the command temp=C F];. Note that you output variable will be namedtemp.

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 24: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 21

20. Rudra Pratap: Calculate Factorials: Write a function factorial to compute the factorial n! for any integern. The input should be number n and the output should be n!. You might have to use for loop or a while loopto do the calculation.

21. Rudra Pratap: What is the MATLAB path? The MATLAB path is a variable, stored under the namepath (the variable that contains the list of all directories that are automatically included in MATLAB’s searchpath). It is generated by a file named pathdef.m (normally located in the toolbox/local directory). By default,all directories that are installed by the MATLAB installer are included in this path.

If you prefer to organize your MATLAB files in different directories and would like to have access to all yourfiles automatically each time you work in MATLAB, you need to modify the MATLAB search path with pathor addpath command and include your directories in the search path.

(a) Create two directories: (i) a directory called tutorial inside the work directory, and (ii) a directory calledmywork on the C: drive.

(b) Use command addpath to add these directories to the existing path. Query with path to see that thedirectories are added.

(c) Use command savepath to save the new path permanently. This command will modify the pathdef.mfile.

22. Rudra Pratap: Entering Matrices: Enter the following three matrices:

A =[

2 63 9

], B =

[1 23 4

], C =

[−5 55 3

]23. Rudra Pratap: Check Some Linear Algebra Rules:

(a) Is matrix addition commutative? Compute A+B and then B+A. Are the results same?

(b) Is matrix addition associative? Compute (A+B)+C and then A+(B+C) in the order prescribed. Are theresults same?

(c) Is multiplication with a scalar distributive? Compute α(A+B) and αA+ αB, taking α = 5 and showthat the results are same.

(d) Is multiplication with a matrix distributive? Compute A*(B+C) and compare with A*B+A*C.

(e) Matrices are different from scalars! For scalars ab = ac implies b = c if a 6= 0. Is that true for matrices?Check y computing A*B and A*C for the matrices given above.In general, matrix product do not commute either. Check if A*B and B*A gives different results.

24. Rudra Pratap: Create matrices with zeros, eye and ones: Create the following matrices with the help ofthe matrix generation functions zeros, eye, and ones. See the help on these functions if required (e.g., helpeye).

D =[

0 0 00 0 0

], E =

5 0 00 5 00 0 5

, F =[

3 33 3

]

25. Rudra Pratap: Create a big matrix with submatrices: Create th following matrix G by putting matrix A,B and C, given above, on its diagonal.

G =

2 6 0 0 0 03 9 0 0 0 00 0 1 2 0 00 0 3 4 0 00 0 0 0 −5 50 0 0 0 5 3

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 25: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 22

26. Rudra Pratap: Manipulate a matrix: Do the following operations on matrix G created above:

(a) Delete last row and last column of the matrix.

(b) Extract the first 4× 4 submatrix from G.

(c) Replace G(5,5) with 4.

(d) What do you get if you type G(13) and hit return? Can you explain how MATLAB got the answer?

(e) What happens if you type G(12,1)=1 and hit return?

27. Let v = [356142]. What is the outcome of following commands,

(a) 3 > 3

(b) 5 > 3

(c) v(logical([0 1 1 0 1 0]))

(d) v > 3

(e) v(v>3)

(f) v(v>3 & v<6)

(g) find(v > 3)

(h) sort(v)

28. Which logical operator has higher precedence: AND (&) or OR (|)?

29. Contrast the ‘while’ loop and the ‘for’ loop. For example, in what situations would you use one instead of theother?

30. What does the ‘break’ command do inside a loop? What does the ‘continue’ command do?

31. Name 3 benefits of writing functions when programming?

32. MATLAB’s functions use a pass-by-value scheme. Explain what this means?

33. What is the difference between global variables and persistent variables?

34. Identify 4 errors in the following program and mark corrections:

1 v = (4 5 6 7 8 9);2 avg = sum(v) / length;3 printf( 'The average is \%g' );

35. Given the vector, x = [ 4 5 6 ]; What values result from each of the following commands?

1 x(1)2 length(x)3 x(length(x))4 x'5 prod(x)6 x( [1 3] )7 [ x\; x]8 [ x \; x]

36. Write MATLAB commands that would create matrices according to the following specifications:

(a) A 4x4 matrix of random numbers, each between (-1.0) and (+1.0). Hint: create a matrix with randomnumbers between 0.0 and 2.0 and go from there.

(b) A 5x5 matrix with the center row and the center column having 1’s and all other spots having 0’s.

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 26: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 23

37. Given a matrix ‘m’, write a MATLAB command that would give the sum of all numbers in ‘m’. Rememberthe difference between summing a vector and summing a matrix!

38. Write MATLAB commands that would use ‘subplot’ (subplot(rows,cols,current)) to create a figure with twoplots on it - a plot of sine and a plot of cosine, each from 0 to 2π in steps of 0.1.

39. Write a program that reads a number of minutes from the keyboard, then displays the equivalent number ofhours and minutes. For example, if ‘90’ minutes were entered, the program would print, 90min = 1h 30m.Hint: for the hours, find out how many whole sets of 60 are in the original number of minutes. For theconverted minutes, find out how many minutes are left over once you take out all the sets of 60.

40. Write a program that calculates the factorial of a given number. Read in a number from the keyboard, thendisplay the product of all values from 1 up to that number. For example, if you type in ‘5’ the program wouldprint: 5! = 120

41. Identify 5 errors in the following program and mark corrections. Look for both syntax errors and logicalerrors. The intent of the function is to examine the parameter and return the value 1 if it’s positive, -1 ifnegative, or 0 if it’s zero.

1 function result mysign[ num ]2 if (num $>$ 0)3 result = 1;4 end5 if (num $<$ 0)6 result = -1;7 else8 num = 0;9 end if

42. For what range of numbers for ‘x’ is each of the following conditions true? You can describe the ranges ingeneral terms (e.g. “numbers 1-10”) or in set notation (e.g. “[1,10]”).

(a) (x >= 1) & (x <= 10)(b) (x >= 1) | (x <= 10)(c) (x < 1) & (x > 10)(d) (x < 1) | (x > 10)(e) ((x < 1) | (x > 10))

43. Convert this ‘switch’ command to an equivalent set of ‘if/elseif/else’ statements.

1 switch (n)2 case 103 fprintf( 'Decimal!' );4 case 165 fprintf( 'Hexadecimal!' );6 otherwise7 fprintf( 'Invalid' );8 end

44. Between a ‘for’ loop and a ‘while’ loop, which one should be used when you don’t know ahead of time howmany times the loop should be repeated?

45. What numbers will the following program print out?

1 for (i = [1:3])2 for (j = [4:5])3 fprintf( '\%g, \%g', i, j );4 end5 end

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.

Page 27: MATLAB Introductory Course: Notes

December 31, 2011 Notes on Getting Started with MATLAB 24

46. What will the following program print out?

1 for (n = [1:10])2 if (mod(n,2) == 0)3 continue;4 end5 if (n == 7)6 break;7 end8 fprintf( '\%g', n );9 end

47. Write a function called ‘isodd’ that takes a number as a parameter and returns the value ‘1’ if it’s an oddnumber or ‘0’ if it’s even. For example, typing ‘isodd(3)’ should return ‘1’, but ‘isodd(4)’ should return ‘0’.Recall that a number is even if the remainder of the number divided by 2 is zero.

48. Write a function called ‘firstfactor’ that takes a parameter ‘num’ and returns the first factor of the numberhigher than ‘1’. Hint: check the remainder of the number divided by all values between 2 and the numberitself. The first value without a remainder will be the first factor of the number.

49. Write a function called ‘gcfactor(a,b)’. It should return the number that is the greatest common factor for thenumbers ‘a’ and ‘b’ - in other words, the largest number that will divide evenly into both. Hint: loop from i= N down to 1, where ‘N’ is the smaller of the two numbers. When ‘a/i’ has a zero remainder and ‘b/i’ has azero remainder, return the value ‘i’ as the answer.

50. Write a MATLAB program that calculates and prints out the first 20 numbers in the Fibonacci sequence. Thefirst two numbers in the sequence are ‘0’ and ‘1’. Each number after that is the sum of the previous twonumbers. So the first 6 numbers in the sequence are: 0, 1, 1, 2, 3, and 5.

51. Projectile Motion Let a projectile is thrown with velocity v at an angle θ from horizontal. Let x(t) and y(t) bethe horizontal and vertical position at time t. These are given by, x(t) = vt cos θ and y(t) = vt sin θ − 1

2gt2,

where g = 10ms−2 is acceleration due to gravity. The time of flight, T , is given by T = 2v sin θg . Plot x vs y

for different combinations of v and θ.

52. Railway Time Write a program that behaves as follows:

Reads in a railway time value from the user (e.g. 1530).

Calculates the separate hours and minutes values of that time (e.g. 15 and 30).

Prints the hours in 12-hour format (1-12). Use an if/elseif/else statement block to decide how to displaythem.

Prints a colon (:).

Prints the minutes.

Prints ‘am’ or ‘pm’ as appropriate.

References[1] MathWorks. Creating Graphical User Interfaces, MATLAB 7. MathWorks, xxxx.

[2] MathWorks. Getting Started Guide, MATLAB 7. MathWorks, xxxx.

[3] MathWorks. Getting Started Guide, Simulink 7. MathWorks, xxxx.

[4] MathWorks. Learning MATLAB 7, MATLAB & Simulink Student Version. MathWorks, xxxx.

[5] Rudra Pratap. Getting Started with MATLAB 7: A Quick Introduction for Scientists and Engineers. Oxford,2006.

All rights reserved with PsiPhiETC ®. These notes are created for educational purpose and may be used,distributed and/ or modified. Visit www.psiphi.in for updated notes and course schedule.