An Introduction to MATLAB for beginners

99
INTRODUCTION TO MATLAB 1 By Murshida ck TKMCE

description

MATLAB for beginners

Transcript of An Introduction to MATLAB for beginners

Page 1: An Introduction to MATLAB for beginners

INTRODUCTION TO MATLAB

1

ByMurshida ck

TKMCE

Page 2: An Introduction to MATLAB for beginners

CONTENTS•Introduction•Desktop tools•Creating arrays•Mathematical operation with arrays•Script files•Two dimensional plots•Functions

2

Page 3: An Introduction to MATLAB for beginners

Introduction MATLAB is a program for doing numerical computation. originally designed for solving linear algebra type problems using

matrices. name derived from MATrix LABoratory. MATLAB has since been expanded and now has built-in functions

for solving problems requiring data analysis

signal processing optimization

and several other types of scientific computations. It also contains functions for 2-D and 3-D graphics and animation.

3

Page 4: An Introduction to MATLAB for beginners

4

Page 5: An Introduction to MATLAB for beginners

The MATLAB environment is command oriented somewhat like UNIX. A prompt appears on the screen and a MATLAB statement can be entered. When the <ENTER> key is pressed, the statement is executed, and another prompt appears.

If a statement is terminated with a semicolon ( ; ), no results will be displayed. Otherwise results will appear before the next prompt.

5

Page 6: An Introduction to MATLAB for beginners

Desktop Tools•Command Window

-type commands

•Workspace-view program variables-clear to clear -double click on a variable to see it in the Array Editor

•Command History-view past commands-save a whole session using diary 6

Page 7: An Introduction to MATLAB for beginners

Command Window

Current Directory

Workspace

Command History

7

Page 8: An Introduction to MATLAB for beginners

•Figure Window -contains output from graphic commands•Help Window -provides help information•Editor Window -creates and debugs script and function files•Current directory Window -shows files in current directory•Launch Pad Window -provides access to tools,demos and documentation 8

Page 9: An Introduction to MATLAB for beginners

COMMAND WINDOW >> type codePress enter Command executed and output displayedsemicolon(;)

output not displayedEllipsis(…) if a command is too long to fit in one lineCommand can continue line after line up to 4096 characters.

9

Page 10: An Introduction to MATLAB for beginners

MATLABCommandWindow

10

Page 11: An Introduction to MATLAB for beginners

Matlab case sensitive% -commentclc -clear screen↑ -recall previously typed commands↓ -move down to previously typed commands

11

Page 12: An Introduction to MATLAB for beginners

Arithmetic Operations With Scalars

Operation Symbol ExampleAddition + 5+3Subtraction - 5-3Multiplication * 5*3Right division / 5/3Left division \ 5\3=3/5Exponentiation ^ 5^3=125

12

Page 13: An Introduction to MATLAB for beginners

text from a MATLAB screen

» %To get started, type one of these commands: » a=5;» b=a/2

b =

2.5000

»

13

Page 14: An Introduction to MATLAB for beginners

Order of Precedence

Parentheses

Exponentiation

Multiplication and division

Addition and subtraction

14

Page 15: An Introduction to MATLAB for beginners

Display Formats User can control format in which MATLAB displays o/p on screen.format command– To change o/p formatDefault format for numerical values -short (fixed point with 4 decimal digits)

15

Page 16: An Introduction to MATLAB for beginners

Command Description

format short Fixed-point with 4 decimal digits

format long Fixed-point with 14 decimal digits

format bank 2 decimal digits

format compact Eliminates empty lines

format loose Adds empty lines

16

Page 17: An Introduction to MATLAB for beginners

Elementary Math functionsFunction Description

sqrt (x) Square root

exp (x) Exponential (ex )

abs (x) Absolute value

log (x) Natural logarithmBase e logarithm

Log10(x) Base 10 logarithm

factorial(x) Factorial function x!

17

Page 18: An Introduction to MATLAB for beginners

Trigonometric math functionssin(x),cos(x), tan(x),cot(x)Rounding functions

Function Description

round(x) Round to the nearest integer

fix(x) Round towards zero

ceil(x) Round towards infinity

floor(x) Round towards minus infinity

rem(x,y) Returns remainder after x is divided by y

Sign(x) Signum function18

Page 19: An Introduction to MATLAB for beginners

Math Functions

Elementary functions (sin, cos, sqrt, abs, exp, log10, round)

-type help elfun

Advanced functions (bessel, beta, gamma, erf)-type help specfun-type help elmat

19

Page 20: An Introduction to MATLAB for beginners

Variables (Arrays) and Operators

20

Page 21: An Introduction to MATLAB for beginners

Defining scalar variablesvariable is a name made of a letter or a combination of several letters that is assigned a numerical value

- actually name of a memory location-assignment operator ‘=‘

aaaaa

Variable_name=a numerical value or a computable expression

>>x=15>>x=3*x-12

21

Page 22: An Introduction to MATLAB for beginners

• When new variable is created matlab assigns appropriate memory space where assigned value can be stored

• When variable is used stored data is used• If assigned new value content of memory is

replaced>>ABB=72;>>ABB=9;>>ABBABB= 9

22

Page 23: An Introduction to MATLAB for beginners

Rules about variable names• Variable names are case sensitive.• Variable names can contain up to 63 characters

(as of MATLAB 6.5 and newer).• Variable names must start with a letter followed

by letters, digits, and underscores.• Must begin with a letter.• Avoid using names of built-in functions for

variable.23

Page 24: An Introduction to MATLAB for beginners

Predefined variablesvariable descriptionans Value of last expressioneps Smallest difference

between 2 numbersi √-1inf Infinityj Same as iNaN Not a numberpi The number ∏

24

Page 25: An Introduction to MATLAB for beginners

Some Useful MATLAB commands

• who List known variables• whos List known variables plus their size• help >> help sqrt Help on using sqrt• clear Clear all variables from work space• clear x y Clear variables x and y from work space• clc Clear the command window

25

Page 26: An Introduction to MATLAB for beginners

ArrayList of numbers arranged in row and/or columns.• Simplest array

-1D array-usually to represent vectors.

• Complex array-2D array-represent matrixes

26

Page 27: An Introduction to MATLAB for beginners

Creating vector from a known list of numbers

•Row vector-type elements with space or comma•Column vector-type elements with semicolon(;) or press Enter key after each element

Variable_name = [type vector elements]

27

Page 28: An Introduction to MATLAB for beginners

Creating vector with constant spacing

or

First term spacing last term

First element last element no of elements(when omitted default value 100)

Variable_name = [m:q:n] Variable_name = m:q:n

Variable_name = linspace(xi,xf,n)

28

Page 29: An Introduction to MATLAB for beginners

Creating 2D array(matrix)•Matrix are used in science & eng to describe many physical quantities.

•All rows must have same number of elements

Variable_name = [1st row elements;2nd row elements;……;last row elements]

29

Page 30: An Introduction to MATLAB for beginners

Zeros , ones and eye commands•zeros(m,n)

mxn matrix of 0’s.•ones(m,n)

mxn matrix of I’ s. •eye(n)

nxn identity matrix

30

Page 31: An Introduction to MATLAB for beginners

Transpose operator•Type single quote (‘) following variable to be transposed.

>> aa = [3 8 1]aa= 3 8 1>>bb=aa’bb= 3 8 1

31

Page 32: An Introduction to MATLAB for beginners

Array addressing

•Vector named ve

element in position k•Matrix ma

refers to element in row k & column p

ve(k)

ma(k,p)

32

Page 33: An Introduction to MATLAB for beginners

Using a colon : in addressing arraysva(:) -all elements of vector vava(m:n) -all elements m through n of vector va A(:,n) -elements in all rows of column n of matrix AA(n,:) -elements in all columns of row n of matrix AA(:,m:n) -elements of all rows between columns m and nA(m:n,:) -elements in all columns between rows m and n 33

Page 34: An Introduction to MATLAB for beginners

Adding elements to existing variables

•by assigning values to the elements.>>DF = 1 2 3 4DF = 1 2 3 4>>DF(5:10)=10:5:35DF = 1 2 3 4 10 15 20 25 30 35>>AD = [5 7 2 ]AD = 5 7 2>>AD(8) = 4AD= 5 7 2 0 0 0 0 4

>>RE = [3 8 1 ];>>GT = 4:3:16;>>KNH = [RE GT]KNH = 3 8 1 4 7 10 13 16>>E = [1 2 3 4;5 6 7 8]E= 1 2 3 4 5 6 7 8>>E(3,:) = [6:4:9]E= 1 2 3 4 5 6 7 8 6 7 8 9

Appending Adding elements

to a vector

Matlab add zeros between last original element and new element

Adding elements to a matrix

34

Page 35: An Introduction to MATLAB for beginners

Deleting ElementsBy assigning nothing to these elements.

>>kt =[10 8 6 21 9]kt= 10 8 6 21 9>>kt(4) = []Kt= 10 8 6 9>>mtr = [5 56 75;23 54 12;64 12 76]mtr= 5 56 75 23 54 12 64 12 76

>>mtr(:,2:3) = []mtr= 5 23 64

>>

Eliminate the 4th element

Eliminate all rows of columns 2 through 3

35

Page 36: An Introduction to MATLAB for beginners

Building function for handling arrays

Function Description Example

length(A) returns number of elements in vector A

>>A =[ 5 9 2 4]>>length(A)ans = 4

size(A) returns a row vector of [m,n] >>A=[6 1 4 0;5 9 8 2]A= 6 1 4 5 9 8 >>size(A)ans = 2 3

reshape(A,m,n) rearrange r x s matrix to a m x n matrix

>>B=reshape(A,3,2)B= 6 5 1 9 4 8

36

Page 37: An Introduction to MATLAB for beginners

contd…

Function Description Example

diag(v) When v is a vector ,creates a square matrix with the elements of v in the diagonal.

>>v = [7 4 2];>>A =diag(v)A= 7 0 0 0 4 0 0 0 2

diag(A) When A is a matrix , creates a vector from the diagonal elements of A .

>>A= [1 2 3;4 5 6;7 8 9]A= 1 2 3 4 5 6 7 8 9>>vec=diag(A)Vec=159

37

Page 38: An Introduction to MATLAB for beginners

Strings And String As Variables

•In single quotes.•Text on screen change to purple when 1st single quote is typed then turns into maroon when string is typed.•Used in

-o/p commands to display text messages.-in formatting commands of plots.(labels to axes ,

title and plots).-as i/p arguments for some functions.

>>Name = ‘murshida’Name = murshida>>Name(2:8) = ‘idhya ‘Name = midhya 38

Page 39: An Introduction to MATLAB for beginners

Character Strings>> hi = ' hello';>> class = 'MATLAB';>> hihi = hello>> classclass =MATLAB>> greetings = [hi class]greetings = helloMATLAB>> vgreetings = [hi;class]vgreetings = helloMATLAB

concatenation with blank or with “,”

concatenation with blank or with “,”

semi-colon: join verticallysemi-colon: join vertically

39

Page 40: An Introduction to MATLAB for beginners

Strings placed as matrixDone by typing ‘;’ or by pressing ‘Enter’ key at the end of each row.Each row must be placed as strings.(ie enclosed in single quotes).Each row with words of equal size.add space for making words of equal size.

>>a=[‘abcd’;’efg ‘]a= abcd efg

>>a=[‘ab cd’;’ef gh’]a= ab cd ef gh

40

Page 41: An Introduction to MATLAB for beginners

Built-in function char•Create an array with rows that have same number of characters from an input of characters which are not of same length.•MATLAB makes length of all rows equal to the longest line by adding spaces to the short line.

Variable_name = char( ‘ string 1 ’ , ’ string 2 ’ , ’string 3 ’ )

>>info = char(‘student name:’,’john smith’,’grade:’,’A+’)Info = student name: john smith grade: A+ 41

Page 42: An Introduction to MATLAB for beginners

>>X=‘156’

X= 156>>Y=156

Y= 156>>

both X & Y look the same .But X cannot be used for mathematical calculation.

both X & Y look the same .But X cannot be used for mathematical calculation.

42

Page 43: An Introduction to MATLAB for beginners

Mathematical Operations with Arrays

43

Page 44: An Introduction to MATLAB for beginners

Addition and subtraction>>vectA = [8 5 4]; vectB = [10 2 7];>>vectC = vectA + vectBvectC = 18 7 11>>A = [ 5 -3 8;9 2 10]A = 5 -3 8 9 2 10>>B = [10 7 4;-11 15 1]B = 10 7 4 -11 15 1>>A - Bans= -5 -10 4 20 -13 9

44

Page 45: An Introduction to MATLAB for beginners

Array multiplication>>F = [1 3; 5 7]

F= 1 3 5 7>>G = [ 4 2; 1 6 ]G= 4 2 1 6>>F*Gans = 7 20 27 52

>>b=3b= 3>>b*Fans = 3 9 15 21

45

Page 46: An Introduction to MATLAB for beginners

Array division•Determinants |A|

in matlab use det(A)•Identity matrix AI = IA = A In matlab use eye(A) •Inverse of a matrix

BA = AB = IIn matlab use A ^-1 or inv(A)

46

Page 47: An Introduction to MATLAB for beginners

Contd..Left division to solve matrix eqn AX = B

X = A\BRight division to solve matrix eqn XC = D

X = D/C

What happens: B is divided by A

What happens: D is divided by A

47

Page 48: An Introduction to MATLAB for beginners

example

Q. Solve three linear equations using matrix4x - 2y + 6z = 8 2x + 8y +2z = 4

6x + 10y+3z= 0Eqns are of the form AX = B or XC =D 4 -2 6 x 8 2 8 2 y = 4 6 10 3 z 0 or 4 2 6 x y z -2 8 10 = 8 4 0 6 2 3 48

Page 49: An Introduction to MATLAB for beginners

Operators (Element by Element)

.* element-by-element multiplication./ element-by-element right division.\ element-by-element left division .^ element-by-element exponentiation

49

Page 50: An Introduction to MATLAB for beginners

element-by-element operations

>>A = [ 2 6 3; 5 8 4]A= 2 6 3 5 8 4>>B = [ 1 4 10; 3 2 7]B= 1 4 10 3 2 7>>A .*B ans= 2 24 30 15 16 28

>>C = A/BC= 2.0000 1.5000 0.3000 1.6667 4.0000 0.5714>>B .*3

ans= 1 64 1000 27 8 343>>A * B???Error using ==>Inner matrix dimensions must agree.

50

Page 51: An Introduction to MATLAB for beginners

Built-in function for analayzing arrays

51

Page 52: An Introduction to MATLAB for beginners

Function Description Examplemean(A) mean value of the elements of the vector A. >> A=[5 9 2 4];

>>mean(A)ans = 5

C=max(A)

[d,n]=max(A)

C= is the largest element in vector A.( If A is a matrix, C =row vector containing the largest element of each column of A.)

d =largest element in vector A, n =position of the element ( the first if several have the max value ).

>>A=[5 9 2 4 11 6 7 11 0 1];>>C=max(A)C= 11

>>[d,n]=max(A)d = 11n = 5

min(A)

[d,n]=min(A)

Same as max(A) , but forsmallest element.

Same as [d,n]= max(A), but for the smallest element .

>>A=[5 9 2 4];>>min(A)ans = 2

Std(A) standard deviation of the element of the vector A.

>>A=[5 9 2 4];>>std(A)Ans= 2.9439

52

Page 53: An Introduction to MATLAB for beginners

Function Description Example

dot (A) scalar (dot) product of two vectors a and b. The vectors can each be row or column vector.

>>a=[1 2 3];>>b=[ 3 4 5];>>dot(A)Ans= 26

cross(A) cross product of two vectors a and b , (a*b). The vectors must have 3 element.

>>a=[1 3 2];>>b=[2 4 1];>>cross(a,b)Ans= -5 3 -2

sum(A) sum of the elements of the vector A. >>A=[5 9 2 4];>>sum(A)ans= 20

sort(A) arranges the elements of the vector A in ascending order.

>>A=[5 9 2 4 ];>>sort(A)ans= 2 4 5 9

Median(A) median value of the elements of the vector A.

>>A=[5 9 2 4];>>median(A)ans= 4.5000

53

Page 54: An Introduction to MATLAB for beginners

•commands cannot be saved and executed again.•not interactive.•for change or correction all commands are to be entered & executed again.

Limitations of command window

54

Page 55: An Introduction to MATLAB for beginners

Script files

create a file with list of commands . save

it & run the file

55

Page 56: An Introduction to MATLAB for beginners

File

creating a script file

56

Page 57: An Introduction to MATLAB for beginners

Use of M-FileClick to create a new M-File

• Extension “.m” • A text file containing script or function or program to run

57

Page 58: An Introduction to MATLAB for beginners

m-file Editor Window

line number

commands are typed line by line.

new line starts when ENTER KEY is

pressed

58

Page 59: An Introduction to MATLAB for beginners

SAVING A SCRIPT FILEFILE

SAVE As..

enter name of file with .m extension

59

Page 60: An Introduction to MATLAB for beginners

Running a script file

typing its name in command window & pressing Enter

clicking Run icon on Editor window

60

Page 61: An Introduction to MATLAB for beginners

Input to a script file

1. Variable is defined & assigned value in the script file.

2. Variable is defined & assigned value in the command window.3. Variable is defined in script file, but a specific value is entered in the command window when the script file is executed.

1

2

3

GO61

Page 62: An Introduction to MATLAB for beginners

%this script file calculates the avg points scored in 3 %games game1=75;game2=93;game3=68;avg_point=(game1+game2+game3)/3

>>ex1

avg_points= 78.6667

62

Page 63: An Introduction to MATLAB for beginners

%this script file calculates the avg points scored in 3 %games .%values of game1,game2 & game3 is done in %command window.avg_point=(game1+game2+game3)/3

>>game1=75;>>game2=90;>>game3=68>>ex2avg_points= 78.6667 63

Page 64: An Introduction to MATLAB for beginners

%this script file calculates the avg points scored in 3 %games .%values of game1,game2 & game3 is assigned using %input command.game1=input(‘enter points scored in game1 : ’);game2=input(‘enter points scored in game2 : ’);game3=input(‘enter points scored in game3 : ’);avg_point=(game1+game2+game3)/3

>>ex2enter points scored in game1 : 75enter points scored in game2 : 93enter points scored in game3 : 68avg_points= 78.6667 64

Page 65: An Introduction to MATLAB for beginners

Initializing with Keyboard Input

• The input function displays a prompt string in the Command Window and then waits for the user to respond.

my_val = input( ‘Enter an input value: ’ );

in1 = input( ‘Enter data: ’ );

in2 = input( ‘Enter data: ’ ,`s`);

65

Page 66: An Introduction to MATLAB for beginners

Output Commands

• disp command displays o/p on the screen

or

• fprintf commandto display o/p(text & data) on the screen or save it to

a file

disp(name of a variable) disp(‘text as string’)

fprint(‘text typed in as string’)

66

Page 67: An Introduction to MATLAB for beginners

PLOTS

67

Page 68: An Introduction to MATLAB for beginners

Plotting with MATLAB MATLAB will plot one vector vs. another. The first one

will be treated as the abscissa (or x) vector and the second as the ordinate (or y) vector. The vectors have to be the same length.

MATLAB will also plot a vector vs. its own index. The index will be treated as the abscissa vector. Given a vector “time” and a vector “dist” we could say:

>> plot (time, dist) >> plot (dist)

plot(x,y)

68

Page 69: An Introduction to MATLAB for beginners

formating a plotThere are commands in MATLAB to "annotate" a plot to put on

axis labels, titles, and legends. For example:

>> % To put a label on the axes we would use: >> xlabel ('X-axis label') >> ylabel ('Y-axis label')

>> % To put a title on the plot, we would use: >> title ('Title of my plot')

>>%To put a text label in the plot,we would use:>>text(x,y,’text as string’)>>gtext(‘text as string’) % user specifies the position in figure window with mouse 69

Page 70: An Introduction to MATLAB for beginners

>> x = [0: pi/100: pi]; % [start: increment: end]

>> y = sin(x);

>> plot(x,y), title('Simple Plot')

70

Page 71: An Introduction to MATLAB for beginners

Matlab Graphics

x = 0:pi/100:2*pi;y = sin(x);plot(x,y)xlabel('x = :2\pi')ylabel('Sine of x')title('Plot of the Sine Function')

71

Page 72: An Introduction to MATLAB for beginners

plot command

plot(x, y, ‘line specifiers’ , ‘PropertyName’ , PropertyValue)

vector (optional) defines the style and color of line and markers

(optional) properties with values that can be used to specify the line width , marker’s size & edge, and fill colors.

72

Page 73: An Introduction to MATLAB for beginners

line specifiers

Line Style Specifier

Solid(default) -

Dashed --

Dotted :

dash-dot -.

Line color Specifier

Red r

Green g

Blue b

Cyan c

Magenta m

Yellow y

Black k

White w73

Page 74: An Introduction to MATLAB for beginners

line specifiers contd..

Marker Type Specifier

Plus sign +

Circle o

Asterisk *

Point .

Marker Type Specifier

Square S

Diamond d

Five-pointed star

p

Six-pointed star

h

74

Page 75: An Introduction to MATLAB for beginners

plot(x,y) a blue solid line (default)plot(x,y, ’r’) a red solid line connects the pointsplot(x,y, ’--y’) yellow dashed line connects the pointsplot(x,y, ’*’) points are marked with *(no line

between the points)

75

Page 76: An Introduction to MATLAB for beginners

Property Name and Property ValueProperty Name Possible Property Value

LineWidth( or linewidth)

A number in units of points(default 0.5).

MarkerSize( or markersize)

A number in units of points.

MarkerEdgeColor( or markeredgecolor)

Color specifiers typed as string

MarkerFaceColor( or markerfacecolor)

Color specifiers typed as string

76

Page 77: An Introduction to MATLAB for beginners

Plot of a Function

plot or fplot commandto plot a y=f(x)create a vector of values of xvector y is created with corrosponding values of f(x) using element-by-element calculations.once two vectors are created

plot(x,y)

77

Page 78: An Introduction to MATLAB for beginners

Plot of a Function contd…

eg: plot function y =3.5-0.5x cos(6x) for -2 ≤ x ≤ 4.

%script file that create plot of function% 3.5.^(-0.5*x).*cos(6*x)

x = [-2: 0.01: 4];y = 3.5.^(-0.5*x).*cos(6*x);plot(x,y)

78

Page 79: An Introduction to MATLAB for beginners

Plot of a Function contd…fplot command

plot function of form y=f(x) between specified limits

fplot( ‘function ‘ , limits, line specifiers)

[xmin,xmax]or

[xmin,xmax,ymin,ymax]79

Page 80: An Introduction to MATLAB for beginners

Multiple Graphs using plot command

t = 0:pi/100:2*pi;y1=sin(t);y2=sin(t+pi/2);plot(t,y1,t,y2)grid on

plot(x,y,u,v,t,h)

add grid lines to the plot

80

Page 81: An Introduction to MATLAB for beginners

Multiple Graphs using hold on, hold off command

•one graph is plotted 1st with plot command.•hold on command is typed.

this keeps the figure window with the 1st plot open,including the axis properties & formating•additional graphs drawn with plot command that follows.•each plot command creates a graph that is added to that figure.•hold off command stop this process.

81

Page 82: An Introduction to MATLAB for beginners

Multiple Graphs using line command

additional graphs (lines) can be added to plot that already exists.

line(x,y, ‘PropertyName’ ,PropertyValue)

x = [-2:0.01:4]y = 3*x.^3 – 26*x + 6;yd = 9*x.^2 – 26;plot(x,y,’linestyle’, ’-’ ,’color’,’b’)line(x,yd,’linestyle’, ’--’ ,’color’,’r’)

82

Page 83: An Introduction to MATLAB for beginners

Multiple Plots

t = 0:pi/100:2*pi;y1=sin(t);y2=sin(t+pi/2);subplot(2,2,1)plot(t,y1)subplot(2,2,2)plot(t,y2)

subplot(m , n , p)

83

Page 84: An Introduction to MATLAB for beginners

plots with logarithmic axis

•semilogy(x,y)•semilogx(x,y)•loglog(x,y)

84

Page 85: An Introduction to MATLAB for beginners

FORMATING A PLOT USING PLOT EDITOR

85

Page 86: An Introduction to MATLAB for beginners

click this button to start the plot

edit mode

use edit and insert to format

86

Page 87: An Introduction to MATLAB for beginners

Histograms

•plots that show distribution of data•overall range of a given set of data points is divided into smaller subranges(bins)•and the histogram shows how many data points are there in each bin

hist (y)

87

Page 88: An Introduction to MATLAB for beginners

>> y=[58 73 73 53 50 48 56 73 73 66 69 63 74 82 84 91 93 89 91 80 59 69 56 64 63 66 64 74 63 69];>> hist(y)>>

88

Page 89: An Introduction to MATLAB for beginners

Random Numbers

x=rand(100,1);stem(x);

hist(x,100)

89

Page 90: An Introduction to MATLAB for beginners

polar plots

To plot a function r = f(θ)

polar(theta,radius, ‘line specifiers ‘)

vector

90

Page 91: An Introduction to MATLAB for beginners

>> t=linspace(0,2*pi,200);>> r=3*cos(0.5*t).^2+t;>> polar(t,r)

91

Page 92: An Introduction to MATLAB for beginners

Graph Functions (summary)

•plot linear plot•stem discrete plot•grid add grid lines•xlabel add X-axis label•ylabel add Y-axis label•title add graph title•subplot divide figure window •figure create new figure window•pause wait for user response

92

Page 93: An Introduction to MATLAB for beginners

Scripts and Functions• There are two kinds of M-files:

– Scripts, which do not accept inputarguments or return output arguments. Theyoperate on data in the workspace.–Functions, which can accept inputarguments and return output arguments.Internal variables are local to the function.

93

Page 94: An Introduction to MATLAB for beginners

if/elseif/else Statement

>> A = 2; B = 3;>> if A > B 'A is bigger' elseif A < B 'B is bigger' elseif A == B 'A equals B' else error('Something odd is happening') endans =B is bigger

94

Page 95: An Introduction to MATLAB for beginners

switch Statement>> n = 8n = 8>> switch(rem(n,3)) case 0 m = 'no remainder' case 1 m = ‘the remainder is one' case 2 m = ‘the remainder is two' otherwise error('not possible') endm =the remainder is two

95

Page 96: An Introduction to MATLAB for beginners

For Loop

>> for i = 2:5

for j = 3:6

a(i,j) = (i + j)^2

end

end

>> a

a =

0 0 0 0 0 0

0 0 25 36 49 64

0 0 36 49 64 81

0 0 49 64 81 100

0 0 64 81 100 121

96

Page 97: An Introduction to MATLAB for beginners

while Loop

>> b = 4; a = 2.1; count = 0;>> while b - a > 0.01 a = a + 0.001; count = count + 1; end>> countcount = 1891

97

Page 98: An Introduction to MATLAB for beginners

Common OS Commands

•ls / dir provide a directory listing of the current directory

• pwd shows the current directory

98

Page 99: An Introduction to MATLAB for beginners

END

99