0% found this document useful (0 votes)
42 views127 pages

Matlab

Uploaded by

dipa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views127 pages

Matlab

Uploaded by

dipa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 127

Matlab Fundamentals

 
 
 
 
Getting Started

MATLAB fundamentals
Index

 About Matlab
 The basics
 Advanced operations
 Examples
 Advanced Graphics and Plotting

3
About Matlab
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.

5
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

6
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

7
Construction

Core functionality: compiled C-routines


Most 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
Sig. Proc Contr. Syst.

Simulink
C-kernel m-files
8
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 the
Command Window.
 Note that nothing is saved when you exit, you will
not be prompted to save
9
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.
10
Double Click on Icon Will open MATLAB

11
12
MATLAB Desktop, Cont.
When launching Matlab, version 6.5/7 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.

13
Working Command
Memory Window

Command
History

14
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/lang - Programming language constructs.
 matlab/elmat - Elementary matrices and matrix manipulation.
 matlab/elfun - Elementary math functions.
 matlab/specfun - Specialized math functions, etc.

15
Using Matlab help, Cont.

 We could then look at the elfun package,


which contains some elementary functions.
 >> help elfun
  Elementary math functions.
Trigonometric.
sin - Sine.
sinh - Hyperbolic sine.
asin - Inverse sine.
asinh - Inverse hyperbolic sine.
cos - Cosine.
cosh - Hyperbolic cosine.
acos - Inverse cosine, etc.

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

17
18
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

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

20
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.

21
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

22
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)
23
Command Window
Getting 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.

24
The basics
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
arr(3,2)
Row 4

Col 1 Col 2 Col 3 Col 4 Col 5

26
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 and
matrices.

27
 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 number
of columns.
28
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.

29
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

30
Changing the data format
>> value = 12.345678901234567;
format short  12.3457
format long  12.34567890123457
format short e  1.2346e+001
format long e  1.234567890123457e+001
format short g  12.346
format long g  12.3456789012346
format rat  1000/81

31
The disp( array ) function
>> disp( 'Hello' )
Hello
>> disp(5)
5
>> disp( [ 'Bilkent ' 'University' ] )
Bilkent University
>> name = 'Alper';
>> disp( [ 'Hello ' name ] )
Hello Alper

32
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

33
 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

34
 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.

35
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
27
43
 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,:)

36
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.

37
Some Useful Tools:
Warning: Never use any key word as the variable name

 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".

38
 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.

39
 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

40
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

41
 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')

42
Plot of random 100 values
1

0.8

0.6

RandomNumbers
0.4

 hold on 0.2
 subplot(311) 0
 plot(x) 0 10 20 30 40 50 60 70 80 90 100
Sampling instants
 title('Plot of random 100 values')
Plot of random 100 values
 xlabel('Sampling instants') 1
 ylabel('Random Numbers')
0.8
 subplot(312)
 plot(x,'*k') 0.6
RandomNumbers

 title('Plot of random 100 values')


0.4
 xlabel('Sampling instants')
 ylabel('Random Numbers') 0.2
 subplot(313) 0
 plot(x,'*r') 0 10 20 30 40 50 60 70 80 90 100
Sampling instants
 title('Plot of random 100 values')
Plot of random 100 values
 xlabel('Sampling instants') 1
 ylabel('Random Numbers')
 0.8

0.6
RandomNumbers

0.4

0.2

0
0 10 20 30 40 50 60 70 80 90 100
Sampling instants

43
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

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

45
 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.

46
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 .m
allows 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.

47
 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

48
 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.

49
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.

50
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.

51
Advanced operations in
Matlab
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.

53
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

54
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.

55
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

56
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

57
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]

58
Arithmetic matrix operation

 The basic arithmetic operations on matrices


are:

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

59
element-by-element operations

 MATLAB provides element-by-element


operations by prepending a ‘.’ before the
operator

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

60
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

61
Logical operations

 MATLAB defines the following logical


operations:

 & and
 | or
 ~ not

62
Math functions

 The following functions operate element-wise


when applied to a matrix:

sin cos tan


asin acos atan
sinh cosh tanh
exp log(natural log) log10
abs sqrt sign

63
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

64
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 in
step out
break point
etc. etc

65
Flow control
 Example
 If statements
If n<0
if expression a=a-1;
statements else
else a=a+1;
statements end
end

66
Flow control

 For
 Repeats a group of statements a fixed,
predetermined number of times.

a=0;
for n = 1:10
a=a+1;
end

67
Function in Matlab
To simplify your matlab file structure, you
can use functions. An example of how to
use matlab functions is the following:
Main Matlab Program
a = 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

68
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, [ ].

69
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 of
variable = expression,
e.g. A = magic(4)

70
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 !?

71
Floating point numbers in Matlab
 IEEE Standard for double precision numbers

s e f
1 2 12 13 64

 Round-off:eps = 2-52
 Underflow: realmin = 2-1022
 Overflow: realmax = (2-eps) ·21023
Variable and Memory Management
Matlab uses double precision (approx. 16
significant digits)
>> format long
>> format compact

All variables are shown with

>> who

>> whos
Variables can be stored on file
>> save filename
>> clear
>> load filename

73
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
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]

75
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.’

76
Indexing Matrices
Indexing
using parentheses
>> A(2,3)

Index submatrices using vectors


of 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)]

77
Indexing Matrices
Index 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

78
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

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

80
Examples
Syntax - symbols and punctuation

 Try these examples


Input Output Comments

2+3 ans = 5
7-5 ans = 2
Arithmetic works as expected.
34*212 ans = 7208
1234/5786 ans = 0.2173 Note that the result is given the name "ans" each time.
2^5 ans = 32
a = sqrt(2) a = 1.4142 You can choose your own names for things.

82
b = 1.4142
You can use commas to put more
ans = 3.1416
b = a, pi, 2 + 3i than one command on a line. Pi, i,
ans = 2.0000 +
and j are contants.
3.0000i
"eps" is the current limit of
precision. Anything smaller than
c = sin(pi) c = 1.2246e-016 eps is probably zero. Note that
eps ans = 2.2204e-016 Matlab understands (and expects
you to understand!) scientific
notation.
"d", "e", and "f" are all vectors.
d=
d=123456789 They are equal. Note the use of
[1 2 3 4 5 6 7 8 9]
e=123456789 the ":" operator - it counts (by
e = [1:9]
f=123456789 ones) from one number to the
f = 1:9
next.
g = 0:2:10 g = 0 2 4 6 8 10 More uses of the colon. Note that
f(3) ans = 3 you can use it to get slices of a
f(2:7) ans = 2 3 4 5 6 7 vector (or matrix, or cube, etc), or
f(:) 123456789 get the whole thing.

83
A semi-colon ";" will prevent the output
h = [1 2 3]; (nothing)
from being displayed. A single quote " '
h' ans = 1
" computes the transpose of a matrix,
        2
or in this case, switches between row
        3
and column vectors.

Operations on vectors. * is matrix


h * h' ans = 14
multiplication, and so the dimensions
h .* h ans = 1 4 9
must line up correctly.
h + h ans = 2 4 6
" .* " is entry-by-entry multiplication.

g = 1 2 3
g = [ 1 2 3;
    4 5 6 Entering a matrix.
4 5 6; 7 8 9]
    7 8 9
g(2,3) ans = 6
g(3,:) ans = 7 8 9
Accessing matrix elements.
g(2,3) = 4 g = 1 2 3
Note use of ":" to access an entire row.
      4 5 4
      7 8 9

84
Input Output Comments

ans =  30  36  42
g^2
       66  81  96
 
      102 126 150 The first multiplies the matrix by itself.
 
ans =  1  4  9 The second squares each entry in the
g .^ 2
      16 25 36 matrix.
 
      49 64 81
 

85
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

86
Working with Scalars, Cont.

 Try these examples


Input Output Comments

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


ans = 3 4
a + b Addition works entry-by-entry.
      5 6
ans = 2 4
a * b So does multiplication.
      6 8
ans = 7 10
a ^ b This is matrix power - a*a
      15 22
ans = 1 4
a .^ b Entry-by-entry power.
      9 16

87
Vectors

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


column
Input Output Comments
v = [1 2 3] v = 1 2 3
Define a pair of vectors.
u = [3 2 1] u = 3 2 1

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.

The cross product works only for 3-d


cross(v,u) ans = -4 8 -4
vectors

88
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
C (i, j )   A(i, k ) * B(k , j )
k 1

89
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 7
4 5 6 2 5 8
7 8 0 3 6 0

90
Matrix-Vector Product
 Matrix-Vector Product is a special case of
general matrix-matrix product.
 Let us
A = [1 2 3; 4 5 6; 7 8 0]; x = [-1 0 2]’;
 b = A*x results in the output
b=
5
8
-7

91
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), then
then A^p = V*D.^p/V
 X^P, where both X and P a matrices, is an error.

92
Matrix built-in operations

 For more, type help matfun

Input Output Comments


k = [16  2  3; k = 16  2  3
     5 11 10;      5 11 10 Define a matrix.
     9  7  6]      9  7  6
rank(k) ans = 3 The rank.
det(k) ans = -136 The determinant.

93
Matrix built-in operations, Cont.
Input Output Comments
ans =  0.0294 -0.0662  0.0956
Inverse of the
inv(k)       -0.4412 -0.5074  1.0662
matrix
       0.4706  0.6912 -1.2206
Eigenvectors
and eigenvalues
vec = -0.4712 -0.4975 -0.0621 of the matrix.
      -0.6884  0.8282 -0.6379 The columns of
[vec,val] =       -0.5514  0.2581  0.7676 "vec" are the
eig(k) val = 22.4319       0       0 eigenvectors,
            0 11.1136       0 and the diagonal
            0       0 -0.5455 entries of "val"
are the
eigenvaules

94
Matrix built-in constructions

 For more, type help func_name


Input Output Comments
rand(2) ans = 0.9501 0.6068
Generates a matrix with
        0.2311 0.4860
rand(2,3) ans = 0.8913 0.4565 0.8214
entries randomly distributed
        0.7621 0.0185 0.4447 between 0 and 1
zeros(2) ans = 0 0
        0 0 Generates a 2x2 matrix with
ones(2) ans = 1 1 all zero (or all ones) entries.
        1 1
eye(2) ans = 1 0
        0 1
Identity matrix I.
hilb(3) ans = 1.0000 0.5000 0.3333
        0.5000 0.3333 0.2500 3x3 Hilbert matrix.
        0.3333 0.2500 0.2000

95
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, use
X(:,2) = [ ];
Thus, X= [1 3
4 6
7 0]
 If you delete a single element from a matrix, the result isn't
a matrix anymore.
 So, expressions like
X(1,2) = [ ], result in an error.

96
Concatenating Matrices, Cont.
a=[1 2;3 4]
Input Output
[a, a, a] ans = 1 2 1 2 1 2
        3 4 3 4 3 4
[a; a; a] ans = 1 2
        3 4
        1 2
        3 4
        1 2
        3 4
[a, zeros(2); zeros(2), a'] ans = 1 2 0 0
        3 4 0 0
        0 0 1 3
        0 0 2 4

97
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.

98
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

99
Solving equations, Cont.

 MATLAB uses the division terminology


familiar 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 left
or right of the coefficient matrix.

100
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.

101
Solving equations, Cont.
 In practice, linear equations of the form AX = B
occur 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.

102
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

103
Solving equations, an Example,
Cont.
 To verify this assertion, try this:
a*x, a*x - b, eps
The results are:
ans = 1 1 1
ans = 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.

104
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.

105
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

106
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

107
Advanced Graphics and
Plotting

Elementary Plotting Functions,


Creating a plot
>> plot(x,y)
 produces a graph of y versus x, where x and y are
two vectors
1

0.8

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

plot(x,sin(x));
0.4

0.2

Sine of x
0

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7
x

109
Line styles and colors
 It is possible to specify color, line styles, and markers
when 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'

110
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
111
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

112
Adding plots

 Setting hold to on, MATLAB doesn’t remove


the existing graph and adds the new data to
the current graph 1

0.8

 x=linspace(0,2*pi,100); 0.6

0.4

plot(x,sin(x)); 0.2

Sine of x
hold on;
0

-0.2

plot(x,cos(x)); -0.4

-0.6

xlabel('x'); -0.8

ylabel('Sine of x');
-1
0 1 2 3 4 5 6 7
x

113
Adding plots

With more graphics


functionalities:

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

114
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

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

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

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

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

119
Graphics
Three-dimensional graphics
>> A = zeros(32);
>> A(14:16,14:16) = ones(3);
>> F=abs(fft2(A));
>> mesh(F)
>> rotate3d on
Several other plot functions available
>> surfl(F)
Can change lightning and material
properties
>> cameramenu
>> material metal
Graphics
 Bitmap images can also be visualized
 >> load mandrill
 >> image(X); colormap(map)
 >> axis image off
122
MATLAB graphics
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

120

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

20

0
0 200 400 600 800 1000 1200 1400 1600

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

124
MATLAB graphics (ctd)
1

0.9

0.8

0.7
» x = rand(1,100);
» y = rand(1,100); 0.6

» plot(x,y,'*') 0.5

0.4

0.3

0.2

0.1

0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

125
MATLAB images

» load earth
» whos
Name Size Bytes Class

X 257x250 514000 double array


map 64x3 1536 double array

Grand total is 64442 elements


using 515536 bytes

» image(X); colormap(map);

126
Thank You!

You might also like