127
Matlab Fundamentals Dr. U D Dwivedi Assistant Professor (Electrical Engineering) Room No. 202, Rajiv Gandhi Institute of Petroleum Technology, Ratapur Chowk, Rae Bareli -229316 INDIA

Matlab Session 1 Introduction

Embed Size (px)

DESCRIPTION

mt

Citation preview

Page 1: Matlab Session 1 Introduction

Matlab Fundamentals

Dr. U D DwivediAssistant Professor (Electrical Engineering)

Room No. 202, Rajiv Gandhi Institute of Petroleum Technology, Ratapur Chowk,

Rae Bareli -229316 INDIA

Page 2: Matlab Session 1 Introduction

Getting Started

MATLAB fundamentals

Page 3: Matlab Session 1 Introduction

Index

About Matlab The basics Advanced operations Examples Advanced Graphics and Plotting

UD Dwivedi 3

Page 4: Matlab Session 1 Introduction

About Matlab

Page 5: Matlab Session 1 Introduction

What is Matlab

MATLAB® is a high-performance language for technical computing.

It integrates computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation.

UD Dwivedi 5

Page 6: Matlab Session 1 Introduction

Typical uses for Matlab

Math and computation Algorithm development Data acquisition Modeling, simulation, and prototyping Data analysis, exploration, and visualization Scientific and engineering graphics Application development, including graphical

user interface building

UD Dwivedi 6

Page 7: Matlab Session 1 Introduction

More about Matlab

MatLab is an interactive system whose basic data element is an array that does not require dimensioning.

The name MatLab stands for MATrix LABoratory MatLab features a family of add-on application-

specific solutions called toolboxes Toolboxes are comprehensive collections of MatLab

functions (M-files) that extend the MatLab environment to solve particular classes of problems

UD Dwivedi 7

Page 8: Matlab Session 1 Introduction

Construction

Core functionality: compiled C-routinesMost functionality is given as m-files, grouped into toolboxes

m-files contain source code, can be copied and altered m-files are platform independent (PC, Unix/Linux, MAC)

Simulation of dynamical systems is performed in Simulink

m-filesC-kernel

Sig. Proc

Simulink

Contr. Syst.

UD Dwivedi 8

Page 9: Matlab Session 1 Introduction

How to start and exit Matlab

On a Microsoft Windows platform, to start MATLAB, double-click the MATLAB shortcut icon on

your Windows desktop. After starting MATLAB, the MATLAB desktop opens

Note the >> is the matlab command prompt To end your MATLAB session, select Exit MATLAB

from the File menu in the desktop, or type quit in theCommand Window.

Note that nothing is saved when you exit, you will not be prompted to save

UD Dwivedi 9

Page 10: Matlab Session 1 Introduction

MATLAB Desktop

When you start MATLAB, the MATLAB desktop appears, containing tools (graphical user interfaces) for managing files, variables, and applications associated with MATLAB.

The first time MATLAB starts, the desktop appears as shown in the following illustration, although your Launch Pad may contain different entries.

UD Dwivedi 10

Page 11: Matlab Session 1 Introduction

Double Click on Icon Will open MATLAB

UD Dwivedi 11

Page 12: Matlab Session 1 Introduction

UD Dwivedi 12

Page 13: Matlab Session 1 Introduction

MATLAB Desktop, Cont.

When launching Matlab, it brings up a desktop with pull-down menus and various windows. These windows are:

Command Window: This is the main window for issuing commands and seeing results, and is what has been used in this class up to now.

Command History: An ordered list of all commands issued in the Command Window.

Current Directory: The files in the user directory currently available for use in the Command Window.

Workspace: a list of variables that have been used in the Command Window.

Launch Pad: a variety of packages that may be available with Matlab. We won't consider this window further.

UD Dwivedi 13

Page 14: Matlab Session 1 Introduction

CommandWindow

WorkingMemory

CommandHistory

UD Dwivedi 14

Page 15: Matlab Session 1 Introduction

Using Matlab help

Information about Matlab commands can be found either by issuing the help command, or by using the Help Window.

Just typing help brings up a list of packages containing functions and symbols:

>> help HELP topics: matlab/general - General purpose commands. matlab/elmat - Elementary matrices and matrix manipulation. matlab/elfun - Elementary math functions. matlab/specfun - Specialized math functions, etc. control\control - Control System Toolbox

Importantfor this course

UD Dwivedi 15

Page 16: Matlab Session 1 Introduction

Using Matlab help, Cont.

We could then look at the elfun package, which contains some elementary functions.

>> help elfunElementary math functions.Trigonometric.

sin - Sine.sinh - Hyperbolic sine.asin - Inverse sine.asinh - Inverse hyperbolic sine.cos - Cosine.cosh - Hyperbolic cosine.acos - Inverse cosine, etc.

UD Dwivedi 16

Page 17: Matlab Session 1 Introduction

Help Window

You can also use the Help Window, activated from the desktop. For example, let's look up information on the Matlab’s functions by category. (see next slide)

UD Dwivedi 17

Page 18: Matlab Session 1 Introduction

UD Dwivedi 18

Page 19: Matlab Session 1 Introduction

Help Window, Cont.

From the tabs in the Help Navigator, you can use an index, or search for keywords or explicit function names (e.g. atan) or concepts.

The description of the arctangent function is much more detailed than typing help atan, and includes graphs and examples in a nice layout.

You can also use the helpwin command to display the above help text inside the deskptop Help Window:

helpwin atan The command doc goes directly to the help text above,

without the extra step involved in helpwin to click on a link: doc atan

UD Dwivedi 19

Page 20: Matlab Session 1 Introduction

Running demos

Click Help -> Demos Then in new window, select Matlab, then

Desktop Environment Then select Desktop overview Run the demo (it will run in a browser)

UD Dwivedi 20

Page 21: Matlab Session 1 Introduction

Matlab Basics. What Matlab operates on?

MATLAB works with scalars, vectors and matrices.

A scalar is just a number, a 1x1 matrix. A vector is a list of numbers, effectively a

matrix, given as either a row or a column. In this sense, everything that MATLAB

operates on is a matrix. The best way to get started with MATLAB is

to learn how to handle matrices.

UD Dwivedi 21

Page 22: Matlab Session 1 Introduction

Uses of MATLAB? MATLAB is an interactive program for scientific and

engineering numeric calculation. It integrates computation, visualization, and

programming in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation.

Typical uses include: Math and computation Algorithm development Modeling, simulation, and prototyping Scientific and engineering graphics

UD Dwivedi 22

Page 23: Matlab Session 1 Introduction

Command Window

Command Window is used to enter variables and run functions and M-files.

Navigation within MATLAB is done using regular UNIX commands cd (change directory) pwd (show the path) ls (list contents of directory) whos (list of the variable stored in the memory)

UD Dwivedi 23

Page 24: Matlab Session 1 Introduction

Command WindowGetting help from the command window

help <function_name> (show the help document for a given function)

P.S.If you want to have an help for your own functions, you can write it at

the beginning of the function as :

% your own help. After this statement, the matlab file will start.

UD Dwivedi 24

Page 25: Matlab Session 1 Introduction

The basics

Page 26: Matlab Session 1 Introduction

The Basics

Variables and Arrays Array: A collection of data values organized into

rows and columns, and known by a single name.Row 1

Row 2

Row 3

Row 4

Col 1 Col 2 Col 3 Col 4 Col 5

arr(3,2)

UD Dwivedi 26

Page 27: Matlab Session 1 Introduction

Arrays The fundamental unit of data in MATLAB

Scalars are also treated as arrays by MATLAB (1 row and 1 column).

Row and column indices of an array start from 1.

Arrays can be classified as vectors andmatrices.

UD Dwivedi 27

Page 28: Matlab Session 1 Introduction

Vector: Array with one dimension

Matrix: Array with more than one dimension

Size of an array is specified by the number of rows and the number of columns, with the number of rows mentioned first (For example: n x m array).Total number of elements in an array is the product of the number of rows and the numberof columns.

UD Dwivedi 28

Page 29: Matlab Session 1 Introduction

Initializing Variables in Assignment Statements Arrays are constructed using brackets and

semicolons. All of the elements of an array are listed in row order.

The values in each row are listed from left to right and they are separated by blank spaces or commas.

The rows are separated by semicolons or new lines. The number of elements in every row of an array

must be the same.

UD Dwivedi 29

Page 30: Matlab Session 1 Introduction

Special Values pi: π value up to 15 significant digits i, j: sqrt(-1) Inf: infinity (such as division by 0) NaN: Not-a-Number (division of zero by zero) clock: current date and time in the form of a 6-

element row vector containing the year, month, day, hour, minute, and second

date: current date as a string such as 16-Feb-2004 eps: epsilon is the smallest difference between two

numbers ans: stores the result of an expression

UD Dwivedi 30

Page 31: Matlab Session 1 Introduction

Changing the data format>> value = 12.345678901234567;

format short → 12.3457format long → 12.34567890123457format short e → 1.2346e+001format long e → 1.234567890123457e+001format short g → 12.346format long g → 12.3456789012346format rat → 1000/81

UD Dwivedi 31

Page 32: Matlab Session 1 Introduction

The disp( array ) function>> disp( 'Hello' )Hello>> disp(5)

5>> disp( [ 'Bilkent ' 'University' ] )Bilkent University>> name = 'Alper';>> disp( [ 'Hello ' name ] )Hello Alper

UD Dwivedi 32

Page 33: Matlab Session 1 Introduction

The num2str() and int2str() functions>> d = [ num2str(16) '-Feb-' num2str(2004) ];>> disp(d)16-Feb-2004>> x = 23.11;>> disp( [ 'answer = ' num2str(x) ] )answer = 23.11>> disp( [ 'answer = ' int2str(x) ] )answer = 23

UD Dwivedi 33

Page 34: Matlab Session 1 Introduction

Calculator functions work as you'd expect: >>(1+4)*3 ans = 15 + and - are addition, / is division, * is multiplication, ^ is an

exponent.

You can assign variables from the matlab workspace.

Everything in matlab is a matrix. (If it's a scalar, it's actually a 1x1 matrix, and if it's a vector, it's an Nx1 or 1xN matrix.)

>>a = 3 a = 3

UD Dwivedi 34

Page 35: Matlab Session 1 Introduction

To create a vector is pretty similar. Each element is separated by spaces, the whole vector is in

square brackets: >>v = [1 3 6 8 9]

To create a vector of values going in even steps from one value to another value, you would use

>>b = 1:.5:10

To turn a row vector into a column vector, just put a ' at the end of it. (This is also how to get the transpose of a matrix.) To create a matrix, you could do something like:

c = [1 3 6; 2 7 9; 4 3 1] The semicolons indicate the end of a row. All rows have to be the

same length.

UD Dwivedi 35

Page 36: Matlab Session 1 Introduction

Dealing with Matrices

Once you have a matrix, you can refer to specific elements in it.

Matlab indexes matrices by row and column. c(3,1) is the element in the third row, 1st column, which is 4. c(2:3,1:2) gives you the elements in rows 2-3, and columns 1-2, so you get 2 74 3

as a result. c(1:3,2) gives you the elements in rows 1-3, and the second column, that is, the entire second column. You can shortcut this to: c(:,2)

You can get a whole row of a matrix with c(1,:)

UD Dwivedi 36

Page 37: Matlab Session 1 Introduction

Help and other tools

Typing "help" at the matlab prompt gives you a list of all the possible directories matlab can find commands in (which also tells you its "search path", or a list of the directories it is looking in for commands.)

Typing "help directoryname" gives you a list of the commands in that directory and a short description of them.

Typing "help commandname" gives you help on a specific command.

Typing "lookfor keyword" gives you a list of commands that use that keyword. ie, "lookfor integral" lists commands that deal with integrals. It's pretty slow, choose the word wisely. You can use control-c to stop searching when you think you've found what you need.

Typing "doc" starts up a web browser with the Matlab. This includes the entire reference manual for matlab, a whole lot of other information on using matlab, and a pointer to the Matlab Primer, a good introduction to using Matlab.

UD Dwivedi 37

Page 38: Matlab Session 1 Introduction

Some Useful Tools:

If you accidentally reassign a function name to a variable (ie, you try saying sum = 3 and then you get errors when you try to use the sum function because it doesn't know it's a function anymore), you can restore it to its normal state using "clear functionname". You can also use clear to get rid of all variable values with "clear all".

Warning: Never use any key word as the variable name

UD Dwivedi 38

Page 39: Matlab Session 1 Introduction

who will tell you all the variables you have currently defined.

whos will tell you the variables, their sizes, and some other info.

pi is a function of that returns the value of pi.

eps is a function that returns Matlab's smallest floating point

number.

UD Dwivedi 39

Page 40: Matlab Session 1 Introduction

format long and format short switch between the long and short display format of

numbers. Either way matlab uses the same number of digits for its calculations, but normally (format short) it will only display the first four digits after the decimal point.

Typing type Function name for any function in Matlab's search path lets you see

how that function is written.

Check difference between commands help and type

UD Dwivedi 40

Page 41: Matlab Session 1 Introduction

Plotting

The basic syntax to get a plot in matlab is plot(x1,y1)

(The x values always come before the y values, x1 and y1 represent variables that your data is stored in.) If you type a second plot command later, it will clear your first plot. If you type "hold on" it will hold the current plot so you can add plots on top of one another (until you reset it by typing "hold off".)

You can plot multiple values with plot(x1,y1,x2,y2)and you can specify the color and linetype of a plot as something like plot(x1,y1,'w*') to get white *'s for each data point

UD Dwivedi 41

Page 42: Matlab Session 1 Introduction

To split your plot into a bunch of smaller plots, you can use the subplot command to split it up into rows and columns.

subplot(r,c,n) will split the plot window into r rows and c columns of plots

and set the current plot to plot number n of those rows and columns.

You can add titles, labels, and legends to plots. title('This is a Title') xlabel('My X axis') ylabel('My Y axis') legend('First Thing Plotted','Second Thing Plotted')

UD Dwivedi 42

Page 43: Matlab Session 1 Introduction

0 10 20 30 40 50 60 70 80 90 1000

0.2

0.4

0.6

0.8

1Plot of random 100 values

Sampling instants

Random

Num

bers

0 10 20 30 40 50 60 70 80 90 1000

0.2

0.4

0.6

0.8

1Plot of random 100 values

Sampling instants

Random

Num

bers

0 10 20 30 40 50 60 70 80 90 1000

0.2

0.4

0.6

0.8

1Plot of random 100 values

Sampling instants

Random

Num

bers

hold on subplot(311) plot(x) title('Plot of random 100 values') xlabel('Sampling instants') ylabel('Random Numbers') subplot(312) plot(x,'*k') title('Plot of random 100 values') xlabel('Sampling instants') ylabel('Random Numbers') subplot(313) plot(x,'*r') title('Plot of random 100 values') xlabel('Sampling instants') ylabel('Random Numbers')

UD Dwivedi 43

Page 44: Matlab Session 1 Introduction

Printing, Saving, and Loading

Basic printing >>print –Pprintername

You can also save to a Postscript or Encapsulated Postscript file:

>>print -dps filename.ps >>prind -deps filename.eps

You can also save your plot as an m-file (matlab script) which should contain all the commands you need to recreate your plot later.

>>print -dmfile filename.m

UD Dwivedi 44

Page 45: Matlab Session 1 Introduction

You can save and load files as either text data or matlab's own data format. If you have a text file consisting of a bunch of columns of data separated by spaces or tabs, you can load it into matlab with

load filename.dat

The above command will give you a matrix called filename. Then you can reassign columns of that matrix, i.e.

col1 = filename(:,1);

UD Dwivedi 45

Page 46: Matlab Session 1 Introduction

When you save data using the command save filename.mat

matlab will save all of your variables and their values in its own format, so that when you load it using load filename.mat

you will have all of your variables already defined and names.

UD Dwivedi 46

Page 47: Matlab Session 1 Introduction

Writing Functions and Scripts

All matlab functions and scripts are plain text files that contain matlab commands. Matlab will treat any file that ends in .m as either a function or a script.

Scripts A script is just a list of commands to be run in some

order. Placing these commands in a file that ends in .mallows you to "run" the script by typing its name at the command line. You type the name of the script without the .m at the end.

UD Dwivedi 47

Page 48: Matlab Session 1 Introduction

Functions A function is capable of taking particular variables

(called arguments) and doing something specific to "return" some particular type of result. A function needs to start with the line function return-values = functionname(arguments)

so that matlab will recognize it as a function. Each function needs to have its own file, and the file has to have the same name as the function. If the first line of the function is function answer = myfun(arg1,arg2) answer = (arg1+arg2)./arg1

UD Dwivedi 48

Page 49: Matlab Session 1 Introduction

In this case the file must be named myfun.m.

The function has arg1 and arg2 to work with inside the function, and by the end of the function, anything that is supposed to be returned should have a value assigned to it.

This particular function is just one line long, and it returns answer, which is defined in terms of the two arguments arg1 and arg2.

UD Dwivedi 49

Page 50: Matlab Session 1 Introduction

Global Variables

When you define a variable at the matlab prompt, it is defined inside of matlab's "workspace." Running a script does not affect this, since a script is just a collection of commands, and they're actually run from the same workspace. If you define a variable in a script, it will stay defined in the workspace.

Functions, on the other hand, do not share the same workspace. A function won't know what a variable is unless the it gets the variable as an argument, or unless the variable is defined as a variable that is shared by the function and the matlab workspace, or a global variable.

To use a global variable, every place (function, script, or at the matlab prompt) that needs to share that variable must have a line near the top identifying it as a global variable, ie:

global phi;

Then when the variable is assigned a value in one of those places, it will have a value in all the places that begin with the global statement.

UD Dwivedi 50

Page 51: Matlab Session 1 Introduction

Debugging Functions

Matlab has an extensive debugger that allows you to examine what is going on inside a function when you encounter problems with it. If you type "help debug" at the matlab prompt, it will list all of the debugging commands available. Debugging commands.

dbstop - Set breakpoint. dbclear - Remove breakpoint. dbcont - Resume execution. dbdown - Change local workspace context. dbstack - List who called whom. dbstatus - List all breakpoints. dbstep - Execute one or more lines. dbtype - List M-file with line numbers. dbup - Change local workspace context. dbquit - Quit debug mode.

UD Dwivedi 51

Page 52: Matlab Session 1 Introduction

Advanced operations in Matlab

Page 53: Matlab Session 1 Introduction

Variables MATLAB does not require any type

declarations!

Real scalar: >> x=1 Complex scalar: >> x=1+2i Row vector: >> x=[1 2 3] Column vector: >> x=[1; 2; 3] 2x2 Matrix: >> x=[1 2; 3 4]You can define global variables by putting in front

the variable the statement global.

UD Dwivedi 53

Page 54: Matlab Session 1 Introduction

Complex numbers

Some useful operations on complex numbers:

Complex scalar >> x = 3+4j Real part of x >> real(x) ->3 Imaginary part of x >> imag(x) ->4 Magnitude of x >> abs(x) ->5 Angle of x >> angle(x) ->0.9273 Complex conjugate of x >> conj(x) ->3 - 4i

UD Dwivedi 54

Page 55: Matlab Session 1 Introduction

Generating vectors>> x=[a:step:b] Generate a vector that takes on the values a to b

in increments of step>> x=linspace(a,b,n) generates a row vector x of n points linearly

spaced between a and b>> x=logspace(a,b,20) generates a logarithmically spaced vector x of n

points between 10^a and 10^b.

UD Dwivedi 55

Page 56: Matlab Session 1 Introduction

Generating matrices Matrix building functions:

>> A=zeros(m,n) returns an m-by-n matrix of zeros

>> A=ones(m,n) returns an m-by-n matrix of 1s

>> A=eye(m,n) returns an m-by-n matrix with 1's on the diagonal

and 0's elsewhere

UD Dwivedi 56

Page 57: Matlab Session 1 Introduction

Generating random matrices>> A=rand(m,n)

returns an m-by-n matrix of random numbers whose elements are uniformly distributed in the interval (0,1)

>> A=randn(m,n) returns an m-by-n matrix of random numbers whose

elements are normally distributed with mean 0 and variance 1

>> A=randint(m,n,range) generates an m-by-n integer matrix. The entries are

uniformly distributed and independently chosen from the range: [0, range-1] if range is a positive integer [range+1, 0] if range is a negative integer

UD Dwivedi 57

Page 58: Matlab Session 1 Introduction

Accessing matrix elements Elements of a matrix are accessed by specifying the row

and column>> A=[1 2 3; 4 5 6; 7 8 9];>> x=A(1,3)

Returns the element in the first row and third column>> y=A(2,:)

Returns the entire second row [4 5 6] “:” means “take all the entries in the column”

>> B=A(1:2,1:3) Returns a submatrix of A consisting of rows 1 and 2

and all three columns [1 2 3; 4 5 6]

UD Dwivedi 58

Page 59: Matlab Session 1 Introduction

Arithmetic matrix operation

The basic arithmetic operations on matrices are:

+ addition - subtraction * multiplication / division ^ power ’ conjugate transpose

UD Dwivedi 59

Page 60: Matlab Session 1 Introduction

element-by-element operations

MATLAB provides element-by-element operations by prepending a ‘.’ before the operator

.* multiplication ./ division .^ power .’ transpose (unconjugated)

UD Dwivedi 60

Page 61: Matlab Session 1 Introduction

Relational operations

MATLAB defines the following relational operations:

< less than <= less than or equal to > greater than >= greater than or equal to == equal to ~= not equal to

UD Dwivedi 61

Page 62: Matlab Session 1 Introduction

Logical operations

MATLAB defines the following logical operations:

& and | or ~ not

UD Dwivedi 62

Page 63: Matlab Session 1 Introduction

Math functions

The following functions operate element-wise when applied to a matrix:

sin cos tanasin acos atansinh cosh tanhexp log(natural log) log10abs sqrt sign

UD Dwivedi 63

Page 64: Matlab Session 1 Introduction

M-files MATLAB is an interpretive language M-files are text files containing MATLAB scripts Scripts are sequences of commands typed by an

editor The instructions are executed by typing the file

name in the command window at the MATLAB prompt

All the variables used in the m-file are placed in MATLAB’s workspace that contains all the variables defined in the MATLAB session

UD Dwivedi 64

Page 65: Matlab Session 1 Introduction

M-files Debug

In Matlab you can debug your m-file, like in other programming languages

To do it, you need to open your matlab file from the window command.

Afterwards, you can operate exactly like for other languages and you can use usual command as:

step instep outbreak pointetc. etc

UD Dwivedi 65

Page 66: Matlab Session 1 Introduction

Flow control

If statements

if expressionstatements

elsestatements

end

Example

If n<0a=a-1;

elsea=a+1;

end

UD Dwivedi 66

Page 67: Matlab Session 1 Introduction

Flow control

For Repeats a group of statements a fixed,

predetermined number of times.

a=0;for n = 1:10

a=a+1;end

UD Dwivedi 67

Page 68: Matlab Session 1 Introduction

Function in MatlabTo simplify your matlab file structure, you

can use functions. An example of how to use matlab functions is the following:

Main Matlab Programa = 10; b = 20;c = my_sum(a,b);

Function declaration:function y = my_sum(m,n)y = m + n ;return(y) // give the file name of function same as function name e.g. my_sum.m

UD Dwivedi 68

Page 69: Matlab Session 1 Introduction

Entering Matrices

We can enter matrices into MATLAB in several different ways:

1. Enter an explicit list of elements.2. Load matrices from external data files.3. Generate matrices using built-in functions.4. Create matrices with your own functions in M-files.

We have only to follow a few basic conventions:

1. Separate the elements of a row with blanks or commas.2. Use a semicolon, ; , to indicate the end of each row.3. Surround the entire list of elements with square brackets, [ ].

UD Dwivedi 69

Page 70: Matlab Session 1 Introduction

Matlab Statements and Variables

MATLAB is an expression language. It interprets and evaluates expressions typed in the command window at the keyboard.

You are allowed to assign a name to an expression.

Statements are usually in the form ofvariable = expression,e.g. A = magic(4)

UD Dwivedi 70

Page 71: Matlab Session 1 Introduction

Interactive Calculations Matlab is interactive, no need to declare variables >> 2+3*4/2

>> a=5e-3; b=1; a+b

Most elementary functions and constants are already defined

>> cos(pi)

>> abs(1+i)

>> sin(pi)

Last call gives answer 1.2246e-016 !?

UD Dwivedi 71

Page 72: Matlab Session 1 Introduction

IEEE Standard for double precision numbers

Round-off: eps = 2-52

Underflow: realmin = 2-1022

Overflow: realmax = (2-eps) ·21023

Floating point numbers in Matlab

s e f1 2 12 13 64

UD Dwivedi 72

Page 73: Matlab Session 1 Introduction

Variable and Memory ManagementMatlab uses double precision (approx. 16 significant digits)>> format long>> format compact

All variables are shown with>> who

>> whosVariables can be stored on file>> save filename>> clear>> load filename

UD Dwivedi 73

Page 74: Matlab Session 1 Introduction

The Help System Search for appropriate function >> lookfor keyword

Rapid help with syntax and function definition >> help function

An advanced hyperlinked help system is launched by

>> helpdesk

Complete manuals as PDF files

UD Dwivedi 74

Page 75: Matlab Session 1 Introduction

Vectors and Matrices

Vectors (arrays) are defined as >> v = [1, 2, 4, 5]

>> w = [1; 2; 4; 5]

Matrices (2D arrays) defined similarly >> A = [1,2,3;4,-5,6;5,-6,7]

UD Dwivedi 75

Page 76: Matlab Session 1 Introduction

Matrix Operators All common operators are overloaded >> v + 2

Common operators are available >> B = A’ >> A*B >> A+B Note: Matlab is case-sensitive

A and a are two different variables• Transponate conjugates complex entries;

avoided by• >> B=A.’

UD Dwivedi 76

Page 77: Matlab Session 1 Introduction

Indexing MatricesIndexing using parentheses>> A(2,3)

Index submatrices using vectorsof row and column indices >> A([2 3],[1 2])

Ordering of indices is important!>> B=A([3 2],[2 1])>> B=[A(3,2),A(3,1);A(2,2);A(2,1)]

UD Dwivedi 77

Page 78: Matlab Session 1 Introduction

Indexing MatricesIndex complete row or column using the colon operator >> A(1,:)

Can also add limit index range>> A(1:2,:)

>> A([1 2],:)

General notation for colon operator>> v=1:5

>> w=1:2:5

UD Dwivedi 78

Page 79: Matlab Session 1 Introduction

Matrix Functions Many elementary matrices predefined >> help elmat; >> I=eye(3) Elementary functions are often overloaded >> help elmat >> sin(A) Specialized matrix functions and operators >> As=sqrtm(A) >> As^2 >> A.*A Note: in general,”Dot Operator” ”.<operator>” is

elementwise operation

UD Dwivedi 79

Page 80: Matlab Session 1 Introduction

Numerical Linear Algebra Basic numerical linear algebra >> z=[1;2;3]; x=inv(A)*z >> x=A\z

Many standard functions predefined >> det(A) >> rank(A) >> eig(A)

The number of input/output arguments can often be varied

>> [V,D]=eig(A)

UD Dwivedi 80

Page 81: Matlab Session 1 Introduction

Examples

Page 82: Matlab Session 1 Introduction

Syntax - symbols and punctuation

Try these examples

Input Output Comments

2 + 37-534*2121234/57862^5

ans = 5ans = 2ans = 7208ans = 0.2173ans = 32

Arithmetic works as expected. Note that the result is given the name "ans" each time.

a = sqrt(2) a = 1.4142 You can choose your own names for things.

UD Dwivedi 82

Page 83: Matlab Session 1 Introduction

b = a, pi, 2 + 3i

b = 1.4142ans = 3.1416ans = 2.0000 + 3.0000i

You can use commas to put more than one command on a line. Pi, i, and j are contants.

c = sin(pi)eps

c = 1.2246e-016ans = 2.2204e-016

"eps" is the current limit of precision. Anything smaller than eps is probably zero. Note that Matlab understands (and expects you to understand!) scientific notation.

d = [1 2 3 4 5 6 7 8 9]e = [1:9]f = 1:9

d = 1 2 3 4 5 6 7 8 9e = 1 2 3 4 5 6 7 8 9 f = 1 2 3 4 5 6 7 8 9

"d", "e", and "f" are all vectors. They are equal. Note the use of the ":" operator - it counts (by ones) from one number to the next.

g = 0:2:10f(3)f(2:7)f(:)

g = 0 2 4 6 8 10ans = 3ans = 2 3 4 5 6 71 2 3 4 5 6 7 8 9

More uses of the colon. Note that you can use it to get slices of a vector (or matrix, or cube, etc), or get the whole thing.

UD Dwivedi 83

Page 84: Matlab Session 1 Introduction

h = [1 2 3];h'

(nothing)ans = 1

23

A semi-colon ";" will prevent the output from being displayed. A single quote " ' " computes the transpose of a matrix, or in this case, switches between row and column vectors.

h * h'h .* hh + h

ans = 14ans = 1 4 9ans = 2 6 8

Operations on vectors. * is matrix multiplication, and so the dimensions must line up correctly. " .* " is entry-by-entry multiplication.

g = [ 1 2 3; 4 5 6; 7 8 9]

g = 1 2 34 5 67 8 9

Entering a matrix.

g(2,3)g(3,:)g(2,3) = 4

ans = 6ans = 7 8 9g = 1 2 3

4 5 47 8 9

Accessing matrix elements.Note use of ":" to access an entire row.

UD Dwivedi 84

Page 85: Matlab Session 1 Introduction

g^2

g .^ 2

ans = 30 36 4266 81 96

102 126 150ans = 1 4 9

16 25 3649 64 81

The first multiplies the matrix by itself. The second squares each entry in the matrix.

Input Output Comments

UD Dwivedi 85

Page 86: Matlab Session 1 Introduction

Working with Scalars

A scalar is just a number Matlab stores them as 1x1 matrices All operations involving a scalar and a matrix

are entry-by-entry, with on exception: The power (“^”) operator

UD Dwivedi 86

Page 87: Matlab Session 1 Introduction

Working with Scalars, Cont.

Try these examplesInput Output Comments

b=2 b=2 Define b to be a scalar.

a + bans = 3 4

5 6 Addition works entry-by-entry.

a * bans = 2 4

6 8 So does multiplication.

a ^ bans = 7 10

15 22 This is matrix power - a*a

a .^ bans = 1 4

9 16 Entry-by-entry power.

UD Dwivedi 87

Page 88: Matlab Session 1 Introduction

Vectors

A vector is just a matrix with only one row or column

Input Output Commentsv = [1 2 3]u = [3 2 1]

v = 1 2 3u = 3 2 1 Define a pair of vectors.

v * u Error The dimensions don't agree.

v * u' ans = 10 Taking the transpose works.

dot(v,u) ans = 10 The dot product is the same thing.

cross(v,u) ans = -4 8 -4 The cross product works only for 3-d vectors

UD Dwivedi 88

Page 89: Matlab Session 1 Introduction

Matrix Operations Synopsis

+, -, *, and / are defined in an intuitive manner for matrices

“ ‘ “ (transposition) turns a row vector into a column vector

“.*” (dot-star) will multiply entry-by-entry “*” will do matrix multiplication. More

precisely, ∑=

=n

kjkBkiAjiC

1),(*),(),(

UD Dwivedi 89

Page 90: Matlab Session 1 Introduction

Transposing Matrices

The special character “ ‘ “ (prime or apostrophe) denotes the transposition of the matrix. The statements

A = [1 2 3; 4 5 6; 7 8 0]; B = A';Result in

A = B =1 2 3 1 4 74 5 6 2 5 87 8 0 3 6 0

UD Dwivedi 90

Page 91: Matlab Session 1 Introduction

Matrix-Vector Product

Matrix-Vector Product is a special case of general matrix-matrix product.

Let usA = [1 2 3; 4 5 6; 7 8 0]; x = [-1 0 2]’;

b = A*x results in the outputb =

58-7

UD Dwivedi 91

Page 92: Matlab Session 1 Introduction

Using Powers with Matrices

A^p raises A to p-th power and is defined if A is a square matrix and p is a scalar.

If p is an integer greater than 1, the power is computed by repeated multiplication.

For other values of p, the calculation involves eigenvalues (D) and eigenvectors (V):if [V,D] = eig(A), thenthen A^p = V*D.^p/V

X^P, where both X and P a matrices, is an error.

UD Dwivedi 92

Page 93: Matlab Session 1 Introduction

Matrix built-in operations

Input Output Comments

k = [16 2 3;5 11 10;9 7 6]

k = 16 2 35 11 109 7 6

Define a matrix.

rank(k) ans = 3 The rank.det(k) ans = -136 The determinant.

For more, type help matfun

UD Dwivedi 93

Page 94: Matlab Session 1 Introduction

Matrix built-in operations, Cont.Input Output Comments

inv(k)ans = 0.0294 -0.0662 0.0956

-0.4412 -0.5074 1.06620.4706 0.6912 -1.2206

Inverse of the matrix

[vec,val] = eig(k)

vec = -0.4712 -0.4975 -0.0621-0.6884 0.8282 -0.6379-0.5514 0.2581 0.7676

val = 22.4319 0 00 11.1136 00 0 -0.5455

Eigenvectors and eigenvalues of the matrix.The columns of "vec" are the eigenvectors, and the diagonal entries of "val" are the eigenvaules

UD Dwivedi 94

Page 95: Matlab Session 1 Introduction

Matrix built-in constructions

For more, type help func_nameInput Output Commentsrand(2)

rand(2,3)

ans = 0.9501 0.6068 0.2311 0.4860

ans = 0.8913 0.4565 0.82140.7621 0.0185 0.4447

Generates a matrix with entries randomly distributed between 0 and 1

zeros(2)

ones(2)

ans = 0 00 0

ans = 1 11 1

Generates a 2x2 matrix with all zero (or all ones) entries.

eye(2) ans = 1 00 1 Identity matrix I.

hilb(3) ans = 1.0000 0.5000 0.33330.5000 0.3333 0.25000.3333 0.2500 0.2000

3x3 Hilbert matrix.

UD Dwivedi 95

Page 96: Matlab Session 1 Introduction

Deleting rows and columns You can delete rows and columns from a matrix

using just a pair of square brackets. Start with X = [1 2 3; 4 5 6; 7 8 0]

Then, to delete the second column of X, useX(:,2) = [ ];

Thus, X = [ 1 34 67 0 ]

If you delete a single element from a matrix, the result isn't a matrix anymore.

So, expressions likeX(1,2) = [ ], result in an error.

UD Dwivedi 96

Page 97: Matlab Session 1 Introduction

Input Output

[a, a, a] ans = 1 2 1 2 1 23 4 3 4 3 4

[a; a; a] ans = 1 23 41 23 41 23 4

[a, zeros(2); zeros(2), a'] ans = 1 2 0 03 4 0 00 0 1 30 0 2 4

Concatenating Matrices, Cont.a=[1 2;3 4]

UD Dwivedi 97

Page 98: Matlab Session 1 Introduction

M - files You can create your own matrices using M-files,

which are text files containing MATLAB code. Use the MATLAB Editor or another text editor to

create a file containing the same statements you would type at the MATLAB command line. Save the file under a name that ends in .m.

For example, create a file containing these two lines.A = [ 16.0 3.0 2.0 13.0; 5.0 10.0 11.0 8.0; …

9.0 6.0 7.0 12.0; 4.0 15.0 14.0 1.0 ]; Store the file under the name magik.m. Then the

statement magik reads the file and creates variable, A, containing our example matrix.

UD Dwivedi 98

Page 99: Matlab Session 1 Introduction

Solving System of Linear Equations

One of the main uses of matrices is in representing systems of linear equations.

If a is a matrix containing the coefficients of a system of linear equations, x is a column vector containing the "unknowns," and b is the column vector of "right-hand sides," the constant terms, then the matrix equation

a x =b

represents the system of equations

UD Dwivedi 99

Page 100: Matlab Session 1 Introduction

Solving equations, Cont.

MATLAB uses the division terminologyfamiliar in the scalar case to describe the solution of a general system of simultaneous equations.

The two division symbols, slash, /, and backslash, \, are used for the two situations where the unknown matrix appears on the leftor right of the coefficient matrix.

UD Dwivedi 100

Page 101: Matlab Session 1 Introduction

Solving equations, Cont. X = A\B denotes the solution to the matrix equation

AX = B. X = B/A denotes the solution to the matrix equation

XA = B. The dimension compatibility conditions for X = A\B

require the two matrices A and B to have the same number of rows.

The solution X then has the same number of columns as B and its row dimension is equal to the column dimension of A.

For X = B/A, the roles of rows and columns are interchanged.

UD Dwivedi 101

Page 102: Matlab Session 1 Introduction

Solving equations, Cont.

In practice, linear equations of the form AX = Boccur more frequently than those of the form XA = B. Consequently, backslash is used far more frequently than slash.

The coefficient matrix A need not be square. If A is m-by-n, there are three cases.

1. m = n, Square system. Seek an exact solution.2. m > n, Overdetermined system. Find a least squares

solution.3. m < n, Underdetermined system. Find a basic solution

with at most m nonzero components.

UD Dwivedi 102

Page 103: Matlab Session 1 Introduction

Solving equations, an Example

To solve the equation a x =b in matlab simply type x = a \ b

Which reads “x equals a-inverse times b” Try it with

a = [1 2 3; 4 5 6; 7 8 10]; b = [1 1 1]';

You should get x =

-1 1 0

UD Dwivedi 103

Page 104: Matlab Session 1 Introduction

Solving equations, an Example, Cont.

To verify this assertion, try this:a*x, a*x - b, epsThe results are:ans = 1 1 1ans = 1.0e-015 *

-0.1110-0.6661-0.2220

ans = 2.2204e-016 Notice that a*x - b is very close to eps - which

means that it is as close to zero as possible.

UD Dwivedi 104

Page 105: Matlab Session 1 Introduction

Solving equations, an Example, Cont.

If there is no solution, a "least-squares" solution is provided (a*x - b is as small as possible). Enter a(3,3) = 9; b = [1 1 0]';(which makes the matrix singular and changes b) and try to solve the equation again.

Notice that the solution is quite inaccurate.

UD Dwivedi 105

Page 106: Matlab Session 1 Introduction

Saving and loading matrices

When you exit matlab you will not be prompted to save

You can turn on logging diary '~/session.txt‘

this will save output and input together and therefore can not be used as a script

You may just want to save one or more matrices save x.value x -ascii

UD Dwivedi 106

Page 107: Matlab Session 1 Introduction

Saving and loading matrices

To save all variables in a file named “mysession.mat” in a reloadable format save mysession

To restore the session, use load mysession

The saved files are in text format and can be viewed using any text editor

UD Dwivedi 107

Page 108: Matlab Session 1 Introduction

Advanced Graphics and Plotting

Elementary Plotting Functions,

Page 109: Matlab Session 1 Introduction

Creating a plot

>> plot(x,y) produces a graph of y versus x, where x and y are

two vectors

x=linspace(0,2*pi,100);plot(x,sin(x));

0 1 2 3 4 5 6 7-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

x

Sin

e of

x

UD Dwivedi 109

Page 110: Matlab Session 1 Introduction

Line styles and colors

It is possible to specify color, line styles, and markerswhen you plot your data using the plot command

plot(x,y,'color_style_marker') color_style_marker is a string containing from one to four

characters constructed from a color, a line style, and a marker type: Color strings: 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'. These

correspond to cyan, magenta, yellow, red, green, blue, white, and black

Linestyle strings are '-' for solid, '--' for dashed, ':' for dotted, '-.' for dash-dot, and 'none' for no line

The marker types are '+', 'o', '*' and 'x'

UD Dwivedi 110

Page 111: Matlab Session 1 Introduction

Axis lables and titles

xlabel('string') labels the x-axis of the current axes

ylabel('string') labels the y-axis of the current axes

Title(‘string’) add a title to a graph at the MATLAB command

prompt or from an M-file

UD Dwivedi 111

Page 112: Matlab Session 1 Introduction

The figure function

MATLAB directs graphics output to a figure window Graphics functions automatically create new figure

windows if none currently exist>>figure creates a new window and makes it the current figure>>figure(h) make an existing figure current by passing its handle

(the number indicated in the window title bar), as an argument to figure

>>clf Clear current figure window

UD Dwivedi 112

Page 113: Matlab Session 1 Introduction

Adding plots

Setting hold to on, MATLAB doesn’t remove the existing graph and adds the new data to the current graph

x=linspace(0,2*pi,100);plot(x,sin(x));hold on;plot(x,cos(x));xlabel('x');ylabel('Sine of x'); 0 1 2 3 4 5 6 7

-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

x

Sin

e of

x

UD Dwivedi 113

Page 114: Matlab Session 1 Introduction

Adding plots

With more graphics functionalities:

x=linspace(0,2*pi,100);plot(x,sin(x),’-ob’);hold on; grid on;plot(x,cos(x),’->r’);xlabel('x');ylabel('Sine of x');legend('sin(x)','cos(x)',3)

UD Dwivedi 114

Page 115: Matlab Session 1 Introduction

Basic plotting commands

Plot Graph 2-D data with linear scales for both axes

Loglog Graph with logarithmic scales for both axes

Semilogx Graph with a logarithmic scale for the x-axis and a

linear scale for the y-axis Semilogy Graph with a logarithmic scale for the y-axis and a

linear scale for the x-axis

UD Dwivedi 115

Page 116: Matlab Session 1 Introduction

Specialized plots

bar(x,Y) draws a bar for each element in Y at locations

specified in x, where x is a monotonically increasing vector defining the x-axis intervals for the vertical bars

>> bar((1:1:10),(1:1:10))

UD Dwivedi 116

Page 117: Matlab Session 1 Introduction

Specialized plots

Stem displays data as lines (stems) terminated with a

marker symbol at each data value

x=linspace(0,2*pi,10);stem(x,sin(x));

UD Dwivedi 117

Page 118: Matlab Session 1 Introduction

Specialized plots

Stairs Stairstep plots are useful for drawing time-history

plots of digitally sampled data systems

x=linspace(0,2*pi,20);stairs(x,sin(x));

UD Dwivedi 118

Page 119: Matlab Session 1 Introduction

Graphics Visualization of vector data is available >> x=-pi:0.1:pi; y=sin(x);

>> plot(x,y)

>> plot(x,y,’s-’)

>> xlabel(’x’); ylabel(’y=sin(x)’);

Can change plot properties in Figure menu, or via ”handle”

>> h=plot(x,y); set(h, ’LineWidth’, 4);

Many other plot functions available >> v=1:4; pie(v)

UD Dwivedi 119

Page 120: Matlab Session 1 Introduction

GraphicsThree-dimensional graphics>> A = zeros(32);>> A(14:16,14:16) = ones(3);>> F=abs(fft2(A));>> mesh(F)>> rotate3d onSeveral other plot functions available>> surfl(F)Can change lightning and material properties>> cameramenu>> material metal

UD Dwivedi 120

Page 121: Matlab Session 1 Introduction

Graphics

Bitmap images can also be visualized >> load mandrill

>> image(X); colormap(map)

>> axis image off

UD Dwivedi 121

Page 122: Matlab Session 1 Introduction

UD Dwivedi 122

Page 123: Matlab Session 1 Introduction

MATLAB graphics

» a = 1:100;» b = 100:0.01:101;» c = 101:-1:1;» d = [a b c];» e = [d d d d d];» plot(e)

0 200 400 600 800 1000 1200 1400 16000

20

40

60

80

100

120

The plot function is very powerful for plotting all sorts of variables.See “help plot” for more details and see the examples in the MATLAB online tutorial

UD Dwivedi 123

Page 124: Matlab Session 1 Introduction

MATLAB graphics

» a = 0:0.1:10;

» subplot(3,1,1); plot(sin(a))

» r1 = rand(1,length(a))*0.2;» subplot(3,1,2); plot(sin(a)+r1)

» r2 = rand(1,length(a))*0.8;» subplot(3,1,3); plot(sin(a)+r2)

UD Dwivedi 124

Page 125: Matlab Session 1 Introduction

MATLAB graphics (ctd)

» x = rand(1,100);» y = rand(1,100);» plot(x,y,'*')

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

UD Dwivedi 125

Page 126: Matlab Session 1 Introduction

MATLAB images

» load earth» whosName Size Bytes Class

X 257x250 514000 double arraymap 64x3 1536 double array

Grand total is 64442 elements using 515536 bytes

» image(X); colormap(map);

UD Dwivedi 126

Page 127: Matlab Session 1 Introduction

Thank You!