0% found this document useful (0 votes)
105 views

Matlab Session 1 Introduction

This document provides an overview of MATLAB fundamentals including what MATLAB is used for, how to start and exit MATLAB, how to get help in MATLAB, the basics of MATLAB including variables, arrays, and matrices, and some examples of basic MATLAB operations and functions.

Uploaded by

fayaz5uin1234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views

Matlab Session 1 Introduction

This document provides an overview of MATLAB fundamentals including what MATLAB is used for, how to start and exit MATLAB, how to get help in MATLAB, the basics of MATLAB including variables, arrays, and matrices, and some examples of basic MATLAB operations and functions.

Uploaded by

fayaz5uin1234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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

Getting Started

MATLAB fundamentals

Index

About Matlab
The basics
Advanced operations
Examples
Advanced Graphics and Plotting

UD Dwivedi

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.

UD Dwivedi

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

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 applicationspecific 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

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
C-kernel

Contr. Syst.

m-files
UD Dwivedi

Simulink
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
UD Dwivedi

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

Double Click on Icon Will open MATLAB

UD Dwivedi

11

UD Dwivedi

12

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

Working
Memory

Command
Window

Command
History

UD Dwivedi

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
matlab/elmat
matlab/elfun
matlab/specfun
control\control

Important
for this course

- General purpose commands.


- Elementary matrices and matrix manipulation.
- Elementary math functions.
- Specialized math functions, etc.
- Control System Toolbox
UD Dwivedi

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.

UD Dwivedi

16

Help Window

You can also use the Help Window, activated


from the desktop. For example, let's look up
information on the Matlabs functions by
category. (see next slide)

UD Dwivedi

17

UD Dwivedi

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
UD Dwivedi

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)

UD Dwivedi

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.
UD Dwivedi

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
UD Dwivedi

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)
UD Dwivedi

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.

UD Dwivedi

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


UD Dwivedi

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.
UD Dwivedi

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.
UD Dwivedi

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.
UD Dwivedi

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 6element 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

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

UD Dwivedi

31

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

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

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

To create a vector is pretty similar.

To create a vector of values going in even steps


from one value to another value, you would use

Each element is separated by spaces, the whole vector is in


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

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

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,:)
UD Dwivedi

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.

UD Dwivedi

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

UD Dwivedi

38

who

whos

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

pi

will tell you all the variables you have currently defined.

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

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

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

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

Plot of random 100 values

0.8
0.6
0.4
0.2
0

10

20

30

40

50
Sampling instants

60

70

80

90

100

60

70

80

90

100

60

70

80

90

100

Plot of random 100 values


1
Random Numbers

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

0.8
0.6
0.4
0.2
0

10

20

30

40

50
Sampling instants
Plot of random 100 values

1
Random Numbers

Random Numbers

0.8
0.6
0.4
0.2
0

10

20

30

UD Dwivedi

40

50
Sampling instants

43

Printing, Saving, and Loading

Basic printing

You can also save to a Postscript or Encapsulated


Postscript file:

>>print Pprintername

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

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

When you save data using the command

matlab will save all of your variables and their


values in its own format, so that when you
load it using

save filename.mat

load filename.mat

you will have all of your variables already


defined and names.
UD Dwivedi

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.

UD Dwivedi

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
UD Dwivedi

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.
UD Dwivedi

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.
UD Dwivedi

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.

UD Dwivedi

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.

UD Dwivedi

53

Complex numbers

Some useful operations on complex


numbers:

Complex scalar
Real part of x
Imaginary part of x
Magnitude of x
Angle of x
Complex conjugate of x
UD Dwivedi

>> x = 3+4j
>> real(x)
>> imag(x)
>> abs(x)
>> angle(x)
>> conj(x)

->3
->4
->5
->0.9273
->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.

UD Dwivedi

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
UD Dwivedi

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
UD Dwivedi

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]

UD Dwivedi

58

Arithmetic matrix operation

The basic arithmetic operations on matrices


are:

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

59

element-by-element operations

MATLAB provides element-by-element


operations by prepending a . before the
operator

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

UD Dwivedi

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
UD Dwivedi

61

Logical operations

MATLAB defines the following logical


operations:

& and
| or
~ not

UD Dwivedi

62

Math functions

The following functions operate element-wise


when applied to a matrix:
sin
asin
sinh
exp
abs

cos
acos
cosh
log(natural log)
sqrt
UD Dwivedi

tan
atan
tanh
log10
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-le are placed in
MATLABs workspace that contains all the variables
dened in the MATLAB session

UD Dwivedi

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
UD Dwivedi

65

Flow control
Example

If statements
If n<0
a=a-1;
else
a=a+1;
end

if expression
statements
else
statements
end

UD Dwivedi

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

UD Dwivedi

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
UD Dwivedi

68

Entering Matrices
We can enter matrices into MATLAB in several
different ways:

1.
2.
3.
4.

Enter an explicit list of elements.


Load matrices from external data files.
Generate matrices using built-in functions.
Create matrices with your own functions in M-files.

We have only to follow a few basic


conventions:

1.
2.
3.

Separate the elements of a row with blanks or commas.


Use a semicolon, ; , to indicate the end of each row.
Surround the entire list of elements with square brackets, [ ].

UD Dwivedi

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)
UD Dwivedi

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 !?
UD Dwivedi

71

Floating point numbers in Matlab

IEEE Standard for double precision numbers


e

1 2

f
12 13

64

Round-off:
eps = 2-52
Underflow:
realmin = 2-1022
Overflow: realmax = (2-eps) 21023
UD Dwivedi

72

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
UD Dwivedi

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
UD Dwivedi

74

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

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

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

UD Dwivedi

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

UD Dwivedi

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

UD Dwivedi

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)
UD Dwivedi

80

Examples

Syntax - symbols and punctuation

Try these examples

Input

Output

Comments

2+3
7-5
34*212
1234/5786
2^5

ans = 5
ans = 2
Arithmetic works as expected.
ans = 7208
ans = 0.2173 Note that the result is given the name "ans" each time.
ans = 32

a = sqrt(2)

a = 1.4142

You can choose your own names for things.

UD Dwivedi

82

b = a, pi, 2 + 3i

c = sin(pi)
eps

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

You can use commas to put more


than one command on a line. Pi, i,
and j are contants.

c = 1.2246e-016
ans = 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 d = 1 2 3 4 5 6 7 8 9
e=123456789
]
e = [1:9]
f=123456789
f = 1:9
g = 0:2:10
f(3)
f(2:7)
f(:)

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

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

h = [1 2 3];
h'

(nothing)
ans = 1
2
3

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 .* h
h + h

ans = 14
ans = 1 4 9
ans = 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 3
4 5 6
7 8 9

Entering a matrix.

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

Accessing matrix elements.


Note use of ":" to access an entire row.

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

UD Dwivedi

84

Input

g^2

g .^ 2

Output

Comments

ans =

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

UD Dwivedi

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

UD Dwivedi

86

Working with Scalars, Cont.

Try these examples


Input

Output

Comments

b=2

b=2

Define b to be a scalar.

a + b

ans = 3 4
5 6

Addition works entry-by-entry.

a * b

ans = 2 4
6 8

So does multiplication.

a ^ b

ans = 7 10
15 22

This is matrix power - a*a

a .^ b

ans = 1 4
9 16

Entry-by-entry power.

UD Dwivedi

87

Vectors

A vector is just a matrix with only one row or


column
Input

Output

Comments

v = [1 2 3]
u = [3 2 1]

v = 1 2 3
u = 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

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
n
precisely,
C (i, j ) = A(i, k ) * B(k , j )
k =1

UD Dwivedi

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

UD Dwivedi

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
UD Dwivedi

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.

UD Dwivedi

92

Matrix built-in operations

For more, type help matfun

Input

Output

Comments

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

k = 16 2 3
5 11 10
9 7 6

Define a matrix.

rank(k)

ans = 3

The rank.

det(k)

ans = -136

The determinant.

UD Dwivedi

93

Matrix built-in operations, Cont.


Input

Output
ans =

inv(k)

[vec,val] =
eig(k)

Comments
0.0294 -0.0662 0.0956
-0.4412 -0.5074 1.0662
0.4706 0.6912 -1.2206

vec = -0.4712 -0.4975 -0.0621


-0.6884 0.8282 -0.6379
-0.5514 0.2581 0.7676
val = 22.4319
0
0
0 11.1136
0
0
0 -0.5455

UD Dwivedi

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

94

Matrix built-in constructions

For more, type help func_name

Input

Output

rand(2)

ans = 0.9501
0.2311
ans = 0.8913
0.7621

rand(2,3)
zeros(2)
ones(2)

ans = 0
0
ans = 1
1

Comments
0.6068
0.4860
0.4565 0.8214
0.0185 0.4447

0
0
1
1

Generates a matrix with


entries randomly distributed
between 0 and 1
Generates a 2x2 matrix with
all zero (or all ones) entries.

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
0.3333 0.2500 0.2000

3x3 Hilbert matrix.

UD Dwivedi

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.
UD Dwivedi

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
3
1
3
1
3

2
4
2
4
2
4

[a, zeros(2); zeros(2), a']

ans = 1
3
0
0

2
4
0
0

UD Dwivedi

0
0
1
2

0
0
3
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.
UD Dwivedi

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

UD Dwivedi

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.

UD Dwivedi

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.
UD Dwivedi

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

3.

m = n, Square system. Seek an exact solution.


m > n, Overdetermined system. Find a least squares
solution.
m < n, Underdetermined system. Find a basic solution
with at most m nonzero components.
UD Dwivedi

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

UD Dwivedi

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.
UD Dwivedi

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.

UD Dwivedi

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


UD Dwivedi

106

Saving and loading matrices

To save all variables in a file named


mysession.mat in a reloadable format

To restore the session, use

save mysession
load mysession

The saved files are in text format and can be


viewed using any text editor

UD Dwivedi

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

0.6

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

0.4

0.2
Sine of x

-0.2

-0.4

-0.6

-0.8

-1

UD Dwivedi

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'
UD Dwivedi

110

Axis lables and titles

xlabel('string')

ylabel('string')

labels the x-axis of the current axes

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

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

Adding plots

Setting hold to on, MATLAB doesnt remove


the existing graph and adds the new data to
the current graph
x=linspace(0,2*pi,100);
1

0.8

0.6

0.4

plot(x,sin(x));
hold on;
plot(x,cos(x));
xlabel('x');
ylabel('Sine of x');

0.2
Sine of x

-0.2

-0.4

-0.6

-0.8

-1

UD Dwivedi

113

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

Basic plotting commands

Plot

Loglog

Graph with logarithmic scales for both axes

Semilogx

Graph 2-D data with linear scales for both axes

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

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

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

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

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

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

UD Dwivedi

120

Graphics

Bitmap images can also be visualized


>> load mandrill
>> image(X); colormap(map)
>> axis image off

UD Dwivedi

121

UD Dwivedi

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;
b = 100:0.01:101;
c = 101:-1:1;
d = [a b c];
e = [d d d d d];
plot(e)

100

80

60

40

20

200

400

UD Dwivedi

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)

UD Dwivedi

124

MATLAB graphics (ctd)


1
0.9
0.8

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

0.7
0.6
0.5
0.4
0.3
0.2
0.1
0

0.1

0.2

0.3

0.4

UD Dwivedi

0.5

0.6

0.7

0.8

0.9

125

MATLAB images
load earth
whos
Name
Size
X
257x250
map
64x3

Bytes Class
514000 double array
1536 double array

Grand total is 64442 elements


using 515536 bytes
image(X); colormap(map);

UD Dwivedi

126

Thank You!

You might also like