03 matlab programming

23
1 Matlab Programming Introduction to Matlab 3 Omed Ghareb Abdullah Sulaimani University Sulaimani University College of Sciences College of Sciences Physics Department Physics Department 1 Matlab Programming Two Approaches Coding in Command Window Good for short programs Commands must be reentered each time you run a simulation Coding with .mfiles Coding with .m files Good for long programs Allows users to save all the commands written in the .mfiles 2

Upload: omed-ghareb

Post on 18-Nov-2014

645 views

Category:

Documents


3 download

DESCRIPTION

Lecture (3): Matlab Programming - Sulaimani University - College of Science - Physics Department

TRANSCRIPT

Page 1: 03 Matlab Programming

1

Matlab Programming

Introduction to Matlab 3

Omed Ghareb AbdullahSulaimani UniversitySulaimani UniversityCollege of SciencesCollege of SciencesPhysics DepartmentPhysics Department

1

Matlab ProgrammingTwo Approachespp

Coding in Command WindowGood for short programsCommands must be re‐entered each time you run a simulation

Coding with .m‐filesCoding with .m filesGood for long programsAllows users to save all the commands written in the .m‐files

2

Page 2: 03 Matlab Programming

2

Can be programmed just like Fortran

Matlab Programming

Can be programmed just like Fortran

Unlike Fortran there are NO data types to be declared

Variables can support Real, Integer, String, and Imaginary numbersImaginary numbers

To create a variable, simply use it

3

Use of M‐File

File → New → M-file

4

Page 3: 03 Matlab Programming

3

Use of M‐File

Click to create a new M-File

• Extension “.m”

• A text file containing script or function or program to run

5

Use of M‐File

Save file as Denem430.m

If you include “;” at the

end of each statement,

result will not be shown

immediately

6

Page 4: 03 Matlab Programming

4

Writing a Program in MATLABFollow the steps written and the figure shown

O ( ) fil i h MATLAB i dOpen a mat (.m) file in the MATLAB window .

Click on file menu → save → your file name.m to save a filein MATLAB for further use .

All the saved files can be accessed from the workspacedirectory present in MATLAB folderdirectory present in MATLAB folder.

Results of all the command written in .m editor can be seen incommand prompt if programs are written without semicolon in.m editor.

7

.m Files RUNOnce your program has been saved as a .m file it can beOnce your program has been saved as a .m file it can be run by either pressing F5 in the editor or by typing the file name in the command window

Other .m files maybe be run from within different .m files

8

Page 5: 03 Matlab Programming

5

Simple Examples% Example1.m

clear all

x=5;

y=3;

z=3*x^2+5*y;z 3 x 2 5 y;

z% character denotes the start of a comment

lines that end with a “;” are simply run

lines that do not end with a “;” are run and results displayed on command window9

Sample MATLAB program demonstrating matrix operations

10

Page 6: 03 Matlab Programming

6

Output of the program on the previous page.

11

Sample MATLAB program for Solving three simultaneous equations

12

Page 7: 03 Matlab Programming

7

Output of the program on the previous page.

13

ExamplesWrite a MATLAB program to calculate the area of a right triangle after prompting the user to enter valuesright triangle after prompting the user to enter values for the base and height of the triangle (in meter). Display the input values and the output (with units).

Using MATLAB’s INPUT functionThe following MATLAB function is useful for prompting the user to enter inputs:pinput (‘message’) – returns a value entered from the keyboard.

Example: Height = input(‘Enter the height of the triangle’);

14

Page 8: 03 Matlab Programming

8

Solution% Filename: RightTriangle.m% Description: Calculate the area of a right triangle% Description: Calculate the area of a right triangle% Prompt the user to enter the height and the base of the triangleheight=input('Enter the height of the right triangle (in meters):');base=input('Enter the base of the right triangle (in meters):');area=0.5*base*height;disp('The Results');f i f('H i h f i l % ' h i h ) di (' ')fprintf('Height of triangle=%g',height);disp('meter');fprintf('Base of triangle=%g',base);disp('meter');fprintf('Area of triangle=%g',area);disp('meter^2');

15

Flow ControlLoop constructs

if  else  and elseifif, else, and elseifswitch and casefor while 

Control Constructsbreak (exit for or while)break (exit for or while)continue (next iteration in for and while)try – catch (debug)return (exit function)

16

Page 9: 03 Matlab Programming

9

IfThe if statement evaluates a logical expression and executes a group of statements when the expression is true. The optional elseif and elsekeywords provide for the execution of alternate groups of statements. A d k d hi h t h th if t i t th l t fAn end keyword, which matches the if, terminates the last group of statements.

if (condition)

statements

if (condition)

statementT

if (condition)

statementT

elseif

F…

end

else

statementF…

end

statementF…

else

statementF…

end 17

Ifsingle option two options

false

condition

evaluated

truestatementT

condition

evaluated

true false

t t tFstatements

statementT statementF

18

Page 10: 03 Matlab Programming

10

Example

height=input('Enter the height(in meters):');height=input('Enter the height(in meters):');if height>170

disp(’tall’)elseif height<150

disp(’small’)else

if height>170disp(’tall’)

elseif height<150disp(’small’)

else disp(’average’)

enddisp(’average’)

end

19

ExampleA=input(‘A=');B=input(‘B=');B input( B );if A > B

disp(‘A greater than B’)elseif A < B

disp(‘A less than B’)elseif A = = B

disp(‘A equal to B’)else error(‘Unexpected situation’)end

20

Page 11: 03 Matlab Programming

11

Logical expressionsRelational operators (compare arrays of same sizes)

(equal to)== (equal to)~=    (not equal)  < (less than)<=    (less than or equal to)> (greater than)>=    (greater than or equal to)Logical operators (combinations of relational operators)& (and)| (or)~ (not)

21

Logical functionsisequal (Test if arrays are numerically equal)

Logical Expressions

isequal (Test if arrays are numerically equal)isempty  (Test if array is empty)any  (Test for any nonzeros)all (Test to determine if all elements are nonzero)xor  (Exclusive or)

xor(A,B) is the logical symmetric difference of elements A and B. The result is one where either A or B, but not both, is nonzero. The result is zero where A and B are both zero or nonzero. A and B must have the same dimensions.

22

Page 12: 03 Matlab Programming

12

Logical Expressionsisequal : True if arrays are numerically equal.

isequal (A,B) : is 1 if the two arrays are the same size and q ( , ) ycontain the same values, and 0 otherwise.

isempty : True for empty array.

isempty(A) : returns 1 if X is an empty array and 0 otherwise.

all : True if all elements of a vector are nonzero.

all (A) : returns 1 if none of the elements of the vector are zero. Otherwise it returns 0.

any: True if any element of a vector is nonzero.

any (A) : returns 1 if any of the elements of the vector are non-zero. Otherwise it returns 0 23

Logical expressionsif (x>=0) & (x<=10)

disp(‘x is in range [0 10]’)

if (x < = -1.0 | x > = 1.0) y = 0.

end

disp( x is in range [0,10] )

else

disp(‘x is out of range’)

end

y

0 10[ ]

end

if (x > -1.0 & x < 0.) y = 1. + x

end

if (x > = 0. & x < 1.0) y = 1.- x

end-1 1

x

1

24

Page 13: 03 Matlab Programming

13

True Table for Logical Operators

Order of priority of logical operators

x y ~x x&y x|y

T T F T T

T F F F T

F T T F T

F F T F F

25

Example of a Complex DecisionIf a=-1, b=2, x=1, and y=‘b’, evaluate

A * b > 0 & b == 2 & x > 7 | ~(y > ‘d’)

26

Page 14: 03 Matlab Programming

14

Switch and CaseThe switch statement executes groups of statements based on the value of a variable or expression. The keywords case and otherwise delineate the groups. Only the first matching case is executed. There must be an end to match the switch

method = 3;

switch (method)

case (1)

disp('Method is linear')

case (2)

disp('Method is quadratic')

input_num=input('input number');

switch sign(input_num)

case -1

disp('negative');

case 0

disp('zero'); p( q )

case (3)

disp('Method is cubic')

otherwise

disp('Unknown method')

end

p( );

case 1

disp('positive');

otherwise

disp('other value');

end 27

ForThe for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates the statements.

General form:

for index=initial: increment: limit

s=0

for i=1:3:11

statementsend

i 1:3:11

s=s+i

end

28

Page 15: 03 Matlab Programming

15

Forfor i = 1:m

f j 1for j = 1:n

H(i,j) = 1/(i+j)

end

end

29

ExampleMATLAB program to find the roots of  1)cos(2)( −= xxf

R l% program to performs four

% iterations of Newton’s Method

X=.7

for i=1:4

X=X – (2*cos(X)-1)/(-2*sin(X))

X =

1.1111

X =

1.0483

Result

( ( ) )/( ( ))

endX =

1.0472

X =

1.0472)(')(

xfxfxx o −=

30

Page 16: 03 Matlab Programming

16

WhileThe while loop repeats a group of statements an indefinite number of times under control of a logical condition. A matching end delineates the statements.

while loop:

i=1;while i<=10

for loop:

for i=1:10y(i)=i^2;while i 10

y(i)=i^2;i=i+1;

end

y(i) i 2;end

31

Problem:

Write a MATLAB program to find the largest number, in which its factorial is available.

k=1;

while prod(1:k)~=Inf,

k=k+1;

end

disp([‘Largest factorial in Matlab:’,num2str(k-1)]);

32

Page 17: 03 Matlab Programming

17

a = 0; fa = 8;

b = 3; fb = -4;

W it t

Problem:

while b-a > eps

x = (a+b)/2;

fx = x^3 - 5*x^2 + 2*x + 8;

if sign(fx) == sign(fa)

a = x; fa = fx;

Write a program to find the roots of the equation:

using Bisection

825)( 23 ++−= xxxxf

else

b = x; fb = fx;

end

end

disp('The Root is:');disp(x);

using Bisection method in the interval [0,3].

33

continue : Pass control to the next iteration ofbreak : Terminate execution of while or for loop.

break & continue

continue : Pass control to the next iteration of for or while loop.

count = 0;

while count < 10

count = count + 1

count = 0;

while count <= 10

count = count + 1

if count == 5

continue

end

end

if count == 5

break

end

end 34

Page 18: 03 Matlab Programming

18

BreakThe break statement lets you exit early

a = 0; fa = 8;

b = 3; fb = -4;

while b-a > eps + b

x = (a+b)/2;y yfrom a for or whileloop. In nested loops, break exits from the innermost loop only.

fx = x^3 - 5*x^2 + 2*x + 8;

if fx == 0

break;

elseif sign(fx) == sign(fa)

a = x; fa = fx;

else

b = x; fb = fx;

end

end

disp('The Root is:');disp(x); 35

try – catch ‐ endThe general form of a try statement is:

try,

clear

a=input('positive number=');ystatement,

catch,statement,

end

try

if a>=0

b=sqrt(a);

end

Normally, only the statements between thetry and catch are executed. However, if anerror occurs while executing any of thestatements, the error is captured into lasterr,and the statements between the catch andend are executed. If an error occurs withinthe catch statements, execution stops unlesscaught by another try...catch block.

disp(b);

catch

disp('the number is negative')

end36

Page 19: 03 Matlab Programming

19

Loop Example% Example2.m - Loop

clear all

for i=1:40

x(i)=i;

y(i)=i^2;y(i) i 2;

end

plot(x,y);

plot(x,y) creates a 2D plot and displays it37

Results1600

600

800

1000

1200

1400

0 5 10 15 20 25 30 35 400

200

400

38

Page 20: 03 Matlab Programming

20

An Easier WayWhen dealing with large amounts of data, loops in When dealing with large amounts of data, loops in Matlab can be very inefficient

Matlab allows mathematical operations to be performed directly on a entire array or matrix (This is called a vector operation as opposed to a scalar operation)

39

Modified Loop Example% Example3.m - Loop

x=linspace(1,40,40);

%Linspace creates an array 1 to 40 of 40 elements

y=x.^2;

plot(x,y);p ( ,y);

In Matlab matrix/array math .^ .* and ./ performs those operations on a element by element basis

While ^ * / when performed on a matrix will attempt to perform matrix math

40

Page 21: 03 Matlab Programming

21

Circuit Example10 Ohms

10V 3 uF

10 mH

~

fLX L π2=

fCXC π2

1=

ZVI =22 )( CL XXRZ −+=

41

RLC Series .m Filer=10;

l=0.01;

c=3*10^-6;

v=10;

for i=1:4000

f(i)=i;

xl(i)=2*pi*f(i)*l;

(i) 1/(2* i*f(i)* )xc(i)=1/(2*pi*f(i)*c);

z(i)=sqrt(r^2+(xl(i)-xc(i))^2);

iz(i)=v/z(i);

end

plot(f,iz);42

Page 22: 03 Matlab Programming

22

RLC series result

0.9

1

f 11

0.4

0.5

0.6

0.7

0.8 LCfo

121π

=

Hzfo 99.918=

0 500 1000 1500 2000 2500 3000 3500 40000

0.1

0.2

0.3

43

RLC Series .m File%Example4.m - RLC

ff=linspace(1,4000,4000);

it=10./(10+(1./(j.* 2.*pi.*ff.*3.*10^-6))+(j.* 2.*pi.*ff.*0.01));

plot(ff,abs(it));

V

j is intrinsically unless its redefined1−

⎟⎟⎠

⎞⎜⎜⎝

⎛++

=

− 01.0**2*10*3**2*

110 6 fjfj

VIt

ππ

LjCj

RZ ππ

221

++=

44

Page 23: 03 Matlab Programming

23

Assignment

10O

hms

10 mH3 uF10V+

-

Write a matlab program to determine the frequency response of the current across this RLC circuit.

LjCj

RZ ππ

21211

++=ZVI =22 )( LCRt IIII −+=

45