96
DREAM PLAN IDEA IMPLEMENTATION

Matlab Lectures 1

  • Upload
    iman145

  • View
    99

  • Download
    12

Embed Size (px)

Citation preview

DREAMDREAM

PLANPLAN

IDEAIDEA

IMPLEMENTATIONIMPLEMENTATION

Introduction to MatlabBy

Dr. Kourosh Kiani

Matrix Laboratory

Course Structure

• Spread over 8 weeks

• 1 classes per week

• 2 hour per class

Introduction

History of MATLAB

• Ancestral software to MATLAB

– Fortran subroutines for solving linear (LINPACK) and eigenvalue (EISPACK) problems

– In 1970, Cleve Moler, the chairman of the computer science department at University of New Mexico, designed MATLAB to give his students to access LINPACK and EISPACK without requiring knowledge of Fortran

History of MATLAB, con’t: 2

• Later, when teaching courses in mathematics, Moler wanted his students to be able to use LINPACK and EISPACK without requiring knowledge of Fortran

• MATLAB developed as an interactive system to access LINPACK and EISPACK

History of MATLAB, con’t: 3

• It soon spread to other universities and found a strong audience within the applied mathematics community.

• MATLAB gained popularity primarily through word of mouth because it was not officially distributed

• In1984, Jack Little, Cleve Moler and Steve Bangert rewrote MATLAB in C with more functionality (such as plotting routines).

History of MATLAB, con’t: 4

• The Mathworks, Inc. was created in 1984

• The Mathworks is now responsible for development, sale, and support for MATLAB

• The Mathworks is located in Natick, MA

What Is MATLAB?

MATLAB (MATrix LABoratory)• high-performance language for technical computing• computation, visualization, and programming in an easy-to-use environment

Typical uses include:

• Math and computation• Algorithm development• Modelling, simulation, and prototyping• Data analysis, exploration, and visualization• Scientific and engineering graphics• Application development, including Graphical User Interface building

A good choice for vision program development because:

• Easy to do very rapid prototyping• Quick to learn, and good documentation• A good library of image processing functions• Excellent display capabilities• Widely used for teaching and research in universities and

industry• MATLAB code is optimized to be relatively quick when

performing matrix operations• MATLAB may behave like a calculator or as a programming

language

Why MATLAB

Why not MATLAB

Has some drawbacks:

• Slow for some kinds of processes• Not geared to the web• Not designed for large-scale system development• Not a general purpose programming language• MATLAB is an interpreted language (making it for the

most part slower than a compiled language such as C++)

MATLAB Components

MATLAB consists of:The MATLAB language• a high-level matrix/array language with control flow statements, functions,

data structures, input/output, and object-oriented programming features.

• The MATLAB working environment• the set of tools and facilities that you work with as the MATLAB user or

programmer, including tools for developing, managing, debugging, and profiling

• Handle Graphics• the MATLAB graphics system. It includes high-level commands for two-

dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics.

• …(cont’d)

• The MATLAB function library. • a vast collection of computational algorithms ranging from

elementary functions like sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms as well as special image processing related functions

• The MATLAB Application Program Interface (API)• a library that allows you to write C and Fortran programs that

interact with MATLAB. It include facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files.

MATLAB Components

Some facts for a first impression

• Everything in MATLAB is a matrix !

• MATLAB is an interpreted language, no compilation needed (but possible)

• MATLAB does not need any variable declarations, no dimension statements, has no packaging, no storage allocation, no pointers

• Programs can be run step by step, with full access to all variables, functions etc.

MATLAB

Opening MatLAB

• Open MatLAB by

– Clicking on the desktop icon or finding MatLAB on the Start menu

To start MATLAB:

START PROGRAMS MATLAB 7.0 MATLAB 7.0

MATLAB Environment

MatLAB window

Command WindowCommand History

Window

Contents of CWDCurrent working Directory (CWD)

Write different MATLAB commands, and watch most of the results

Watch and manipulate your

variables

Recall your past commands

Workspace

• Allows access to data

• Area of memory managed through the Command Window

• Shows Name, Size (in elements), Number of Bytes and Type of Variable

Current Directory

• MATLAB, like Windows or UNIX, has a current directory

• MATLAB functions can be called from any directory

• Your programs (to be discussed later) are only available if the current directory is the one that they exist in

To add path

Select the folder where you placed your M-File

Add Folder…

File – Set Path…

Command History

• Allows access to the commands used during this session, and possibly previous sessions

• Clicking and dragging to the Command window allows you to re-execute previous commands

Command Window

• Probably the most important part of the GUI

• Allows you to input the commands that will create variables, modify variables and even (later) execute scripts and functions you program yourself.

• MatLAB interface has four important features– Current working directory drop-down box– Command window (human interface)– Command history window– Contents of CWD

‘command’ files

• When you type the name of a command, MatLAB begins looking for a ‘.m’ file with that name

• Search begins in the Current Working Directory (CWD)

• Best Practice is to set CWD to you network (‘?:’) drive

Command files

• Command files may be

– Internal MatLAB functions

– User-defined script file

– User-defined function file

‘Script file’ vs ‘Function file’

• Script file

– Process a series of MatLAB commands

– Uses global variable space

• Function file

– Usually accepts one or more variable arguments

– Usually returns one or more values determined by the argument(s) supplied

– Uses its own local variable space

Matlab Programs

• Matlab is an extravagant calculator if all we can do is execute commands typed into the Command Window…

• So how can we execute a “program?”

• Programs in Matlab are:– Scripts, or

– Functions

• Scripts: Matlab statements that are fed from a file into the Command Window and executed immediately

• Functions: Program modules that are passed data (arguments) and return a result (i.e., sin(x))

• These can be created in any text editor (but Matlab supplies a nice built-in editor)

Global vs. Local variables

• Global variables are known everywhere

– Any variable defined in the command window is global

– Any variable defined in a script is global

• Local variables are known only in the ‘current’ program segment (function file)

Write a simple script file

• Open .m editor

Simple Script

• Ask user for name• Output string welcoming ‘name’ to Dr. Kiani Lecture• Save as ‘welcome.m’

M-files

• M-files are macros of MATLAB commands that are stored as ordinary text files with the extension "m", that is filename.m

• example of an M-file that defines a function, create a file in your working directory named yplusx.m that contains the following commands:

Write this file:function z = yplusx(y,x) z = y + x; -save the above file(2lines) as yplusx.mx = 2; y = 3; z = yplusx(y,x) 5• Get input by prompting on m-file: T = input('Input the value of T: ')

• A semi-colon ‘;’ suppresses echo of MatLAB commands

• Square brackets ‘[ ]’ are used to collect or concatenate like items in MatLAB

• The ‘input()’ function is used to prompt user for input in the command window

• The ‘disp()’ function is used to display strings or variables in the command window

Output from ‘welcome.m’

• Note that the input value ‘Semnan’ must be enclosed in single tick marks so MatLAB knows it is a string variable

• MatLAB commands may be either ‘Script’ or ‘Function’ type

• Script file– No parameters (arguments)– No return value– Uses global address space

• Function file– May take parameters– Typically returns one or more values– Uses local address space

MATLAB program design fundamentals

• MATLAB variable name conventions– Starting with a letter followed by other characters– Case sensitive. Abc ABc are different– Valid variable names: MYvar12, MY_Var12 and

MyVar12_– Invalid variable names: 12MyVar, _MyVar12

• MATLAB reserved variables/constants– eps, i, j, pi, NaN, Inf, i=sqrt(-1)– lastwarn, lasterr

Reserved Words…

• Matlab has some special (reserved) words that you may not use…

for

end

if

while

function

return

elsif

case

otherwise

switch

continue

else

try

catch

global

persistent

break

Matlab has Some Special Variables

Special Variable Description

ans default variable name for results

beep make sound

pi mathematical constant

eps smallest number that can be subtracted from 0 to make a negative

inf infinity

NaN not a number

i (or) j imaginary number

realmin, realmax smallest & largest positive real numbers

bitmax largest positive integer

nargin, nargout number of function in (or) out variables

varargin variable number of function in arg’s

varaout variable number of function out arg’s

The Matlab Environment

• Matlab is an interpreted language

– Commands are typed into the COMMAND Window and executed immediately

– Variables are allocated in memory as soon as they are first used in an expression

– Commands must be re-entered to be re-executed

• All variables created in the Command Window are in what is called the Base Workspace

– Variables can be reassigned new values as needed

– Variables can be selectively cleared from the workspace

• The Workspace can be saved to a data file

– File extension is .mat (ex: mydata.mat)

– File is in binary and essentially unreadable by humans

– .mat files can be reloaded back into the Matlab Workspace

Numerical type data structure

• Double precision numerical variable

– IEEE standard, 64 bits (8 bytes), 11 bits for exponential and 53 bits for numerical and a sign bit.

– Use double() to convert other types to double.

• Other data types.

– Uint8, unsigned 8 bit integer commonly used in image presentation and processing

– int8(), int16(), int32(),uint16(), uint32()

Managing MATLAB Environment

• who or whos -- See the current runtime environment

• clear -- remove all variables from memory

• clc -- clear the command window

• clf -- clear the graphics window

• save -- save the workspace environment

• load -- restore workspace from a disk file

• abort -- CTRL-C

• help -- help “command”

Really good “help” command

Using MATLAB functions

• MATLAB functions come “built in” to MATLAB, sqrt, sin, abs, max, exp, etc.

• MATLAB functions come in specialized “toolboxes” for special fields of work; the financial toolbox, statistical toolbox, symbolic math toolbox are examples.

• And, you will be able to write your own functions and use them just like built in ones.

Some Elementary Math Functions

• abs(x) absolute value• sqrt(x) square root• round(x) rounds to nearest• fix(x) truncates toward 0• floor(x) rounds down• ceil(x) rounds up

• sign(x) sign of x• rem(x,y) remainder of x/y• exp(x) e raised to x power• log(x) natural log of x• log10(x) log to the base 10• log2(x) log to the base 2

Some Trigonometric Functions

• sin(x) computes the sine of x, x in radians,• cos(x) computes the cosine of x, x in radians• tan(x) computes the tangent of x, x in radians• asin(y) computes the inverse sine, -1 < x < +1• atan(y) computes the inverse tangent, i.e.,

computes the angle whose tangent is y

• Notice that MATLAB wants angles to be expressed in radians, not degrees. To convert use the relationship

• 1 degree = pi/180 radians• angle_radians = angle_degrees*(pi/180)• angle_degrees = angle_radians*(180/pi)

Other Useful Elementary Analysis Functions

• max(x), min(x), mean(x), median(x), std(x), sum(x), prod(x), cumsum(x), cumprod(x), sort(x), size(x), length(x) are just a few.

• Note that x may be a vector (row or column) or a matrix. For matrices, functions typically work on the columns of the matrix to yield their results.

Random Number Generators

• MATLAB contains two random number generators, rand(n,m) for uniformly distributed random numbers and randn(n,m) for normal or Gaussian distributed random numbers.

• Random number sequences can be scaled for different mean and standard deviation requirements.

• Sequences of random numbers are often used in engineering problem solving.

• x = 10*rand(1,100) – 5; creates a row vector x with 100 random numbers uniformly distributed between -5 and 5.

• Enter the above command followed by the command plot (x) to see what happens.

Simple Commands

• who

• whos

• save

• clear

• load

who

• who lists the variables currently in the workspace.

• As we learn more about the data structures available in MATLAB, we will see more uses of “who”

whos

• whos is similar to who, but also gives size and storage information

• s = whos(...) returns a structure with these fields name variable name size variable size bytes number of bytes allocated for the array class class of variable and assigns it to the variable s. (We will discuss structures more).

Save

• save – saves workspace variables on disk

• save filename stores all workspace variables in the current directory in filename.mat

• save filename var1 var2 ... saves only the specified workspace variables in filename.mat. Use the * wildcard to save only those variables that match the specified pattern.

Clear

• clear removes items from workspace, freeing up system memory

• Examples of syntax:– clear

– clear name

– clear name1 name2 name3 ...

clc

• Not quite clear

• clc clears only the command window, and has no effect on variables in the workspace.

Load

• load - loads workspace variables from disk

• Examples of Syntax:– load

– load filename

– load filename X Y Z

MATLAB Basics: Data Files

• save filename var1 var2 …

– save homework.mat x y binary

– save x.dat x –ascii ascii

• load filename

– load filename.mat binary

– load x.dat –ascii ascii

Matlab Help

Some Simple Calculations

•Matlab capable of simple mathematical operations analogous to a calculator:

•>> 9.3 + 5.6

•ans =

• 14.9000

•>> 13.1 - 4.113

•ans =

• 8.9870

•>> 10.1 * 890.99

•ans =

• 8.9990e+03

Some Simple Calculations-2

• >> 9.6 / 3.2

• ans =

• 3.0000

• >> 9.9 ^ 3.1

• ans =

• 1.2203e+03

The ans variable

• The results of calculations do not need to be saved to a variable explicitly.– If no variable is specified then the result is automatically saved to

the ans (answer) variable.

• This variable may be subsequently used

• >> 91.3 – 14

• ans =

• 77.3

• >> z=ans * 2

• z =

• 154.6

The ans variable - 2

• In general you should not use ans but your own meaningfully named variables

• Examining a Variable’sValue– Simply typing a variable’s name alone is interpreted as a

command to show the value stored in that variable

• >>z

• z =

• 144.6

Semicolon, Comma & Period

• By default Matlab interprets the end of a line as the end of a statement/expression

• Semicolon

• Semicolon ; terminates the current expression and suppresses output (to the screen) of the result

• volume = pi * radius^2 * height;– The value is calculated and stored in volume but not echoed back to the

screen.

• A semicolon should be used on most lines of code as we are not interested in intermediary results

Semicolon, Comma & Period - 2

• Comma

• The comma , can be used to separate multiple statements on the same line. The value of any variables will be echoed to the screen.

• x=5.7, y=89.12– will echo those variables and their names back on the screen.

Semicolon, Comma & Period - 3

• Period

• Long statements can be split over lines by 3 periods

• Z = x-d+t+g+h+d-3+b+r+m+n+j …• - p;

Complex Numbers

• Matlab implicitly supports complex numbers– no requirement for special functions to manipulate

• For example:

• » z1=sqrt(-4)+3

• z1 =

• 3.0000+ 2.0000i

• » z2=z1*(1-i)– z2 =

– 5.0000- 1.0000i

Complex Numbers - 2

• » z3=5.6*sin(1.55)*i

• z3 =

• 0+ 5.5988i

• » r1=imag(z3)

• r1 =

• 5.5988

• » z4=mean([z1 z2 z3])

• z4 =

• 2.6667+ 2.1996i

Complex Numbers - 3

• Note:– mathematical and built-in function usage is

exactly the same as for non-complex– complex expressions yield complex values

NaN & Inf

• Mathematical operations can often yield undefined results or those beyond the storage capability of the machine

• In many languages these type of operation (e.g., division by zero) cause the running program to crash– not particularly desirable

• Matlab has two special "constants" which are substituted when such operations occur:– NaN Not a Number

– Inf Infinity

NaN & Inf - 2

• This allows recovery or continuation

• >> undef=0/0

• Warning: Divide by zero.

• undef =

• NaN

• >> big=1/0

• Warning: Divide by zero.

• big =

• Inf

NaN & Inf - 3

• >> big2=2^realmax

• big2 =

• Inf

Strings

• Not all real-world objects are best represented by numbers– e.g., names, addresses, units of measurement

• A common type supported by most languages (including Matlab) is the String– a collection of characters

• Indicated by the single-quote '

Strings

• A string is an array of characters– s = 'abc'

is equivalent to s = [ 'a' 'b' 'c' ]• All operations that apply to vectors and arrays can

be used together with strings as well– s(1) 'a'– s( [ 1 2 ] ) = 'XX' s = 'XXc'– s(end) 'c'

String Conversion

• Conversion of strings to numerical arrays– double( 'abc xyz' )

ans = 97 98 99 32 120 121 122

– double( 'ABC XYZ' )

ans = 65 66 67 32 88 89 90

• Conversion of numerical arrays to strings– char( [ 72 101 108 108 111 33 ] )

ans =Hello!

Character Arrays

• 2-D character arrays– s = [ 'my first string'; 'my second string' ]

??? Error– s = char( 'my first string', 'my second string' )

s =my first string my second string

– size(s) [ 2 16 ]– size( deblank( s(1,:) ) ) [ 1 15 ]

char function

automatically pads strings

String Tests

• ischar() : returns 1 for a character array– ischar ( 'CS 111' )

ans = 1

• isletter() : returns 1 for letters of the alphabet– isletter( 'CS 111' )

ans = 1 1 0 0 0 0

• isspace() : returns 1 for whitespace (blank, tab, new line)– isspace( 'CS 111' )

ans = 0 0 1 0 0 0

String Comparison

• Comparing two characters– 'a' < 'e'

ans = 1

• Comparing two strings character by character– 'fate' == 'cake'

ans = 0 1 0 1

– 'fate' > 'cake'

ans = 1 0 1 0

String Comparison

• strcmp() : returns 1 if two strings are identical– a = 'Bilkent';– strcmp( a, 'Bilkent' )

ans = 1

– strcmp( 'Hello', 'hello' )ans = 0

• strcmpi() : returns 1 if two strings are identical ignoring case– strcmpi( 'Hello', 'hello' )

ans = 1

String Comparison

• >> str1='My first string'

• str1 =

• My first string

• >> findstr(str1,'first')

• ans =

• 4

• >> strcmp(str1,'My')

• ans =

• 0

Strings

• >> strncmp(str1,'My',2)

• ans =

• 1

• >> str2='45.6'

• str2 =

• 45.6

• >> str2num(str2)

• ans =

• 45.6000

Strings

• >> str1

• str1 =

• My first string

• >> str2

• str2 =

• 45.6

• >> strcat(str1,str2)

• ans =

• My first string45.6

String Case Conversion

• Lowercase-to-uppercase– a = upper( 'This is test 1!' )

a =THIS IS TEST 1!

• Uppercase-to-lowercase– a = lower( 'This is test 1!' )

a =this is test 1!

Searching in Strings

• findstr() : finds one string within another one– test = 'This is a test!';– pos = findstr( test, 'is' )

pos = 3 6

– pos = findstr( test, ' ' )

pos = 5 8 10

Replacing in Strings

• strrep() : replaces one string with another– s1 = 'This is a good example';– s2 = strrep( s1, 'good', 'great' )

s2 =This is a great example

String Conversion

• Recall num2str() for numeric-to-string conversion– str = [ 'Plot for x = ' num2str( 10.3 ) ]

str =Plot for x = 10.3

• str2num() : converts strings containing numbers to numeric form– x = str2num( '3.1415' )

x = 3.1415

Managing Variables

• The variables created during a Matlab session are not persistent objects:

– they cease to exist when the session is over

– endure for the duration of the session

• Matlab provides the following command for managing the workspace

• clear

• delete a variable now

Managing Variables - 2

•>> x=7.9

•x =

• 7.9000

•>> clear x

•>> x

•??? Undefined function or variable 'x'.

•Useful if you wish to ensure that a variable starts with no value

– initialisation

Managing Workspace: load

• Load in a variable that has previously been saved from Matlab or another source

• >> linear=1:10

• linear =

• 1 2 3 4 5 6 7 8 9 10

• >> save linear

• >> clear linear

• >> linear

• ??? Undefined function or variable 'linear'.

Managing Workspace: load -2

• >> load linear

• >> linear

• linear =

• 1 2 3 4 5 6 7 8 9 10

• Useful for large and/or important data

Managing Workspace: save

• Save a matlab variable to a file for usage in a later session

• >> squares=linear.^2

• squares =

• 1 4 9 16 25 36 49 64 81 100

• >> save mydata linear squares

• >> clear linear squares

• >> squares

• ??? Undefined function or variable 'squares'.

Managing Workspace: save -2

• >> load mydata

• >> squares

• squares =

• 1 4 9 16 25 36 49 64 81 100

The format command

• Matlab has a default behavior when outputting numeric values:– if value is a whole number then display as an

integer– otherwise if there’s about 5 significant digits or

less then display as a float– otherwise display it in scientific notation

The format command - 2

• Matlab provides a number of different possible formats for showing numeric values– specified with the format instruction

– applies for all disp (and variable name) output until the format is changed with another format instruction.

– format by itself returns to the default format

• Command Explanation

The format command - 3

• format short 5 digits, also the default format

• format long 16 digits

• format short e 5 digits in exponential form

• format long e 16 digits in exponential form

• format short g “better” of short or short e

• format long g “better” of long or long e

• format hex As a hexadecimal number

• format bank To 2 decimal places (like currency)

• format + Sign of value only

• format rat As a rational approximation

Format Examples

• format instructions should be used in conjunction with disp to ensure the output answers are in the most appropriate form.

• Note: format does not change the actual value of the variable being displayed, it simply alters the display format.

• >> format short; disp(pi);

• 3.1416

• >> format long; disp(pi);

• 3.14159265358979

Format Examples - 2

• >> format short e; disp(pi);

• 3.1416e+00

• >> format long e; disp(pi);

• 3.141592653589793e+00

• >> format short g; disp(pi);

• 3.1416

• >> format long g; disp(pi);

• 3.14159265358979

Format Examples - 3

• >> format hex; disp(pi);

• 400921fb54442d18

• >> format bank; disp(pi);

• 3.14

• >> format +; disp(pi);

• +

• >> format rat; disp(pi);

• 355/113

Questions?