getting started matlab fundamentals dr. umakant dwivedi 15/10/2009

Post on 20-Dec-2015

237 Views

Category:

Documents

5 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Getting Started

MATLAB fundamentals

Dr. Umakant Dwivedi15/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.

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

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

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

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.

7

Double Click on Icon Will open MATLAB

8

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.

10

CommandWindow

WorkingMemory

CommandHistory

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;

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)

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.

14

Command WindowGetting help from the command window

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

15

Arithmetic operation

The basic arithmetic operations on matrices are:

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

16

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

operations by prepending a ‘.’ before the operator

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

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

18

Logical operations

MATLAB defines the following logical operations:

& and | or ~ not

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

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

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

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]

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

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

25

Flow control

If statements

if expression

statements

else

statements

end

Example

If n<0a=a-1;

elsea=a+1;

end

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

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

Loading XLS File into MatLab and Plotting

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

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

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

32

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

33

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

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

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

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

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

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

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.

Advanced operations in Matlab

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.

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

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.

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

45

Flow control

If statements

if expression

statements

else

statements

end

Example

If n<0a=a-1;

elsea=a+1;

end

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

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

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)

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

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

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

Thank You!

top related