52
Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

  • View
    230

  • Download
    5

Embed Size (px)

Citation preview

Page 1: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

Getting Started

MATLAB fundamentals

Dr. Umakant Dwivedi15/10/2009

Page 2: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

2

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.

Page 3: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

3

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

Page 4: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

4

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

Page 5: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

5

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

Page 6: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

6

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.

Page 7: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

7

Double Click on Icon Will open MATLAB

Page 8: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

8

Page 9: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

9

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.

Page 10: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

10

CommandWindow

WorkingMemory

CommandHistory

Page 11: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

11

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;

Page 12: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

12

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)

Page 13: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

13

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.

Page 14: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

14

Command WindowGetting help from the command window

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

Page 15: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

15

Arithmetic operation

The basic arithmetic operations on matrices are:

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

Page 16: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

16

element-by-element operations MATLAB provides element-by-element

operations by prepending a ‘.’ before the operator

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

Page 17: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

17

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

Page 18: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

18

Logical operations

MATLAB defines the following logical operations:

& and | or ~ not

Page 19: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

19

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

Page 20: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

20

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

Page 21: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

21

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

Page 22: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

22

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]

Page 23: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

23

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

Page 24: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

24

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

Page 25: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

25

Flow control

If statements

if expression

statements

else

statements

end

Example

If n<0a=a-1;

elsea=a+1;

end

Page 26: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

26

Flow control

For Repeats a group of statements a fixed,

predetermined number of times.

a=0;

for n = 1:10

a=a+1;

end

Page 27: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

27

Flow control WHILE

WHILE Repeat statements an indefinite number of times.The general form of a WHILE statement is: WHILE expression statements END.

Examplea=0; b=5;while (a<25)

a=a+1;end

Page 28: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

Loading XLS File into MatLab and Plotting

Page 29: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

29

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

Page 30: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

30

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

Page 31: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

31

Plotting variables from workspace:

To plot y Vs x graph. Click on variable x then press Ctrl button and select variable y

Step 1

Step 2Click on plot button

Plot(x,y)>> plot(Time,Rdata)

OR use plot command

Page 32: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

32

Click on Insert button on the toolbar pallets as shown in the 2nd figure to add Title, X ,Y-axis name and legend

Page 33: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

33

After adding Title etc. You can save the figure or copy it and

Page 34: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

34

0 1 2 3 4 5 6 7 8 9 10-6

-4

-2

0

2

4

6

8

Time

Rda

ta

My Title

data1

Final Graph

Page 35: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

35

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

Page 36: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

36

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

Page 37: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

37

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

Page 38: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

38

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

Page 39: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

39

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.

Page 40: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

Advanced operations in Matlab

Page 41: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

41

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.

Page 42: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

42

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

Page 43: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

43

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.

Page 44: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

44

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

Page 45: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

45

Flow control

If statements

if expression

statements

else

statements

end

Example

If n<0a=a-1;

elsea=a+1;

end

Page 46: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

46

Flow control

For Repeats a group of statements a fixed,

predetermined number of times.

a=0;

for n = 1:10

a=a+1;

end

Page 47: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

47

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

Page 48: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

48

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)

Page 49: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

49

Creating a plot

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

two vectors

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

plot(x,sin(x));

0 1 2 3 4 5 6 7-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

x

Sin

e of

x

Page 50: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

50

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

Page 51: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

51

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

Page 52: Getting Started MATLAB fundamentals Dr. Umakant Dwivedi 15/10/2009

Thank You!