Lecture-02 Programming Using MATLAB
Lecture-02 Programming Using MATLAB
Example:
Prog1.m
y=x.^3-5*x.^2+6
z=sqrt(y.^2-1)
L=sum(z)
n=max(size(y))
On the command window
>> x=[1:4];
>> prog1
y=
2 -6 -12 -10
z=
1.7321 5.9161 11.9583 9.9499
L=
29.5563
n=
4
Notes:
It is preferred that the name of the m.file describe its
operations.
The variable x that you depend on it in the first order must be
predetermined and exists in the workspace.
Any changes you make in the m.file, you must save it before
retyping its name in the command window.
1
Creating functions:
As we mentioned in chapter one, there are defined variables in the MATLAB, but
sometimes we need a new function to use which doesn’t exist internally in the
MATLAB, so it is possible to create functions using the following procedure.
open a new m.file
make a function according to the following structure
save the m.file with the same name of the created function
Example:
Create a function that takes the length of any vector or takes the number of rows of
any matrix and adds 10 to it then divides the result by 5 and name that function by
your name.
mohamed.m
Function y=mohamed(x)
% it is a function created by myself
% it takes the length of the input vector
% and adds 10 to it then it divides the
% result by 5. If the input is a matrix
% it takes the number of rows and
% perform the same operations
[m,n]=size(x);
if m = = 1
y=(n+10)/5;
else
y=(m+10)/5;
end
2
Note that,
The first line contains the function name and show that this
function is one input one output function.
There are six lines begins with % that means that they are
description of the function.
The last six lines are the program describing the function.
Example:
Make a function that read two polynomials and multiply them, dividing them, find
the derivative of the first and the roots of the second.
3
On the command window
>> ABC
what are the days: [1:4]
D=
1 2 3 4
what are the temp: [21 20 24 23]
T=
21 20 24 23
The result of a comparison using the relational operators is either 0 (if the
comparison is false) or 1 (if the comparison is true) and the result can be used as a
variable.
For example: if x = 2 and y = 5, typing z = (x < y) returns the value z = 1
And typing u = (x = = y) returns to the value u = 0
When the relational operators is used to compare arrays, it compares the arrays on
an element by element basis. The arrays being compared must have the same
dimensions. The only exception occurs when comparing an array to a scalar. In
that case all elements in the array are compared to the scalar.
Example:
>> x =[6 3 9];
>> y =[14 2 9];
>> z =(x<y)
z=
1 0 0
>> z =(x~=y)
z=
4
1 1 0
>> z =(x>8)
z=
0 0 1
>> z =x(x>y) ( This order finds all elements of x that are greater than the
z= corresponding elements in y )
3
>> z =x(x>8) ( This order finds all elements of x that are greater than 8 )
z=
9
Logical operators
MATLAB has three logical operators which are sometimes called Boolean
operators. These operators perform element by element operations. These
operators are shown in the following table.
Operator Name Definition
~A returns an array of the same dimensions as
~ NOT A: the new array has ones when A is zero and
zeros where A is nonzero
A & B returns an array of the same dimensions
as A and B: the new array has ones where both
& AND
A and B have nonzero elements and zeros
where either A or B is zero
A | B returns an array of the same dimensions as
A and B: the new array has ones where at least
| OR
one element in A or B is nonzero and zeros
where A and B are both zero
Example
>> x =[5 -3 0 0];
>> y =[2 4 0 5];
>> a =[4 3 12 0];
>> z =(x>y)&a
z=
1 0 0 0
>> z =(x>y)|a
z=
1 1 1 0
>> z =(x>y)&(x>a)
z=
1 0 0 0
>> z =~a
z=
0 0 0 1
5
3.3 Conditional statements
The if statement
* The If statement provides a condition, if it is satisfied, a certain operation will be
performed, and if it is not satisfied, the operation will be canceled.
* The basic form of If statement
if logical expression
statement
end
* Every if statement must have an accompanying end statement
* A space is required between the if and the logical expression which may be a
scalar, a vector or a matrix.
* The logical expression may be compound expression, the statement may be a
single command or a series of commands for example if x and y have scalar
values
z = 0;w = 0
if (x>=0) & (y>=0)
z = sqrt (x) + sqrt (y)
w = log (x) – 3* log(y)
end
Note that we combine two logical expressions. The fist is x >=0 and the second
is y>=0.
Logical False
Expression
True
Statement
End
6
The else statement
* When more that one action can occur as a result of a decision we can use the else
statement along with the if statement.
* The basic structure for the use of the else statement is
if logical expression
Start
statement group 1
else
statement group 2
end
Logical False
Expression
True
Statement Statement
End
Logical False
True Expression 2
Statement 1
True
Statement 2 Statement 3
End
7
Example:
Write the following function using MATLAB y
x2 + y2 in quadrant 1
Z = x2 + 3 in quadrant 2 x2 + 3 x2 + y2
No operation in quadrant 3 x
x–y–5 in quadrant 4
assumes that x = 0, y = 0 belongs tow positive region. No x–y–5
Where x and y are real integers. operation
if (x>=0)&(y>=0)
z=x^2+y^2
elseif (x<0)&(y>=0)
z=x^2+3
elseif (x<0)&(y<0)
disp('the two coordinates are negative')
else
z=x+y-5
end
Note that the order disp('the two coordinates are negative') displays the words
between the two quotations as it is
End
Statements
following the
End statement
8
Example (1):
Program2.m
for i=1:5
x(i)=i/2;
end
x
>> program2
x=
0.5000 1.0000 1.5000 2.0000 2.5000
Example (2):
series.m
y=0;
for n=1:2:51
term=3*n+1;
y=y+term;
end
y
>> series
y=
2054
9
Example (3):
>> series2
y=
132
Start
Logical False
Expression
True
Statement (which
increment the loop
variable)
End
Statement
following the
end statement
10
Example (1):
Calculate the series y = Σ (3n +1) for n = 1, 3, 5,… 51 using while loop.
serieswhile.m
n=1;y=0;
while n<52
term=3*n+1;
y=y+term;
n=n+2;
end
y
>> serieswhile
y=
2054
Example (2):
Find the maximum number that its factorial is less than 10100
Factorial.m
n=1;
while prod(1:n)<1e100
n=n+1;
end
number=n
>> Factorial
number =
70
Example:
For the vector x of length n, calculate the series y = Σ (1 / xi) for i = 1 to n
But if the vector x contains zero, cancel the terms after this zero
Breakorder.m
x=input('The Vector x is ')
n=length(x);
for i=1:n
if x(i) = = 0,break,end
z(i)=1/x(i);
end
11
z
y=sum(z)
>> Breakorder
The Vector x is [1 2 0 4 5]
x=
1 2 0 4 5
z=
1.0000 0.5000
y=
1.5000
As we saw; in the first case the break doesn’t occur because no element equal to
zero, but in the second case there is a zero so the break occurs.
12
Central Difference method (Three point formula)
If we have two vectors x and y, where y is a function of x
dy/dx |x2 = (y3 – y1) / (x3 – x1)
Y
= (y3 – y1) / 2h
Where h is the step of changing x
X
X1 X2 X3
13
n=length(x); yd=diff(y)./diff(x);
subplot(2,1,1) , plot(x,y,'ko')
subplot(2,1,2) , plot(x(2:n),yd,'k+')
Trapezoidal.m X1 X2 X3
Area =
-0.9581
Simpson’s Rule
Area = (h / 3) (y1 + 4 y2 + 2 y3 + 4 y4 + 2 y5 + …. + yn)
Simpson.m
14
for i=2:n-1
if rem(i,2)==0
a=4;
else
a=2;
end
Area=Area+(a*y(i));
end
Area=(h/3)*Area
Area =
-0.9589
Kramer Method
The system of equations can be put in the form AX = B
Where A = the coefficient matrix and X is the unknown matrix and B is right hand
side matrix
1 1 1 3.5 x
A = -2 0 5 & B = -1.5 &X= y
0 6 -5 3.5 z
solving this problem using Kramer Rule will be according the following steps
Δ =|A|
Δ1 = | A | substituting the 1st column of A by the vector B
Δ2 = | A | substituting the 2nd column of A by the vector B
Δ3 = | A | substituting the 3rd column of A by the vector B
x = Δ1 / Δ , y = Δ2 / Δ , z = Δ3 / Δ
15
Kramer.m
a=[1 1 1;-2 0 5;0 6 -5];
b=[3.5;-1.5;3.5];
d=det(a);
a1=a;a2=a;a3=a;
a1(:,1)=b;
a2(:,2)=b;
a3(:,3)=b;
d1=det(a1);d2=det(a2);d3=det(a3);
x=d1/d , y=d2/d , z=d3/d
On the command window
>> Kramer
x=
2
y=
1
z=
0.5000
All these equation can be solved using iterative methods, there are more than one
method can be used, the most commonly used method is the Newton Raphson
Method.
16
Newton.m
x=1;
f=x+x^5-5;
while abs(f) > 1e-05
fd=1+5*x^4;
x=x-(f/fd);
f=x+x^5-5;
end
x
On the command window
>> newton
x=
1.2992
fzero function
You can use the fzero function to get the zero of the function of single variable
which is denoted by x. One form of its syntax is fzero('function' , xo) where
function is string containing the name of the function and xo is the user guess for
the zero. The fzero function returns a value of x that is near xo
Example
>> fzero('cos',2)
ans =
1.5708
This means that the solution of (cos (x) = 0) near the value 2 is x = 1.5708
To use this function to find the zeros of more complicated function, it is more
convenient to define the function in a function file
Example:
F1.m
function y=f1(x)
y=x+2*exp(-x)-3;
On the command window.
>> fzero('f1',-0.5)
ans =
-0.5831
>> fzero('f1',3)
ans =
2.8887
you can get different zeros according to the initial guess.
17
PROBLEMS
(1) Suppose that x = 6. Find the results of the following operations by hand and
use MATLAB to check your results.
(a) z = (x<10) (b) z = (x = = 10)
(c) z = (x>= 4) (d) z = (x ~ = 7)
(2) For the arrays x and y given below, use MATLAB to find all elements in x
that are greater than the corresponding elements in y.
x = [-3 0 0 2 6 8] and y = [-5 -2 0 3 4 10]
(3) The array price given below contains the price in dollars of a certain stock
over 10 days. Use MATLAB to determine how many days the price was above
20$.
Price = [19 18 22 21 25 19 17 21 27 29]
(4) The array price_A, price_B and price_C given below contain the price in
dollars of three stocks over 10 days.
(a) Use MATLAB to determine how many days the price of stock A was
above both the price of stock B and the price of stock C.
(b) Use MATLAB to determine how many days the price of stock A was
above either the price of stock B or the price of stock C.
(6) An ideal diode is used in a half wave rectifier circuit as shown in the figure.
The voltage VL across the load RL is given by:
VL = V S if VS > 0 and VL = 0 if VS = 0
Suppose that the supply voltage is
VS = 3 e-t/3 sin (π t) volts where t is in seconds.
Write a MATLAB program to plot the voltage VL versus t for t varies from 0 to 10
seconds.
Diode
VS RL VL
18
(7) The following m.file is a function file (linspace) for the creation of linearly
spaced vector. The program does not work properly due to at least four
mistakes. Find them then rewrite the program with errors after correction.
linspace.m
linspace (d1,d2,n)=y;
% linspace is linearly spaced vector
% linspace (x1,x2) generates a row vector
of 100 elements linearly
% equally spaced points between x1 and x2
%
% linspace (x1,x2,n) generates n points between
x1 and x2
% see also LOGSPACE
if nargin = 2
n = 100;
end
y=[d1+(0:n-2)*(d2-d1)/(n-1) d2];
end
return
(9) The equations describing the circuit shown in the figure are:
I1 I2 I3
- V1 + R 1 I 1 + R 4 I 4 = 0 R1 R2 R3
- R4 I4 + R2 I2 + R5 I5 = 0 I4 I5
+ +
- R5 I5 + R3 I3 + V2 = 0 R4 R5
V1 V2
I1 = I 2 + I 4 – –
I2 = I 3 + I 5
(10) Consider the following script. Fill in the lines of the table shown below with
the values that would be displayed immediately after the while statement if
you run the script file. Write in the values of the variables each time the while
statement is executed. You might need more or fewer lines in the table. Then
use MATLAB to check your answer.
K = 1; b = -2; x= -1; y = -2;
while k<=3
19
k, b, x, y
y = x^2 - 3;
if y<b
b = y;
end
x = x +1;
k = k +1;
end
Pass k b X y
First
Second
Third
Fourth
Fifth
(14) Generate a matrix that each element is a function of its number of row and
number of column as follow
A (i , j) = i3 + j3 .
20