Sei sulla pagina 1di 23

Introduction to Matlab 3

Matlab Programming

Omed Ghareb Abdullah


Sulaimani University
College of Sciences
Physics Department

Matlab Programming
y Two Approaches
pp
y Coding in Command Window
y Good for short programs
y Commands must be re‐entered each time you run a 
simulation

y Coding with .m‐files
Coding with .m files
y Good for long programs
y Allows users to save all the commands written in the .m‐files

1
Matlab Programming
y Can be programmed just like Fortran

y Unlike Fortran there are NO data types to be declared

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

y To create a variable, simply use it

Use of M‐File
File →
New →
M-file

2
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

3
Writing a Program in MATLAB
Follow the steps written and the figure shown

y Open
O a mat (.m)
( ) file
fil in
i the
h MATLAB window
i d .

y Click on file menu → save → your file name.m to save a file


in MATLAB for further use .

y All the saved files can be accessed from the workspace


directory present in MATLAB folder.
folder

y Results of all the command written in .m editor can be seen in


command prompt if programs are written without semicolon in
.m editor.

.m Files RUN
y Once 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

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

4
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 window 9

Sample MATLAB program demonstrating matrix operations

10

5
Output of the
program on the
previous page.

11

Sample MATLAB program for Solving three simultaneous


equations

12

6
Output of the
program on the
previous page.

13

Examples
Write a MATLAB program to calculate the area of a
right 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 function


The following MATLAB function is useful for prompting the user
to enter inputs:
p
input (‘message’) – returns a value entered from the keyboard.

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

14

7
Solution
% Filename: RightTriangle.m
% Description: Calculate the area of a right triangle
% Prompt the user to enter the height and the base of the triangle
height=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 off triangle=%g',height);disp('meter');
fprintf('Height i l % ' h i h ) di (' ')
fprintf('Base of triangle=%g',base);disp('meter');
fprintf('Area of triangle=%g',area);disp('meter^2');

15

Flow Control
y Loop constructs
y if, else, and elseif
if  else  and elseif
y switch and case
y for 
y while 
y Control Constructs
y break (exit for or while)
y continue (next iteration in for and while)
y try – catch (debug)
y return (exit function)

16

8
If
The if statement evaluates a logical expression and executes a group
of statements when the expression is true. The optional elseif and else
keywords provide for the execution of alternate groups of statements.
A endd keyword,
An k d which
hi h matches
t h the
th if,
if terminates
t i t the th last
l t group off
statements. if (condition)

if (condition) statementT

statementT …
if (condition)
… elseif
statements
else F
statementF
… …
statementF
end … else

end statementF

end 17

If
single option two options

condition true condition false


evaluated evaluated

true false
statementT statementF
t t tF
statements

18

9
Example
height=input('Enter the height(in meters):');
if height>170
disp(’tall’)
elseif height<150
disp(’small’)
else
disp(’average’)
end

19

Example
A=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

10
Logical expressions
y Relational operators (compare arrays of same sizes)
ƒ == (equal to)
ƒ ~=    (not equal)  
< (less than)
ƒ <=    (less than or equal to)
> (greater than)
ƒ >=    (greater than or equal to)
y Logical operators (combinations of relational operators)
y & (and)
y | (or)
y ~ (not)
21

Logical Expressions
¾ Logical functions
¾ 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

11
Logical Expressions
isequal : True if arrays are numerically equal.
isequal
q ((A,B)
, ) : is 1 if the two arrays
y are the same size and
contain 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 expressions
if (x>=0) & (x<=10)
disp(‘x
disp( [0 10]’)
x is in range [0,10] )
[ ]
else 0 10
disp(‘x is out of range’)
end

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


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

12
True Table for Logical Operators
y 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 Decision
If a=-1, b=2, x=1, and y=‘b’, evaluate
A * b > 0 & b == 2 & x > 7 | ~(y > ‘d’)

26

13
Switch and Case
The 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
input_num=input('input number'); method = 3;
switch sign(input_num) switch (method)
case -1 case (1)
disp('negative'); disp('Method is linear')
case 0 case (2)
disp('zero');
p( ); disp('Method
p( is q
quadratic'))
case 1 case (3)
disp('positive'); disp('Method is cubic')
otherwise otherwise
disp('other value'); disp('Unknown method')
end end 27

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

General form: s=0
for
for index=initial: increment: limit
ii=1:3:11
1:3:11
statements
end s=s+i
end

28

14
For
for i = 1:m
f
for j = 1:n
1
H(i,j) = 1/(i+j)
end
end

29

Example
y MATLAB program to find the roots of  f ( x ) = 2 cos( x ) − 1

R
Result
l
% program to performs four
X=
% iterations of Newton’s Method
1.1111
X=.7
X=
for i=1:4
1.0483
X=X – (
(2*cos(X)-1)/(-2*sin(X))
( ) )/( ( ))
X=
end
1.0472
f ( x)
x = xo − X=
f ' ( x) 1.0472
30

15
While
The 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: for loop:

i=1; for i=1:10


while ii<=10
10 y(i)=i^2;
y(i) i 2;
y(i)=i^2; end
i=i+1;
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

16
Problem: a = 0; fa = 8;
b = 3; fb = -4;
Write
W it a program tot while b-a > eps
find the roots of the x = (a+b)/2;
equation: fx = x^3 - 5*x^2 + 2*x + 8;

f ( x) = x − 5 x + 2 x + 8
3 2
if sign(fx) == sign(fa)
a = x; fa = fx;
using Bisection
else
method in the
b = x; fb = fx;
interval [0,3].
end
end
disp('The Root is:');disp(x); 33

break & continue
break : Terminate execution of while or for loop.
continue : Pass control to the next iteration of
for or while loop.
count = 0; count = 0;
while count <= 10 while count < 10
count = count + 1 count = count + 1
if count == 5 if count == 5
break continue
end end
end end 34

17
a = 0; fa = 8;
Break b = 3; fb = -4;
while b-a > eps + b
The break statement x = (a+b)/2;
lets yyou exit early
y
from a for or while fx = x^3 - 5*x^2 + 2*x + 8;

loop. In nested loops, if fx == 0


break exits from the break;
innermost loop only. 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 ‐ end


clear
The general form of a try statement is:
try,
y a=input('positive number=');
statement, try
catch, if a>=0
statement, b=sqrt(a);
end
end
Normally, only the statements between the disp(b);
try and catch are executed. However, if an
error occurs while executing any of the catch
statements, the error is captured into lasterr,
and the statements between the catch and
end are executed. If an error occurs within disp('the number is negative')
the catch statements, execution stops unless
caught by another try...catch block. end 36

18
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 it 37

Results
1600

1400

1200

1000

800

600

400

200

0
0 5 10 15 20 25 30 35 40

38

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

y 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;
p ( ,y);
plot(x,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

20
Circuit Example
10 Ohms

X L = 2πfL

10V 3 uF
~ 1
XC =
10 mH
2πfC

V
Z = R 2 + ( X L − X C )2 I=
Z

41

RLC Series .m File
r=10;
l=0.01;
c=3*10^-6;
v=10;
for i=1:4000
f(i)=i;
xl(i)=2*pi*f(i)*l;
xc(i)=1/(2*pi*f(i)*c);
(i) 1/(2* i*f(i)* )
z(i)=sqrt(r^2+(xl(i)-xc(i))^2);
iz(i)=v/z(i);
end
plot(f,iz);
42

21
RLC series result
1

0.9 1 1
fo =
0.8 2π LC
0.7

0.6
f o = 918.99 Hz
0.5

0.4

0.3

0.2

0.1

0
0 500 1000 1500 2000 2500 3000 3500 4000

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
Z = R+
1
+ j 2πL It =
j 2πC ⎛ 1 ⎞
⎜⎜10 + + j * 2π * f * 0.01⎟⎟
⎝ j * 2π * f * 3 *10 −6

j is intrinsically −1 unless its redefined


44

22
Assignment

10 Ohms
3 uF 10 mH
10V
-

Write a matlab program to determine the frequency response of the


current across this RLC circuit.

1 1 1 V
It = I R + ( IC − I L )2
2 = + j 2πC + I=
Z R j 2πL Z
45

23

Potrebbero piacerti anche