Tutorial on Matlab

advertisement
Getting Started
MATLAB fundamentals
Dr. Umakant Dwivedi
15/10/2009
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.
2
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
3
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
4
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
5
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.
6
Double Click on Icon Will open MATLAB
7
8
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,

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.

Command History: An ordered list of all commands
issued in the Command Window.
9
Working
Memory
Command
Window
Command
History
10

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 ;
>>b=5*a;
>>c=b;
11
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)
12

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.
13
Command Window
Getting help from the command window
help <function_name> (show the help document for a given function)
14
Arithmetic operation

The basic arithmetic operations on matrices
are:






+ addition
- subtraction
* multiplication
/ division
^ power
‘ conjugate transpose
15
element-by-element operations

MATLAB provides element-by-element
operations by prepending a ‘.’ before the
operator




.* multiplication
./ division
.^ power
.’ transpose (unconjugated)
16
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
17
Logical operations

MATLAB defines the following logical
operations:



& and
| or
~ not
18
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
tan
atan
tanh
log10
sign
19
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
20
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
21
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]

22
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
>> x = 3+4j
>> real(x)
>> imag(x)
>> abs(x)
>> angle(x)
>> conj(x)
->3
->4
->5
->0.9273
->3 - 4i
23
Complex numbers

Examples





x=5+3i and y= -3+1.5i
Finding, Real part of x ,Imaginary part of x ,
Magnitude of x, Angle of x, Complex conjugate of
x
Find x+y, x-y, x.y, x/y
V=230 angle 30 deg. and I=10 angle -30 deg.
Calculate Complex power S=V.I*, Real and
reactive powers
24
Flow control
Example

If statements
if expression
statements
else
statements
end
If n<0
a=a-1;
else
a=a+1;
end
25
Flow control

For

Repeats a group of statements a fixed,
predetermined number of times.
a=0;
for n = 1:10
a=a+1;
end
26
Flow control

WHILE
WHILE Repeat statements an indefinite number of times.
The general form of a WHILE statement is:

WHILE expression
statements
END.

Example
a=0; b=5;
while (a<25)
a=a+1;
end
27
Loading XLS File into
MatLab and Plotting
Loading an Excel File: Open MatLab

Select Import Data from the File menu in the MatLab, OR double
click on the data file in the Current directory window.
Double Click on your
Data file
29
Loading an Excel File: A new window named Import Wizard as
shown below should pop-up (in few seconds).
Select
Create vector
then Click
Finish button
30
Plotting variables from workspace:
Step 1
To plot y Vs x graph.
Click on variable x
then press Ctrl button
and select variable y
Step 2
Click on plot button
OR use plot command
Plot(x,y)
>> plot(Time,Rdata)
31
Click on Insert button on the toolbar pallets as shown in the
2nd figure to add Title, X ,Y-axis name and legend
32
After adding Title etc. You can save the figure or copy it
and
33
Final Graph
My Title
8
data1
6
4
Rdata
2
0
-2
-4
-6
0
1
2
3
4
5
Time
6
7
8
9
10
34
Plotting using plot command

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
35

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')
36
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
37

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);
38

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.
39
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.

41
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
>> x = 3+4j
>> real(x)
>> imag(x)
>> abs(x)
>> angle(x)
>> conj(x)
->3
->4
->5
->0.9273
->3 - 4i
42
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.
43
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
44
Flow control
Example

If statements
if expression
statements
else
statements
end
If n<0
a=a-1;
else
a=a+1;
end
45
Flow control

For

Repeats a group of statements a fixed,
predetermined number of times.
a=0;
for n = 1:10
a=a+1;
end
46
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
47
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)
48
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
-0.2
-0.4
-0.6
-0.8
-1
0
1
2
3
4
5
6
7
x
49
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
50
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
>>clf

Clear current figure window
51
Thank You!
Download