Vous êtes sur la page 1sur 27

Course Notes

Getting Started with MATLAB


PsiPhiETC January 1, 2012

December 31, 2011

Notes on Getting Started with MATLAB

Contents
1 Motivation 1.1 Why this course? . . . . . . . . . . . . . . 1.2 What is MATLAB? . . . . . . . . . . . . . 1.3 Features of MATLAB! . . . . . . . . . . . 1.4 Course Contents . . . . . . . . . . . . . . . 1.5 Installation . . . . . . . . . . . . . . . . . 1.6 Desktop Tools & Development Environment 1.7 Ways to Get Help . . . . . . . . . . . . . . 1.8 Some General Commands . . . . . . . . . 1.9 Vectors and Scalars . . . . . . . . . . . . . 1.10 Simple Plots . . . . . . . . . . . . . . . . . 1.11 MATLAB Editor . . . . . . . . . . . . . . 1.12 Matlab Script . . . . . . . . . . . . . . . . 1.13 MATLAB Functions . . . . . . . . . . . . Interactive Computations 2.1 Matrix Creation . . . . . . . 2.2 Matrix Indexing . . . . . . . 2.3 Matrix Manipulation . . . . 2.4 Matrix Operations . . . . . . 2.5 Elementary Maths Functions 2.6 Character Strings . . . . . . 2.7 Saving and Loading Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1 1 1 1 1 1 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 4 4 5 5 5 6 6 7 7 7 7 7 8 8 8 8 8 9 9 9 10 10 10

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

Programming in MATLAB 3.1 Script Files . . . . . . . . . . . . . . . . . 3.2 Function Files . . . . . . . . . . . . . . . . 3.3 Control Flow: if-elseif-else . . . . . . . . . 3.4 Control Flow: for loops . . . . . . . . . . . 3.5 Control Flow: while loops . . . . . . . . . 3.6 Control Flow: switch-case-otherwise . . . . 3.7 break, continue, return . . . . . . . . . . . 3.8 Interactive Input: input, keyboard and pause 3.9 Input/Output . . . . . . . . . . . . . . . . . Creating Graphics Programmatically 4.1 Figure . . . . . . . . . . . . . . . 4.2 Setting Figure Properties . . . . . 4.3 Axes . . . . . . . . . . . . . . . . 4.4 Setting Axes Properties . . . . . . 4.5 Plot . . . . . . . . . . . . . . . . 4.6 Setting Plot Properties . . . . . . 4.7 Overlay Plot . . . . . . . . . . . . 4.8 Putting Text . . . . . . . . . . . . 4.9 Axis . . . . . . . . . . . . . . . . 4.10 Legend . . . . . . . . . . . . . . 4.11 Subplot . . . . . . . . . . . . . . 4.12 Findobj . . . . . . . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

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

December 31, 2011

Notes on Getting Started with MATLAB

Creating Graphics Interactively 5.1 Graphics Objects Hierarchy . . . . . . . . 5.2 Plotting Process . . . . . . . . . . . . . . 5.3 Figure Tools . . . . . . . . . . . . . . . . 5.4 Plotting Tools . . . . . . . . . . . . . . . 5.5 Figure Palette: New Subplots . . . . . . . 5.6 Figure Palette: Variables and Plot Catalog 5.7 Figure Palette: Annotations . . . . . . . . 5.8 Plot Browser . . . . . . . . . . . . . . . 5.9 Property Editor . . . . . . . . . . . . . . 5.10 Printing . . . . . . . . . . . . . . . . . . 5.11 Exporting . . . . . . . . . . . . . . . . . 5.12 Saving . . . . . . . . . . . . . . . . . . . Publishing Report 6.1 Introduction . . . . . . . . . . . . . 6.2 Code Cells . . . . . . . . . . . . . . 6.3 Document Title and Introduction . . 6.4 Section and Section Titles . . . . . . 6.5 Other Text Markup . . . . . . . . . 6.6 More Text Markup. . . . . . . . . . . 6.7 Conguration . . . . . . . . . . . . 6.8 Displaying Results . . . . . . . . . 6.9 Example File for Publishing Report Building GUI 7.1 Introduction . . . . . . . . 7.2 GUIDE . . . . . . . . . . 7.3 Creating Simple GUI . . . 7.4 Creating Simple GUI. . . . 7.5 Programming Simple GUI

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

10 10 11 11 11 11 11 11 11 11 12 12 12 12 12 12 12 13 13 13 13 14 14 14 14 14 15 15 15 16 16 16 16 16 17 18 19

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

Simulink 8.1 Introduction . . . . . . . . . . . . . . . . . . . . . 8.2 User Interface . . . . . . . . . . . . . . . . . . . . 8.3 Example 1: Sine Wave and its Integration . . . . . 8.4 Example: Spring Mass System (Direct Approach) . 8.5 Example: Spring Mass System (Transfer Function) 8.6 Example: Capacitor Charging . . . . . . . . . . . Homework

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

List of Figures
1 2 3 4 Sine wave and its Integration . . . . . . Spring Mass System (Direct Approach) Spring Mass System (Transfer Function) Capacitor Charging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 17 18 18

List of Tables

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

1
1.1

Motivation
Why this course?

This, Getting Started With MATLAB, is an introductory course designed for newcomer to the MATLAB. The newcomer may be interested in MATLAB for (i) completing his current assignment (ii) curiosity (iii) desire for value addition. The course objective is to initiate participant into MATLAB and then develop a belief for selflearning.

1.2

What is MATLAB?

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

1.3

Features of MATLAB!

The MATLAB provides multiple features to the user. Some of these features are (i) extensive library of in-built mathematical 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) specialized toolboxes like Simulink.

1.4

Course Contents

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

1.5

Installation

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

1.6

Desktop Tools & Development Environment

The reference for this topic is Chapter 7 of Getting Started Guide [2]. The default desktop layout contains Menu Bar on top, Tool Bar just below menu bar, a folder browser and launchpad on bottom left with name Start. The desktop contains 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 desktop layout may be changed by File > Preference. The current folder panel is used for managing les. It show contents of present working directory (pwd) and you can create new les or folders. The search feature allow you to search les. It provide advance features in the form of reports for code analyzer report, dependency report etc. Also, you can see different attributes (e.g. le size) of les and sort le according to different options. The command window is main window of MATLAB Desktop. It is used for entering variable, running script and functions and for interactive computations. The pwd command return present working directory. The ls command lists directory contents on Unix and dir command lists directory contents in Windows. In command window, try magic(3), x=2, y=x*x etc.

December 31, 2011

Notes on Getting Started with MATLAB

The commands that we type in command window are stored in command history. The commands may be executed 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 dened in the MATLAB session. The command who displays the variable names and whos displays the attributes of these variables. The MATLAB Editor is used for creating new les or opening existing les.

1.7

Ways to Get Help

The MATLAB provides excellent and extensive documentation in the form of help. There are multiple ways to get help. The Help Browser in MATLAB Desktop can be used for browsing and searching almost all topics. You may look at demos for quick overview. In our view, beginners to MATLAB are very likely to get lost in extensive help topics. 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 description of 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-in Function and On-line Help in Rudra Pratap [5] is strongly recommended.

1.8

Some General Commands

The clc is for clearing command window. The clear is for clearing workspace variable. The clear var1 var2 var3 clears var1, var2 and var3. The clear all clears all the workspace variables. The cd is used for changing directory and mkdir for making new directory. When we call a function from command window the MATLAB search for this function in pwd and others directories on MATLABPATH. The path returns the directories MATLABPATH. You may add new directory by using addpath DirectoryPath. The copyle source destination copies a le from source to destination. The delete shall be used carefully as it delete le permanently. The diary is used for recording MATLAB session and quit for quitting MATLAB. To recall a command from history just enter one (or more) character and press up arrow key (smart recall). See help on various command for details.

1.9

Vectors and Scalars

The 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 transpose operator, 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, : is used for dening a vector whose rst element (a), last element (b) and increment () between successive elements is known e.g. v = a : : b. The can be positive (b > a) or negative (b < a) and if it is not specied then it takes default value of 1. The linspace (a,b,n) is used for dening a vector of n linearly spaced elements with a as rst element and b as last element. The vector operators are + for addition, - for subtraction, cross for cross product, dot for 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 changing format of number displayed in command window.

1.10

Simple Plots

MATLAB 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 vector of length n. The plot(x,y) plots the points (xi , yi ), where xi & yi are the ith element of x & y, and connect these points by straight line. The title(TitleString) insert title, xlabel(XLabelString) insert label on x-axis and ylabel(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 modied. Visit www.psiphi.in for updated notes and course schedule.

December 31, 2011

Notes on Getting Started with MATLAB

1.11

MATLAB Editor

The Editor is used for creating new les and/or opening existing les. Use File > New , File > Open or edit FileName. This will open le 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 bottom left and status bar at bottom right.

1.12

Matlab Script

The MATLAB scripts are dened in .m le. A script le contains comments and valid MATLAB commands and expressions. The comment starts with a percentage character, %, and it can appear anywhere in a line. The contents of a line immediately after % is comment. The Editor display comments in green color. The MATLAB keywords are displayed in blue color. The script can be executed by Green Arrow toolbar. The rst comment line is called H1 line. This line shall describe what script do. The lookfor command returns the H1 line. The script le also contain help giving usage details etc. The comment lines following H1 line constitutes help and these lines are returned by help command. The help starts from H1 line and end at rst blank line following H1.

1.13

MATLAB Functions

The MATLAB functions are dened in .m le with le name same as function name. The rst line declare the function and starts with keyword function. The syntax of this line is, function [argout]=FunctionName(argin), where argin is the input argument and argout is output argument. The input argument(s) are passed by value. The variables dened within he function are local to it. It shall be kept in mind that FunctionName shall not conict with name of in-built functions. The exist function of MATLAB is used to nd whether FunctionName already exist or not. The rst comment line following function decleration is called H1 line. This line shall describe what this function do. The lookfor command returns the H1 line. The function le also contain help giving details of syntax, usage, example and brief description. The comment lines following H1 line constitutes help and these lines are returned by help command. The help starts from H1 line and end at rst blank line following H1.

2
2.1

Interactive Computations
Matrix Creation

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

2.2

Matrix Indexing

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

2.3

Matrix Manipulation

Let A be a matrix with m row and n column. To replace a single element (say A(i,j)) by a scalar (say b), simply use A(i, j) = b. To replace ith row (A(i,:)) by a row vector (v1n ), use A(i, :) = v1n . To replace j th column

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

December 31, 2011

Notes on Getting Started with MATLAB

(A(:,j)) by a column vector (vm1 ), use A(:, j) = vm1 . 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 to do so is A=[A, vm1 ], A=[A; v1n ]. 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)), matrix with all elements ones (ones(m,n)), identity matrix (eye(m,n)) etc. The function magic(n) generates a magic square of size n.

2.4

Matrix Operations

The arithmetic operations, +, - and * are as usual. The A/B is equal to AB 1 . The ^ is power operation for matrix. The element wise operation for multiplication, division and power are, .*, ./, and .^ , respectively. The element wise relational operations on matrix are <, >, <=, >=, ==, =. Let A and B are of size m n. The A RELationalOPeration B is matrix of size m n, with element value 1 when relation is true and 0 when relation is false. The element wise logical operation on matrices are AND (&), OR (|) and NOT (). The A LOGicalOPeration B 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 these functions.

2.5

Elementary Maths Functions

The MATLAB has inbuilt denition of almost all elementary maths function. You can directly call these functions from command window, script or function les. To get list of elementary functions, type help elfun. Some examples are trigonometric functions (sin, cos, tan, asin, acos, atan, sinh, . . . ), exponential functions (exp, log,. . . ), algebraic functions (sqrt, nthroot, . . . ), complex number functions (abs, angle, conj, img, real), round-off functions (oor, ceil, x, 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 Strings

The string in MATLAB is a sequence of characters in single quote. The function eval takes a string (a valid MATLAB expression) argument and evaluate it. The num2str is used for converting a number to string and str2num is used for converting a string to number. The lower converts upper case alphabets to lower case and upper do the converse. The strcmp and strncmp is used for comparing two strings. The strcat is for string concatenation. The ndstr nds 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 Data

There are various ways to save data to le and load data from le. The function save saves data from workspace to le (matlab.mat). This le name and variable to be saved into it can be specied as argument to save. The load function load data from le to workspace. The load can be used for .mat le as well any other ASCII le (provided it every row has same number of columns). See online help on save and load for details.

3
3.1

Programming in MATLAB
Script Files

The MATLAB provides programming features for solving complex problems. The script les are simplest way to learn these programming features. The script le contains sequence of valid MATLAB commands and expressions. The name of script le shall start with a letter and can have letters, digits and underscore (_). The lename shall not clash with names of built-in functions. Use exits to nd whether a built-in with same name exist or not. The name of any variable shall not be same as name of script le. The script le works on global workspace variable i.e. workspace variable are accessible to script and vice versa. Given below is example script le from reference [5]. All rights reserved with PsiPhiETC . These notes are created for educational purpose and may be used, distributed and/ or modied. Visit www.psiphi.in for updated notes and course schedule.

December 31, 2011

Notes on Getting Started with MATLAB

1 2 3 4 5 6 7

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

3.2

Function Files

The function le is one of the key feature of MATLAB. It begin with a function denition 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 le must be saved with same name as FunctionName with extension .m. The argin is the list of comma separated 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 be based on good pseudo-code and shall have features like readability, modularity, robustness and expandability. Given below is example function le, solvexf.m, from reference [5].
1 2 3 4 5 6 7 8 9 10 11

function [det_A, x]=solvexf(r) % SOLVEXF solves a 3x3 matrix eqn with parameter r % This is the function file solvexf.m % To call this function, type: % [det_A,x]=solvexf(r) % r is input and det_A and x are o/p A=[5, 2*r, r; 3,6, 2*r-1; 2, r-1, 3*r]; b=[2;3;5]; det_A=det(A); x=A\b;

3.3

Control Flow: if-elseif-else

This construction provides logical branching for computation. The syntax is,
1 2 3 4 5 6 7

if expression statements elseif expression statements else statements end

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


1 2 3 4 5 6 7

if I == J A(I,J) = 2; elseif abs(I-J) == 1 A(I,J) = -1; else A(I,J) = 0; end

3.4

Control Flow: for loops

The for loop is used to repeat statement(s) for a xed 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 modied. Visit www.psiphi.in for updated notes and course schedule.

December 31, 2011

Notes on Getting Started with MATLAB

1 2 3

for variable = expression statement(s) end

The columns of the expression are stored one at a time in the variable and then the following statements, up to the end, are executed. The for loops can be nested, but every for must be matched with an end. Given below is the example that nd sum of rst 100 natural numbers,
1 2 3 4

sum=0; for i=1:100 sum=sum+i; end

3.5

Control Flow: while loops

The while loop is generally used to execute statement(s) for an indenite number of times until condition specied by while is no longer satised. The general form of a while loop is:
1 2 3

while expression statements end

Given below is an example of while loop,


1 2 3 4 5 6 7

v=1; num=1; i=1; while (num4096) v=[v;num]; i=i+1; num=2^i; end v

3.6

Control Flow: switch-case-otherwise

The switch-case-otherwise construction provides logical branching for computation. A ag is used as a switch and the values of the ag make up different cases for execution. The general syntax is:
1 2 3 4 5 6 7 8

switch flag case value1 block 1 computation case value2 block 2 computation otherwise last block computation end

Given below is an example of switch-case,


1 2 3 4 5 6 7 8 9 10 11

color= input('color= ','s'); switch color case 'red' c=[1, 0, 0]; case 'green' c=[0, 1, 0]; case 'blue' c=[0, 0, 1]; otherwise error('invalid choice') end

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

December 31, 2011

Notes on Getting Started with MATLAB

3.7

break, continue, return

The command break inside a for or while loop terminates the execution of the loop. The command continue pass control to the next iteration of for or while loop. The command return simply returns the control to the invoking function.

3.8

Interactive Input: input, keyboard and pause

The 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 2

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

The command keyboard returns control from script/function to keyboard. The command window prompt changes to k . At this point, you can check variable already computed, change their values, and issue any valid MATLAB commands. 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/Output

The MATLAB supports standard C-language le I/O function for reading from and writing to les. The fopen opens an existing le or creates a new le and fclose closes an opened le. The fprintf is used for writing formatted data to le and fscanf for reading formatted data from le. The sprintf writes data in formatted string and sscanf reads string in specied format. The fgetl reads a line from a le discarding new-line character whereas fgets reads a line from a le including new-line character. Given below is a script le from reference [5].
1 2

3 4 5 6 7 8 9 10 11

% TEMPTABLE - generates and writes a temperature table % Script file to generate a Fahrenheight-Celsius temperature table. The table is written in ... file named 'Temperature.table' %----------------------------------------------------------F=-40:5:100; C=(F-32)*5/9; t=[F;C]; fid=fopen('Temperature.table','w'); fprintf(fid,' Temperature Table \n '); fprintf(fid,' Fahernheight Celsius \n'); fprintf(fid,' %4i %8.2f\n',t) fclose(fid)

4
4.1

Creating Graphics Programmatically


Figure

The command gure opens a new gure window and returns its handles (an object that is used to see or change properties of gure window). You can open multiple gure windows, each having separate handle, at the same time. The gure that is visible and is above others on screen is called current gure. The command gure (h), make the gure with handle h as current gure. The command gcf returns the handle of current gure. Some of the gure properties are its color, name, position, etc. The position is specied by a vector of size four. First two elements gives x and y coordinates of lower left corner. Third element is width of gure window and fourth element is its height. The gure window has a menubar. You can hide/display this by setting Menubar property to none/gure. To change the gure 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 modied. Visit www.psiphi.in for updated notes and course schedule.

December 31, 2011

Notes on Getting Started with MATLAB

4.2

Setting Figure Properties

You can see gure properties by get (h) command, where h is gure handle. The properties are displayed in PropertyName, PropertyValue pair. The active property is displayed in curly braces {} and alternative property is separated by or symbol (|). The gure properties can be changed by set command. The syntax of this command is set (h, PropertyName, PropertyValue). Given below is code for changing some of the gure properties.
1 2 3 4 5 6

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

4.3

Axes

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

4.4

Setting Axes Properties

The procedure to change axes properties is similar to that of gure. Use the get and set command for doing so. Given below is an example code:
1 2 3 4 5 6 7 8 9

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

4.5

Plot

The function plot creates linear plot and return handle to it. The plot (y) plots the columns of y versus their index. The plot (x,y) plot vector y versus vector x. Various colors, line types, and may be specied by using plot (x,y,LineSpec), where LineSpec gives line specication 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 plot properties. Given below is one example of plot,
1 2 3

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

4.6

Setting Plot Properties

The plot properties (line series properties) can be changed interactively by following Edit > Current Object Properties (Select Plot) > more properties. These properties can also be changed by get and set command. This method is useful 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 modied. Visit www.psiphi.in for updated notes and course schedule.

December 31, 2011

Notes on Getting Started with MATLAB

1 2 3 4 5 6 7

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

4.7

Overlay Plot

Sometime 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 specications for these plots. Another method is to use hold on | off. In this method, generates rst 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 for the next plot. The third method is to use line (x, y, PropName, PropValue). Given below is an example code:
1 2 3 4 5 6 7 8 9

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

4.8

Putting Text

The 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 specied by using text(x,y,string,PropertyName, PropertyValue). The properties can be changed by using get, set commands. The properties can also be changed by Edit > Current Object Properties (Select Text Object) > More Properties. The text can also be inserted by using Insert > Text Box. Use gtext (string) to place string, a place selected by mouse. The ginput command is used to get coordinates of a point selected by the mouse. Given below is the example code.
1 2 3 4 5 6

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

4.9

Axis

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

x=linspace(0,2*pi,100); y=sin(x); plot(x,y); 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 modied. Visit www.psiphi.in for updated notes and course schedule.

December 31, 2011

Notes on Getting Started with MATLAB

10

4.10

Legend

The legend command put legend on the plot. It can be called as legend (string), legend (string1,string2,. . . ) or legend (string1,string2,. . . , PropertyName, PropertyValue). The MATLAB put legend at a place it nd most suitable. The legend location can be changed by changing its Location property. The legend properties can be changed 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 the example code:
1 2 3 4 5 6

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

4.11

Subplot

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

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

4.12

Findobj

Many times we are interested to change an objects property but we do not know its handle. The command ndobj returns the object having a specied property. The h=ndobj (P1Name, P1Value, . . . ) returns the handles of the objects whose property values matches. The h=ndobj (ObjectHandles, P1Name, P1Value,. . . ) restricts the search to the objects listed in ObjectHandles and their descendents. See online help for more details on ndobj.
1 2 3 4 5 6 7

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

Creating Graphics Interactively

The reference for this part is Getting Started Guide [2].

5.1

Graphics Objects Hierarchy

Graphics objects are the basic drawing elements used by MATLAB to display data. Each instance of an object is associated with a unique identier called a handle. The graphical objects are arranged hierarchically. The children of a gure 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 modied. Visit www.psiphi.in for updated notes and course schedule.

December 31, 2011

Notes on Getting Started with MATLAB

11

5.2

Plotting Process

The plotting process involves creating graphs, exploring data, editing graph components, annotating graphs, printing and exporting graphs, adding and removing graphical contents and nally saving graph for re-use.

5.3

Figure Tools

The gure tools can be accessed from gure window. Some of these tools are zoom, pan, data cursor, basic tting and data statistics. The zoom tool is for zooming in or out particular area of the gure. It is possible to zoom horizontally or vertically, independently. The pan tool is for translation. The data cursor displays the data at the mouse location. The basic tting tool provides facilities for various type of data tting including linear, quadratic etc. The data statistics tools is for checking statistical properties of data like mean, median, standard deviation etc.

5.4

Plotting Tools

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

5.5

Figure Palette: New Subplots

You 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 Catalog

The Figure Palette provides features for interactive plotting. Let x and y, be two vectors of same size available in workspace. 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 the available options and one of them can be used for plotting.

5.7

Figure Palette: Annotations

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

5.8

Plot Browser

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

5.9

Property Editor

The Property Editor can be used to change properties of any graphics object. Select the object, go to the Property Editor and change properties. The common properties of the object are displayed on property editor. All properties can be viewed and changed by selecting More properties option from Property Editor. The object properties can also 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 modied. Visit www.psiphi.in for updated notes and course schedule.

December 31, 2011

Notes on Getting Started with MATLAB

12

5.10

Printing

The graphics can be printed on a standard printer. To see print preview, File > Print Preview. The print preview gives various options like placement of gure 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 StyleSheet for future use. These properties can also be changed by print and related commands.

5.11

Exporting

The gure can also be exported into various le formats like g, png, jpg etc. Select File > Export Setup. The Export Setup gives various options for changing gure properties before export. These properties are related to paper size, fonts, lines etc. Change these properties as required and export gure in desired format. The saveas and print commands can also be used for exporting gure.

5.12

Saving

The MATLAB provides two options for saving gures for reuse. These options are to save gure as .g le and generate M le. These options can be accessed from File menu. The .g le stores data, graphics objects and their properties. This le can be opened with MATLAB for exact creation of gure. The M le stores graphics object and their properties in the form of MATLAB function le. To recreate the gure you need to have data along with generated function le. The saveas can also be used for saving gure into .g le.

6
6.1

Publishing Report
Introduction

A You can create formatted reports in HTML, LTEX PDF or MS Word using MATLAB 7s built in publisher. This is the fastest way to communicate your work to others. To publish a report, you need to create a script, enable cell mode from cell menu, divide script into code cells, insert text markup for formatting, edit publish conguration (if required) and nally publish the report. These actions can be carried out interactively or programmatically. See online help on publish for details.

6.2

Code Cells

A code cell is a set of related commands that form one unit of computations. The beginning of a cell is marked by double percentage character (%%). A cell continues until beginning of another cell is encountered. Observe the change in color and cell separation line in editor. You can evaluate cells individually (Ctrl+Enter). Given below is example code displaying two cells:
1 2 3 4 5

%% Create vectors theta=linspace(0,10*pi,200); r=exp(-theta/10); %% Plot using polar plot polar(theta,r);

6.3

Document Title and Introduction

The report title is specied in rst code cell (starting from rst line) of script. The text after %% in rst cell is displayed as document title. The comment line (%) immediately following title line is displayed as document introductory text. To separate introductory text from rest of the document, you must put a line with double percentage (%%) after the introductory text. The document contents are automatically generated and displayed after the introductory 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 modied. Visit www.psiphi.in for updated notes and course schedule.

December 31, 2011

Notes on Getting Started with MATLAB

13

1 2 3 4

%% This is the Title % Introductory text % Introductory text %%

6.4

Section and Section Titles

The document sections and cells are related to each other. You can create new cell that starts a new section by putting %% 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 section title in same line. These three methods are shown in example code given below:
1 2 3 4 5 6 7

%% New Section with New Cell % double percentage followed by section title %% % To create New Cell in Existing Section: % double percentage followed by nothing %%% New Section in Existing Cell % triple percentage followed by section title

6.5

Other Text Markup

The text markup (formatted text) can be inserted in comment lines. You can create bold text by *bold text *, italic text by _ italic text_ and monospace text by |monospace text|. The bulleted list can be created by putting * in front of 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 2 3 4 5 6 7 8 9 10

%% Other Text Markup % *bold text* , _italic text_ , | monospace text | % % * Item 1 % * Item 2 % % # Item 1 % # Item 2 % % <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 is A generated, see section 6.7). The TEX equations can be inserted like $$ ei + 1 = 0 $$. You can also insert LTEX and HTML stuff into your report.

6.7

Conguration

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

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

December 31, 2011

Notes on Getting Started with MATLAB

14

6.8

Displaying Results

The published report contains title, introductory text, list of contents, section title and section introduction, MATLAB code, generated gures 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 in report. Given below is example code:
1 2 3 4 5 6 7

%% Displaying Output phi=1.618; PHI=(1+sqrt(5))/2; s=sprintf('phi=%5.3f, PHI=%10.8f',phi,PHI); disp(s); disp(PHI); phi

6.9
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

Example File for Publishing Report

%% Document Title % Introductory text %% Section % Section introduction %% Other Text Markup % *bold text* , _italic text_ , |monospace text| % <www.psiphi.in> %% More Text Markup % The TeX equations can be inserted like: % $$\phi=\frac{1+\sqrt{5}}{2}$$ %% Displaying Output phi=1.618; PHI=(1+sqrt(5))/2; s=sprintf('phi=%5.3f, PHI=%10.8f',phi,PHI); disp(s); disp(PHI); phi %% Plot theta=linspace(0,10*pi,200); r=exp(-theta/10); polar(theta,r);

7
7.1

Building GUI
Introduction

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

7.2

GUIDE

The GUIDE can be opened by guide command or GUIDE toolbar on MATLAB Desktop. You can open existing GUI or create new GUI. You can open blank (default) or one of the available template. The GUIDE interface contains menu bar on the top. Help menu show MATLAB help for GUIDE. The toolbar is shown just below menu bar. The Layout editor is shown on the left side of interface. Use File > Preference > GUIDE > Show Names in Component palette > OK to show name of components on editor. The GUIDE Layout Editor help you in creating components like axes, push button, static text, pop-up menu etc. The GUI is created in grid portion of interface. The GUI 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 modied. Visit www.psiphi.in for updated notes and course schedule.

December 31, 2011

Notes on Getting Started with MATLAB

15

7.3

Creating Simple GUI

The MATLAB simple_ gui is a demo program for building GUI. Type simple_ gui in command window. It will open 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 GUI components (axes, three push buttons, static text and pop-up menu) by draging them to editing space. You can align pushbuttons 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 inspector by View > Property Inspector. Now select particular component (the property inspector will show the properties of selected component) and view its properties. Change string of pushbutton (Select Push Button > String > Change it), 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 .g (that contains a complete description of the GUI layout) and an .m le (that contains the code that controls the GUI, including the callbacks for its components). These les are created in same directory.

7.5

Programming Simple GUI

The most important part of GUI development is programming it. The GUI components have callback functions that are called particular event is triggered. The GUI can be programmed directly by modifying .m le. You can view the callback functions of various components from context menu (select+right click). See MATLAB help and simple_ gui.m for details of how GUI is programmed. Two important functions that need to be programmed are OpeningFunction 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 modied. Visit www.psiphi.in for updated notes and course schedule.

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);

Simulink

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

8.1

Introduction

Simulink is used for modeling, simulation and analysis of dynamic systems. It is tightly integrated with the MATLAB environment. Simulink provides a GUI for building models as block diagrams. It also includes a comprehensive block library of sinks, sources, linear and nonlinear components, and connectors. You can also create your own blocks. After the model is dened, it can be simulated by using a choice of mathematical integration methods, either from the Simulink menus or by entering commands in the MATLAB Command Window. Simulation results can be seen by using scopes and can be put in the MATLAB workspace for post processing and visualization. Model analysis 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 Interface

The Simulink can be started by simulink command or by clicking Simulink icon in MATLAB toolbar. The user interface consists of Simulink Library Browser and Simulink Model Window. The Simulink Library Browser have Commonly 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 block diagram, set conguration parameters, start-stop, save, print etc.

8.3

Example 1: Sine Wave and its Integration


t

Displays: (1) sin (2) t0 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, output port, Select rst block hold Ctrl key Select 2nd block (branch). The block diagram is given in gure 1. Simulation: Simulation Conguration 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 by equation given below: m + cx + kx = f (t) x 1 x = (f (t) cx kx) m Where x is displacement, t is time, m is mass, c is damping coefcient, 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 modied. Visit www.psiphi.in for updated notes and course schedule.

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 gure 2. Use Ctrl+F for ip 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 gure 3. 3. Double click the transfer function block and enter numerator, denominator (eg. set m = 2.0, c = 0.7, k = 1). 4. Double click the save output to le block and set lepath and lename (MAT le) 5. Run the simulation 6. MATLAB command widow, load mat le, who, plot

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

December 31, 2011

Notes on Getting Started with MATLAB

18

Figure 3: Spring Mass System (Transfer Function)

8.6

Example: Capacitor Charging


1 1 V = V + u RC RC

This example demonstrates capacitor charging. The model is equation equation given below:

Where V is voltage, t is time, R is resistance, C is capacitance, and u is unit step function. The Laplace transform of above equation is given by: V (s) = 1 s 1 1 U (s) V (s) RC RC

1. Create new model and drag: Sources Step, Math Operation Gain, Math Operation Gain, Math Operation Sum, Continuous Integrator, Sinks Scope 2. Connect these blocks as in gure 4. Use Ctrl+F for ip and Ctrl+R to rotate. 3. Edit the step block and enter nal 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 conguration parameters (1) Type: xed (2) Fixed Step Size: 0.01 (3) Solver: ode3 (BogackiShampine) 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 modied. Visit www.psiphi.in for updated notes and course schedule.

December 31, 2011

Notes on Getting Started with MATLAB

19

Homework
1. What does the name MATLAB stand for? 2. Every programming language has its own set of advantages and disadvantages. List some of the advantages and disadvantages of using Matlab. 3. Name three ways that its possible to get help from within Matlab. 4. Rudra Pratap: Arithmetic Operations: Compute the following quantities: (a) (b)
25 25 1 and 51 3 (5+1)2

compare with (1 1.

1 1 . 25 )

(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 calculated 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

.
ln 17 ln3 .

(c) Solve 3x = 17 for x and check the result. (The solution is x = substitution.)

You can verify the result by direct

6. Rudra Pratap: Trigonometry: The basic MATLAB trig functions are sin, cos, tan, cot, sec, and csc. The inverses, 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. The argument of these functions must be in radians. Calculate the following quantities: (a) sin , cos , and tan 6 2 (b) sin2
6

+ cos2

(c) y = cosh2 x sinh2 x, with x = 32. 7. Rudra Pratap: Equation of a straight line: The equation of a straight line is y = mx + c, where m and c are constants. Compute the y-coordinates of a line with slope m = 0.5 and the intercept c = 2 at the following 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 = (c) z =
t1 t+1 sin(t2 ) t2

9. Rudra Pratap: Points on a circle: All points with coordinates x = r cos and y = r sin , where r is a constant, lies on a circle with radius r, i.e. they satisfy the equation x2 + y 2 = 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. Now check that x and y indeed satises the equation of a circle, by computing the radius r = (x2 + y 2 ). 10. Rudra Pratap: A simple line plot: Plot y = sin x, 0 x 2, taking 100 linearly spaced points in the given 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). Now combine the two plots with the command plot(x,y,x,y,o) to show the line through the data points as well as the distinct data points. All rights reserved with PsiPhiETC . These notes are created for educational purpose and may be used, distributed and/ or modied. Visit www.psiphi.in for updated notes and course schedule.

December 31, 2011

Notes on Getting Started with MATLAB

20

12. Rudra Pratap: An exponentially decaying sine plot: Plot y = e0.4x sin x, 0 x 4, taking 10, 50, and 100 points in the interval. [Be careful about computing y. You need array multiplication between exp(0.4 x) and sin(x)]. 13. Rudra Pratap: On-line help: Type help plot on the MATLAB prompt and hit return. Read through the on-line help on plot. 14. Rudra Pratap: Overlay Plots: Plot y = cos x and z = 1 x + x for 0 x on the same plot. [Hint: 2 24 you can use plot(x,y,x,z,) or you can plot the rst curve, use the hold on command, and then plot second curve on top of the rst one.] 15. Rudra Pratap: Show center of the circle: Given below is content of script le circle.m
1 2 3 4 5 6 7 8 9 2 4

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

Modify the script le 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 le circle.m to draw a circle of arbitrary radius as follows: (a) Include the following command in the script le before the rst executable line (theta=. . . ) to ask the user 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 le. When asked, enter the value of radius and press return. 17. Rudra Pratap: Variables in the workspace: All the variables created by a script le are left in the global workspace. 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 in the 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 transpose operator (). 18. Rudra Pratap: H1 Line: The rst commented line before any executable statement in a script le is called H1 line. It is this line that is searched by the lookfor command. Since the lookfor command is used to look for M-les with keywords in their description, you should put keywords in H1 line of all M les you create. Type lookfor unit to see what MATLAB comes up with. Does it list the script le you just created? 19. Rudra Pratap: Convert Temperature: Write a function that outputs a conversion table for Celsius and Fahrenheit temperatures. The input of the function should be two temperatures: Ti and Tf , specifying the lower and upper range of the table in Celsius. The output should be a two column matrix: the rst column showing the temperature in Celsius from Ti to Tf in the increments of 1 C and the second column showing corresponding temperature in Fahrenheit. To do this (i) create the column vector C from Ti to Tf with the 9 command C=[Ti:Tf], (ii) calculate the corresponding numbers in Fahrenheit using the formula F = 5 C +32, and (iii) make the nal matrix with the command temp=C F];. Note that you output variable will be named temp.

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

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 integer n. The input should be number n and the output should be n!. You might have to use for loop or a while loop to do the calculation. 21. Rudra Pratap: What is the MATLAB path? The MATLAB path is a variable, stored under the name path (the variable that contains the list of all directories that are automatically included in MATLABs search path). It is generated by a le 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 les in different directories and would like to have access to all your les automatically each time you work in MATLAB, you need to modify the MATLAB search path with path or 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 called mywork on the C: drive. (b) Use command addpath to add these directories to the existing path. Query with path to see that the directories are added. (c) Use command savepath to save the new path permanently. This command will modify the pathdef.m le. 22. Rudra Pratap: Entering Matrices: Enter the following three matrices: A= 2 3 6 9 , B= 1 3 2 4 , C= 5 5 5 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 the results same? (c) Is multiplication with a scalar distributive? Compute (A + B) and A + B, taking = 5 and show that 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 = 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 of the matrix generation functions zeros, eye, and ones. See the help on these functions if required (e.g., help eye). 5 0 0 0 0 0 3 3 , E = 0 5 0 , F = D= 0 0 0 3 3 0 0 5 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. 2 6 0 0 0 0 3 9 0 0 0 0 0 0 1 2 0 0 G= 0 0 3 4 0 0 0 0 0 0 5 5 0 0 0 0 5 3 All rights reserved with PsiPhiETC . These notes are created for educational purpose and may be used, distributed and/ or modied. Visit www.psiphi.in for updated notes and course schedule.

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 rst 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) nd(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 the other? 30. What does the break command do inside a loop? What does the continue command do? 31. Name 3 benets of writing functions when programming? 32. MATLABs 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 2 3

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

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

x(1) length(x) x(length(x)) x' prod(x) x( [1 3] ) [ x\; x] [ x \; x]

36. Write MATLAB commands that would create matrices according to the following specications: (a) A 4x4 matrix of random numbers, each between (-1.0) and (+1.0). Hint: create a matrix with random numbers between 0.0 and 2.0 and go from there. (b) A 5x5 matrix with the center row and the center column having 1s and all other spots having 0s. All rights reserved with PsiPhiETC . These notes are created for educational purpose and may be used, distributed and/ or modied. Visit www.psiphi.in for updated notes and course schedule.

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. Remember the difference between summing a vector and summing a matrix! 38. Write MATLAB commands that would use subplot (subplot(rows,cols,current)) to create a gure with two plots 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 of hours and minutes. For example, if 90 minutes were entered, the program would print, 90min = 1h 30m. Hint: for the hours, nd out how many whole sets of 60 are in the original number of minutes. For the converted minutes, nd 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, then display the product of all values from 1 up to that number. For example, if you type in 5 the program would print: 5! = 120 41. Identify 5 errors in the following program and mark corrections. Look for both syntax errors and logical errors. The intent of the function is to examine the parameter and return the value 1 if its positive, -1 if negative, or 0 if its zero.
1 2 3 4 5 6 7 8 9

function result mysign[ num ] if (num $>$ 0) result = 1; end if (num $<$ 0) result = -1; else num = 0; end if

42. For what range of numbers for x is each of the following conditions true? You can describe the ranges in general terms (e.g. numbers 1-10) or in set notation (e.g. [1,10]). (a) (b) (c) (d) (e) (x >= 1) & (x <= 10) (x >= 1) | (x <= 10) (x < 1) & (x > 10) (x < 1) | (x > 10) < 1) | (x > 10)) ((x

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


1 2 3 4 5 6 7 8

switch (n) case 10 fprintf( 'Decimal!' ); case 16 fprintf( 'Hexadecimal!' ); otherwise fprintf( 'Invalid' ); end

44. Between a for loop and a while loop, which one should be used when you dont know ahead of time how many times the loop should be repeated? 45. What numbers will the following program print out?
1 2 3 4 5

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

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

December 31, 2011

Notes on Getting Started with MATLAB

24

46. What will the following program print out?


1 2 3 4 5 6 7 8 9

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

47. Write a function called isodd that takes a number as a parameter and returns the value 1 if its an odd number or 0 if its 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 rstfactor that takes a parameter num and returns the rst factor of the number higher than 1. Hint: check the remainder of the number divided by all values between 2 and the number itself. The rst value without a remainder will be the rst factor of the number. 49. Write a function called gcfactor(a,b). It should return the number that is the greatest common factor for the numbers 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 a zero remainder, return the value i as the answer. 50. Write a MATLAB program that calculates and prints out the rst 20 numbers in the Fibonacci sequence. The rst two numbers in the sequence are 0 and 1. Each number after that is the sum of the previous two numbers. So the rst 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) be 1 the horizontal and vertical position at time t. These are given by, x(t) = vt cos and y(t) = vt sin 2 gt2 , 2v sin 2 where g = 10ms is acceleration due to gravity. The time of ight, T , is given by T = 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 display them. 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 modied. Visit www.psiphi.in for updated notes and course schedule.

Vous aimerez peut-être aussi