Chapter Three
Programming Using MATLAB
And Numerical Applications
3.1 Scripts and functions:
m.files : they are files contain programs and has a specified name describe its
purpose. If you type its name on the command window, MATLAB will
perform all orders contained by that m.files.
How to create m.file?:
Click on File menu
Choose new m.file
Save the m.file with a name.
Write a program and save it.
To call that program, write its name in the command window and
press enter
The MATLAB will perform all operations in the m.file.
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
Function name & Number of inputs and outputs
* Description of the function and its operation.
* It takes several lines.
* This description appears only in the Help.
* Each line must begin with % mark to denote that is
a description.
The main program that describing the function
beginning with the inputs and ending with the
outputs
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.
On the command window,
>> t=[3 1 4];
>> z=mohamed(t) (you can use any variable symbols)
z=
2.6000
>> u=[2 4 1;5 0 1]
u=
2 4 1
5 0 1
>> z=mohamed(u)
z=
2.4000
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.
We have 2 inputs and 5 outputs
operations.m
function [y1,y2,y3,y4,y5]=operations(P,Q)
% It is a function has 2 inputs, each input
% is a polynomial. And 5 outputs, the first
% one is the multiplication of them, the
% second and third are the result and remainder
% of dividing P over Q, the fourth is the
% derivative of the first, and the fifth is
% the roots of the second.
y1=conv(P,Q);
[y2,y3]=deconv(P,Q);
y4=polyder(P);
y5=roots(Q);
Inputting data technique in m.files:
ABC.m
D=input('what are the days: ')
T=input('what are the temp: ')
plot(D,T,'g+',D,T,'-'),grid on
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
3.2 Relational and Logical Operators
Relational operators
MATLAB has six relational operators to make comparison between arrays. These
operators are shown in the following table.
Relational Operator Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to
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.
* We may nest if statements as shown by the following example.
if logical expression 1
statement group 1
if logical expression 2
statement group 2 Start
end
end
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
The elseif statement
* When more that one action can occur based on more than one logical statement
we can use the elseif statement along with the if statement.
* The general form of that statement is
if logical expression 1 Start
statement group 1
elseif logical expression 2
statement group 2
else
statement group 3 Logical False
end Expression 1
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
3.4 Control Loops
A loop is a structure for repeating a calculation a number of times. Each repetition
of the loop is a pass. MATLAB uses two types of loops
the For loop when the number of passes is known.
the while loop when the looping process must terminate when a specified
condition is satisfied and thus the number of passes is not known.
3.4.1 For Loops Start
The general form of the For Loop
for loop variable = m:s:n Statement
Statement
end
The expression m:s:n specifies
the vector that containing the True
values that the loop variable Increment k by s k>n?
will take through each pass of
the loop. False
Statement
End
Statements
following the
End statement
8
Example (1):
Find the output from the following two programs
Program1.m
for i=1:5
x(i)=i/2
end
>> program1
x=
0.5000
x=
0.5000 1.0000
x=
0.5000 1.0000 1.5000
x=
0.5000 1.0000 1.5000 2.0000
x=
0.5000 1.0000 1.5000 2.0000 2.5000
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):
Calculate the series y = Σ (3n +1) for n = 1,3,5,……,51
series.m
y=0;
for n=1:2:51
term=3*n+1;
y=y+term;
end
y
>> series
y=
2054
9
Example (3):
Calculate the series y = Σ (3n +1) for n = 2 3 5 7 10 15
series2.m
n=[2 3 5 7 10 15];
y=0;
for i=1:6
term=3*n(i)+1;
y=y+term;
end
y
>> series2
y=
132
3.4.2 While Loops
* The while loop is used when the looping process terminates because a specified
condition is satisfied, thus the number of passes is not known
* The basic form of the while loop is as follow
while logical expression
statement
end
* The operation of the while loop can be summarized by the following flowchart
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
3.4.3 Break Order
The break order is an order contained in an if statement and is related with a
certain logical statement or condition, if it is satisfied, the break occurs.
Occurrence of break means:
Stop looping
Go outside any outer loop containing this order.
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)
On the command window
>> Breakorder
The Vector x is [1 2 3 4 5]
x=
1 2 3 4 5
z=
1.0000 0.5000 0.3333 0.2500 0.2000
y=
2.2833
>> 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.
3.5. Numerical Analysis Applications.
Now we will introduce some numerical applications that is achieved by MATLAB
programming such as
Numerical differentiation
Numerical integration
Solving of system of linear equations
Solving of nonlinear equations.
3.5.1 Numerical differentiation
Polynomial Derivatives
We have introduced before the order polyder that differentiate the polynomial
functions
If p1 and p2 are two polynomials, you can get the derivative of the which will be
also a polynomial
D = polyder(p1) gives the derivative of p1
D = polyder(p1 , p2) gives the derivative of the convolution between p1 and p2
[num,dem]= polyder(p1 , p2) gives the numerator and denominator coefficients of
the function p1 / p2
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
We can make a program to calculate the derivative at each Y1 Y3
point according to that formula used. Y2
X
X1 X2 X3
Central difference method. m
x=input('what are the values of the independent variable: ');
y=input('what are the values of the dependent variable: ');
n=length(x); h=x(2)-x(1);
for i=2:n-1
yd(i-1)=(y(i+1)-y(i-1))/(2*h);
end
subplot(2,1,1) , plot(x,y,'ko')
subplot(2,1,2) , plot(x(2:n-1),yd,'k+')
on the command window
>> Central difference method
what are the values of the independent variable: 0:0.1:5
what are the values of the dependent variable: cos(x)
Backward Difference estimate
The derivative may also calculated according to the following formula
dy/dx |x1 = (y2 – y1) / (x2 – x1)
Y
= (y2 – y1) / h
There is a function in the MATLAB that gives the
successive differences of a vector Y1 Y3
diff (x) = [x(2)–x(1) x(3)–x(2) …….] Y2
We can also make program to calculate the derivative X
at each point according to that formula used. X1 X2 X3
Backward Difference estimate. m
x=input('what are the values of the independent variable: ');
y=input('what are the values of the dependent variable: ');
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+')
try it at the command window.
Note: the central difference method is more accurate than the backward difference
method.
3.5.2 Numerical Integration
Trapezoidal method Y
Area = 0.5 h (y1 + y2) + 0.5 h (y2 + y3) + 0.5 h (y3 + y4)
+ ….. + 0.5 h (yn-1 + yn)
Area = 0.5 h (y1 + 2 y2 + 2 y3 + …. + yn)
Y1 Y3
Y2
We can also make a simple program to calculate
the integration using this method
X
Trapezoidal.m X1 X2 X3
x=input('What are the values of the independent variable: ');
y=input('What are the values of the dependent variable: ');
n=length(x);
h=x(2)-x(1);
Area=(h/2)*(2*sum(y)-y(1)-y(n))
On the command window
>> Trapezoidal
What are the values of the independent variable: 0:0.1:5;
What are the values of the dependent variable: cos(x)
Area =
-0.9581
Simpson’s Rule
Area = (h / 3) (y1 + 4 y2 + 2 y3 + 4 y4 + 2 y5 + …. + yn)
The following program evaluates the Simpson’s Rule
Simpson.m
x=input('what are the values of the independent variable: ');
y=input('what are the values of the dependent variable: ');
n=length(x);
h=x(2)-x(1);
Area=y(1)+y(n);
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
On the command window
>> Simpson
what are the values of the independent variable: 0:0.1:5;
what are the values of the dependent variable: cos(x)
Area =
-0.9589
Note that there is a small different in area calculated by two methods.
3.5.3 System of Linear Equations
Assume the following system
x + y + z = 3.5
-2x +5z = -1.5
6y – 5z = 3.5
It is required to solve this system of linear equations. There are several methods to
solve this system of linear equations
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
3.5.4 Solving of Nonlinear Equations:
Nonlinear equations are the equation which is not of the first order like:
F(x) = x2 + 3x – 1 or G(x) = 4x4 – 1 or H(x) = ex + cos(x) – 1
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.
Newton Raphson Method
Assume initial condition xo and apply the following formula
xn+1 = xn – (f(xn) / f ' (xn))
Example:
Solve the following equation x + x5 = 5 Using the Newton Raphson method
x + x5 = 5
x + x5 – 5 = 0
F(x) = x + x5 – 5 = 0 Then, F ' (x) = 1 + 5x4
xn+1 = xn – (F(xn) / F ' (xn))
Let xo = 1
n xn F(xn) F ' (xn) xn+1
0 1 -3 6 1.5
1 1.5 4.0938 26.3125 1.3444
2 1.3444 0.7365 17.3346 1.3019
3 1.3019 0.0425 15.3655 1.2992
4 1.2992 0.00017 15.2438 1.2992
5 1.2992
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.
(5) Rewrite the following statements to use only one if statement.
if x < y
if z < 10
w=x*y*z
end
end
(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
(8) Use a loop in MATLAB to determine how long it take to accumulate
1,000,000 $ in a bank account if you deposit 10,000 $ initially and 10,000 $ at
the end of each year, the account pays 6 % annual interest.
(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
The given values for the resistance and voltages are:
R1 = 5 Ω, R2 = 100 Ω, R3 = 200 Ω, R4 = 150 Ω and R5 = 250 Ω
V1 = 100 volts and V2 = 50 volts.
Form the given data in the form of matrices and the use MATLAB to solve that
linear equations to get the current in each branch.
(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
(11) Write a program to calculate one solution for the equation
(x + x5 – 5 )1/2 / (x3 – 6 ) = 0
Using any technique.
(12) Write a program to calculate :
X = 1/a – 1/2a + 1/3a – 1/4a + ………… – 1/100a
For values of a = -5, -3, -1, 1, 3, …50
(13) Without using loops, generate the vector
x = [1 1/2 1/3 1/4 1/5 1/6 … 1/100].
(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