0% found this document useful (0 votes)
11 views49 pages

‏لقطة شاشة ٢٠٢٤-١٢-٠٢ في ٢.٣٩.٢٧ م

Uploaded by

ma1427511
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views49 pages

‏لقطة شاشة ٢٠٢٤-١٢-٠٢ في ٢.٣٩.٢٧ م

Uploaded by

ma1427511
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Taif University

College of Engineering

802201-3
Introduction to Computer Programming

Student’s Workbook

Student Academic ID

Student Name

Instructor Name

Spring 2023

Version: 2023.8.29.1
Sheet 1
Objectives
1. Create a student account on mathworks.com (See MATLAB Installation Guide)
2. Install MATLAB on your laptop (Homework)
3. Use MATLAB to compute simple arithmetic expressions
Problems
You may use MATLAB online until the offline version is installed on your laptop.
1. Write the following mathematical expressions in MATLAB
Mathematical Expression MATLAB Expression Value
(a) 4 +3 4^2 + 3 19

(b) √16 sqrt(16) 4

(c) 4 4^(2+5) 16384

(d) 5 −4 5^3-4 121


16 − 4
(e) (16-4)/(12+1) 0.9231
12 + 1
120
(f) 120/(2+4) 20
2+4
1
(g) 1/4^3 0.015625
4
3
(h) (3/5)^2 0.36
5
(i) 5𝜋 + 4 5*pi+4 19.708
𝜋
(j) 3 cos 3*cos(pi/3) 1.5
3
(k) 𝑒 Exp(3) 20.086

(l) 5 ln 𝑒 5*log(exp(2)) 10
𝜋
(m) 3 + 4 cos 3^2+4*cos(pi/3) 11
3
(n) √1 − 3𝜋 Sqrt(1-3*pi) 2.9025i

(o) 3𝜋 + 4 𝑒 3*pi+4*exp(2) 38.981

(1 − 0.2 )
(p) (1-0.2^10)/(1-0.2) 1.2500
1 − 0.2

1
Sheet 2
Objectives
1. Interpret MATLAB arithmetic expressions and evaluate them
2. Use variables to store numbers and substitute in formulas

Problems
1. Without a calculator find the value of each of the following MATLAB
expressions, then verify your answer using MATLAB
MATLAB Expression Mathematical Expression Value
4
(a) 1+4 / 2^2 1+ 2
2

6
(b) 6/2*3 ×3
2

4
(c) 1+4/5 1+
5

3
(d) 1+2+3 / 1+2+3 1+2 +2+3
1

3−4
(e) (3 – 4) /2
2

3
(f) 3^3/3*3 ×3
3

8
(g) 5 * 8/2 ^3 5×
2

5
(h) 4*5/2^sqrt(4) 4×
2√

2. Use variables to write MATLAB commands to solve each of the following


problems:
(a) Find the average of two numbers 𝑥 = 7 and 𝑥 = 19.

>> x1 = 7;

>> x2 = 19;

>> (x1+x2)/2
ans = 13

2
(b) Calculate the time, 𝑡, it takes a car traveling at a uniform speed 𝑣 = 120 𝑘𝑚/ℎ to
travel a distance of 𝑑 = 450 𝑘𝑚 (Hint: 𝑣 = 𝑑/𝑡 )

Rewrite the formula as t = d / v

>> d = 450;

>> v = 120;

>> t = d/v

t = 3.75

(c) Calculate the time, 𝑡, a particle takes to hit the ground if it was stationary at height
𝑑 = 100 𝑚 and started falling freely under gravitational acceleration of
𝑔 = 9.8 𝑚/𝑠 (Hint 𝑑 = 𝑔 𝑡 )

Rewrite the formula as

>> g = 9.8;

>> t = sqrt(2*d/g)

t = 4.5175

(d) Follow the steps below to calculate the equivalent resistance of the two resistors 𝑅 =
6Ω and 𝑅 = 3Ω when the two resistors are connected in series and when they are
connected in parallel:

i. Store the values of resistances 𝑅 and 𝑅 in two variables.

>> R1 = 6;

>> R2 = 3;

3
ii. Calculate the equivalent resistance in the series case using the rule
𝑅 =𝑅 +𝑅

>> RS = R1 + R2

Rs = 9

iii. Calculate the equivalent resistance in the parallel case using the rule
𝑅 𝑅
𝑅 =
𝑅 +𝑅

>> RP = R1*R2/(R1+R2)

Rp = 2

(e) Find the value of the expression:


.
𝑔 𝑒 −1
𝑡+ ,
𝑘 𝑘
where 𝑘 = 0.05, 𝑔 = 9.81 and 𝑡 = 3

>> k = 0.05;

>> g = 9.81;

>> t = 3;

>> g/k*(t+(exp(-0.05*t)-1)/k)

ans = 42.018

(f) Calculate the area of a circle 𝐴 = 𝜋𝑟 , where the radius is 𝑟 = 3.5 𝑚

>> r=3.5;

>> A=pi*r^2

A = 38.48

4
(g) Find the roots of a quadratic equation in the general form 𝑎𝑥 + 𝑏𝑥 + 𝑐 = 0 given 𝑎, 𝑏
±√
and 𝑐. Namely, find the roots 𝑥 = , in each of the following cases:

i. 𝑎 = 1; 𝑏 = 3; 𝑐 = 2;

>> a = 1;

>> b = 3;

>> c = 2;

>> ( -b-sqrt(b^-4*a*c))/(2*a)

ans = -2

>> ( -b+sqrt(b^-4*a*c))/(2*a)

ans = -1

ii. 𝑎 = 1; 𝑏 = 2; 𝑐 = 2;

>> a=1; b=2; c=2;

>> ( -b-sqrt(b^-4*a*c))/(2*a)

ans = -1-j

>> ( -b+sqrt(b^-4*a*c))/(2*a)

ans = -1+j

iii. 𝑎 = 1; 𝑏 = 2; 𝑐 = 1;

>> a=1; b=2; c=2;

>> ( -b-sqrt(b^-4*a*c))/(2*a)

ans = -1

>> ( -b+sqrt(b^-4*a*c))/(2*a)

ans = -1

5
3. Given the following definition of functions f (N,t) and g(N,t), evaluate each
function for each combination of variable values to fill in the table below.

1000 𝑒 1
𝑓(𝑁, 𝑡) = + ,
𝑁+1 100

√𝑡𝑁 − 3 + 𝑁𝑡 (𝑁 − 1)
𝑔(𝑁, 𝑡) =
|𝑡 − 𝑁𝑡 |
𝑁 = 2, 𝑁 = 2, 𝑁 = 2, 𝑁 = 6, 𝑁 = 6,
𝑡 = 0.2 𝑡 = 0.3 𝜋 𝜋
𝑡 = sin 𝑡 = sin 𝑡 = √5
3 3
𝑓(𝑁, 𝑡) 13.343 30.0100 250.0100 60.2779 1.7857e+04

𝑔(𝑁, 𝑡) 9.883 6.6270 5.4923 9.9249 6.1918

Complete below the MATLAB statements you used for calculating the first two columns of the
previous table.

>> N = 2;

>> t = 0.2

>>

f = 13.343

>>

g = 9.883

>> t = 0.3

>> 30.0100

>> 6.6270

6
Sheet 3 - Arrays
Objectives
1. Construct vectors and matrices to store arrays of numbers
2. Measure array dimensions using size function
3. Extracting elements and sub-arrays from existing arrays
4. Use colon notation to construct arrays with arithmetic sequences of numbers.

1. Write MATLAB statements to perform tasks (a) through (f) on vectors A, B, C,


and D.
A=[7 5 9] B=[3,-1, 10.5] C=[1+2j;2+3j;3+5j] D=[4
3
2]

Task Statement Result

(a) Create matrix a (2×3) >> a=[A; B]


from A and B vectors. a = 7 5 9
3 -1 10.5

(b) Create matrix b (3×2) >> b=[C D] b = 1+2i 4


from C and D vectors 2+3i 3
3+5i 2

(c) Create a matrix c (1×6) >> c=[A B]


from A and B vectors c = 7 5 9 3 -1 10.5

(d) Create a matrix d (6×1) >> d=[C;D]


d = 1+ 2i
from C and D vectors 2+ 3i
3+ 5i
4+ 0i
3+ 0i
2+ 0i

7
(e) Find the size of matrices a, b, c, and d using size() built-in function

>> size(a)

ans = 2 3

>> size(b)

ans = 3 2

>> size(c)

ans = 1 6

>> size(d)

ans = 6 1

(f) Write a MATLAB statement to calculate the sum of the first element in vector A with
the second element in the vector C

>> A(1) +C(2)

ans = 9 + 3i

2. Write MATLAB statements to perform tasks (a) and (b) on matrices X and Y
1 2 3 2 3 4
X= 4 5 6 & Y= 5 6 7 ,
7 8 9 9 7 8
Task Statement Result

(a) Create a 6×3 matrix by >> [X; Y] ans = 1 2 3


vertically appending the 4 5 6
two matrices. 7 8 9
2 3 4
5 6 7
9 7 8

(b) Create a 3×6 matrix by >> [X Y]


ans = 1 2 3 2 3 4
horizontally appending the 4 5 6 5 6 7
two matrices 7 8 9 9 7 8

8
3. Write MATLAB statements to perform the following tasks:
(a) Create a matrix, 𝐴, of 5×5 random values between 0 and 1.

>> A=rand(5,5) or A=rand(5)


(b) Extract the element at the intersection of the second row and the third column

>> A(2,3)
(c) Extract all the elements of the second row and store the value in variable 𝑡.

>> t = A(2,:)
(d) Extract the first two columns of matrix A and store the result in variable 𝑥

>> x = A(:, 1:2)

(e) Extract a 3×3 matrix from the top-right corner of matrix A and store it in variable 𝑦

>> y = A(1:3, 3:5)


(f) Construct column vector 𝐵 of size 25×1 which contains all the columns of A stacked
one over the other.

>> B=[A(:,1); A(:,2); A(:,3); A(:,4); A(:,5)]


(g) Delete the second row of matrix A.

>> A(2,:) = [ ]
(h) Try to delete the first element from 𝑡 (defined in part c of this problem), and the first
element from 𝑥 (defined in part d of this problem). Comment on the result.

>> t(1) = [ ], can be occurred.

X(1,1) = [ ], error can not occurred.

4. Write the following arithmetic sequences using MATLAB colon notation and
verify your answer using MATLAB:
Arithmetic Sequence MATLAB Colon Notation
(a) (50,60,…,150) 50:10:150

(b) (1, 3, 5, …, 99) 1:2:99

(c) (3,2.9,2.8,…,2) 3:-0.1:2

9
Sheet 4 – Built-in Functions
Objectives
1. Convert numbers to character arrays and vice versa.
2. Use built-in functions

1. Use MATLAB Command Window to find the result of the following MATLAB
expressions
MATLAB Expression Value

(a) x=char(65) 'A'

(b) char(x+1) ‘B’

(c) char(66) + 'A' 131

(d) char([ 72 , 101, 108, 108, 111]) ‘Hello’

(e) ['Hi ', 'there'] Hi there

(f) ['The temperature is ', 48] 'The temperature is 0'

2. Write MATLAB statements to perform the following tasks:

(a) Create a vector, 𝑥, with 50 random integer numbers between 5 and 15.

>> x =5+ floor(11*rand(50,1))

(b) Find the minimum value of 𝑥,

>> min(x) ans=5

(c) the maximum value of 𝑥,

>> max(x) ans=15

(d) the mean value of 𝑥

>> mean(x) ans= 10.7800

(e) the standard deviation of the elements of 𝑥.

>> std(x) ans= 3.4004

10
3. Use MATLAB built-in functions to perform the following tasks:
(a) Find the absolute (positive) value of −5, i.e., |−5|.

>> abs(-5)

ans = 5

(b) Approximate the number 9.25 to the nearest integer.

>> round(9.25)

ans = 9

(c) Find the remainder of dividing 517 by 7.

>> mod(517,7) or rem(517,7)

ans = 6

11
Sheet 5 - Scripts
Objectives
1- Create script files, save them to storage, and run them
2- Locate existing script files and open them for editing
3- Use input built-in function to ask the user for input values
4- Use disp and mat2str to display formatted output

Problems
1. The below script calculates the area, A, of a rectangle and its perimeter, P,
given the length and width are already stored in variables L and W,
respectively. Save the script to a file called ‘rect.m’, then write MATLAB
commands to use the script to calculate the area and perimeter of a rectangle
with length 12 and width 9.
rect.m

A=L*W
P=2*(L+W)

Command Window

>> L = 10;

>> W = 6;

>> rect obtained results A=60 P=32

2. Write a script to ask the user to input the radius 𝑟 of a closed cylinder and its
height ℎ, then calculates and displays the cylinder base area 𝐵 = 𝜋𝑟 , its
volume 𝑉 = 𝜋𝑟 ℎ and its surface area 𝐴 = 2𝜋𝑟ℎ + 2𝜋𝑟 .
cylinder.m
r=input('Enter cylinder raduis ? ');
h=input('Enter cylinder height ? ');
B = pi*r^2
V = pi*r^2*h

12
3. Write a script that asks the user to input three numbers 𝑎, 𝑏, and 𝑐 then
calculates the sum 𝑠, the product 𝑝 and the average 𝑚 of the 3 numbers and
finally displays the output “The sum is ” followed by the value of 𝑠, and
similarly for 𝑝 and 𝑚.
add.m
a=input('Enter a number a ? ');
b=input('Enter a number a ? ');
c=input('Enter a number c ? ');
s = a + b + c;
p = a*b*c;
disp(['The sum is ', mat2str(s)])
disp(['The product is ', mat2str(p)])

4. Write a MATLAB script called ‘box_vol.m’, which asks the user to input the
three dimensions of a box in vector form, e.g., [3, 2, 4], then displays the
volume of the box, V. (Hint: the volume of a box is calculated using the
formula 𝑉 = 𝐿 ⋅ 𝑊 ⋅ 𝐻)
box_vol.m
x=input('Enter box dimensions ? ');
L=x(1);
W=x(2);
H=x(3);
V = L*W*H

13
5. Write a script to ask the user to input the coefficient of a quadratic equation
in the general form 𝑎𝑥 + 𝑏𝑥 + 𝑐 = 0 and print out the roots
±√
𝑥= .
solve2.m
a=input('Coefficient a ? ');
b=input('Coefficient b ? ');
c=input('Coefficient c ? ');
x1=(-b-sqrt(b^2-4*a*c))/(2*a)
x2=(-b+sqrt(b^2-4*a*c))/(2*a)
Use your program to find the roots of the following equations
-0.5000
i. 6𝑥 − 𝑥 − 2
x1 = x2 = 0.6667
-0.5000 0.2500
ii. 8𝑥 + 2𝑥 − 1
x1 = x2 =
-2.5000 3
iii. 2𝑥 − 𝑥 − 15
x1 = x2 =
6. A dummy of mass 𝑚 kg is used in a crash test to investigate the safety of a
new car. The car approaches a solid barrier at speed 𝑣 m/s. It crashes into the
barrier and stops suddenly. In the crash test, the passenger compartment
comes to rest in time 𝑡 seconds. Write a MATLAB script called "calc_force",
which asks the user to input 𝑚, 𝑣, and 𝑡, then calculates the total force, 𝐹, on
the dummy during the crash test, given using the formula:
𝐹⋅𝑡 = 𝑚⋅𝑣

calc_force.m
m=input('Enter mass ? ');
v=input('Enter speed ? ');
t=input('Enter time ? ');
F= m*v/t

14
7. A room with rectangular shaped floor is to be covered with tiles. The
dimensions of the floor are L × W 𝑚 and a tile is s × s 𝑚 . Write a MATLAB
script which asks the user for the dimensions of the floor and the side length
of the tile, then displays the number of tiles needed to cover the floor in the
following format.
We need 24 tiles
(Assume leftover fragments of the tiles are not reused.)
𝑠

𝑠 1 2 3 4 5 6

7 8 9 10 11 12 𝑊

13 14 15 16 17 18

19 20 21 22 23 24
𝐿
tiles.m
L=input('Enter mass ? ');
W=input('Enter speed ? ');
S=input('Enter time ? ');
LS=ceil(L/S); WS=ceil(W/S);
NS=LS*WS;
disp(['We need ', mat2str(NS), ' tiles'])

15
Sheet 6 – Conditional Statements
Objectives
1. Use conditional if-statement.
2. Express simple and compound conditions.
3. Use nested if-statements.
Problems
1. Write a script which asks the user to enter a number then displays the square
root of the input, if the input is a non-negative number. Otherwise, the script
displays the message ‘Negative numbers have no real square roots’.
sqrt1.m
clc
N=input('Enter a number ? ');
if N>0
disp(sqrt(N))
else
disp('Negative numbers have no real square roots')
end

2. Write a script that, given the value 𝑥, sets 𝑦=2 when 𝑥 ≥ 2 or 𝑦 = 1 if 𝑥 < 2.
set_y.m
x=input('Enter a number ? ');
if x>=2
y=2
else
y=1
end

16
3. Write a MATLAB script, which asks the user to enter a number, 𝑛, between -
100 and 100, and then displays the message ‘n to the power n = ’ followed by
the value of 𝑛 . When 𝑛 ∉ [−100,100], the script displays the message ‘number
out of range’.
NpowerN.m
n=input('Enter a number between -100 and 100 ');
if n>=-100 && n<=100
disp([mat2str(n), ' to the power ' mat2str(n),
...
' = ', mat2str(n^n)])
else
disp('number out of range')
end

4. Write a script which takes the value of 𝑥 and displays the value of 𝑓(𝑥) defined
as follows:
1, 𝑥<2
𝑓(𝑥) = 2, 2≤𝑥≤5
3, 𝑥>5
piecewise_f.m
x=input('Enter a number ');
if x<2
y=1
elseif x>=2 && x<=5
y=2
else
y=3
end

17
5. Write a script to ask the user for the mark 𝑥, then display the corresponding
student grade, i.e., A+, A, B+, B, etc., based on the following table:
𝑥 < 60 𝐹 60 ≤ 𝑥 < 65 𝐷 65 ≤ 𝑥 < 70 𝐷
70 ≤ 𝑥 < 75 𝐶 75 ≤ 𝑥 < 80 𝐶 80 ≤ 𝑥 < 85 𝐵
85 ≤ 𝑥 < 90 𝐵 90 ≤ 𝑥 < 95 𝐴 95 ≤ 𝑥 𝐴

grade.m
clc
m=input('Enter a student mark ');
if m<60
G='F'
elseif m<65
G='D'
elseif m<70
G='D+'
elseif m<75
G='C'
elseif m<80
G='C+'
elseif m<85
G='B'
elseif m<90
G='B+'
elseif m<95
G='A'
else
G='A+'
end

18
6. Write a script, which asks the user to provide three numbers, 𝑎, 𝑏 and 𝑐, then
uses conditional statements to find the median of the three numbers. For
instance, if 𝑎 ≤ 𝑏 ≤ 𝑐, then 𝑏 is the median. Any one of the three numbers, 𝑎, 𝑏
or 𝑐 could be the median.
med3.m
a=input('a= '); b=input('b= '); c=input('c= ');
if (a<=b && a>=c) || (a>=b && a<=c)
m=a;
elseif (b>=a && b<=c) || (b<=a && b>=c)
m=b;
else
m=c;
end
disp(['The median is: ', mat2str(m)])

19
7. Write a MATLAB script, which receives as input three numbers and displays
the most repeated input value as well as how many times it was repeated. For
example, if the input is 5, 5, and 4, the script should display the message ‘5
occurred 2 times’. If, for example, the input is 1, 4, and 4, the output should
be ‘4 occurred 2 times’. If all inputs are different, the script should display the
message ‘values are unique’.
repeated.m
clc
a=input('a= '); b=input('b= '); c=input('c= ');

if a==b && a==c


disp([mat2str(a) ' Occurred 3 times'])
elseif a==b || a==c
disp([mat2str(a) ' Occurred 2 times'])
elseif b==c
disp([mat2str(b) ' Occurred 2 times'])
else
disp('Values are unique')
end

20
8. Write a MATLAB script which receives three input numbers and displays two
values: First, how many of the input numbers are greater than 10. Second,
how many input numbers are less than or equal to 10. For example, if the
inputs are 11, 7, 5, your program should display 1 2.
compare10.m
a=input('a= '); b=input('b= '); c=input('c= ');
if a>10 && b>10 && c>10
disp([3 0])
elseif a>10 && b>10 && c<=10
disp([2 1])
elseif a>10 && b<=10 && c>10
disp([2 1])
elseif a<=10 && b>10 & c>10
disp([2 1])
elseif a<=10 && b<=10 & c>10
disp([1 2])
elseif a<=10 && b>10 & c<=10
disp([1 2])
elseif a>10 && b<=10 & c<=10
disp([1 2])
else
disp([0 3])

end

21
9. Write a MATLAB script, which receives three input numbers and displays in
descending order the largest two absolute differences between any pair of
numbers. For example, if the input is 2, 5, and 9, your program should display
7 and 4, which are the absolute differences between 2 and 9 and between 5
and 9, because both absolute differences are greater than the absolute
difference between 2 and 5.
LargestDiffs.m
a=input('a= '); b=input('b= '); c=input('c= ');

d1=abs(a-b); d2=abs(a-c); d3=abs(b-c);


if d1>=d2 && d1>=d3
if d2>=d3
disp([d1 d2])
else
disp([d1 d3])
end
elseif d2>=d1 && d2>=d3
if d1>=d3
disp([d2 d1])
else
disp([d2 d3])
disp([d2 d3])
end
else
if d1>=d2
disp([d3 d1])
else
disp([d3 d2])
end
end

22
Sheet 7 – For Loop
Objectives
1. Use for-loop to repeat a task a given number of times
2. Use for-loop to compute series summation
3. Use for-loop to iterate through a vector of elements
4. Use nested for-loop to construct 2-D matrices.
5. Use break to stop looping
Problems
1. Use repeated addition to find the sum of integers from 1 to 50
sum1to50.m
S = 0;
for i=1:50
S = S + i;
end
disp(S)

2. Use for loop to find the sum of squares of the odd positive numbers
smaller than 20, i.e., 𝑺 = 𝟏𝟐 + 𝟑𝟐 + ⋯ + 𝟏𝟗𝟐
sumsq.m
S = 0;
for i=1:2:20
S = S + i^2;
end
disp(S)

3. Given the following script


X=input('X= ');
for i=1 :5
if (i>X)
disp('Taif');
end
end
How many times is the word 'Taif' displayed in each of the following cases?
Input X=0 X=3 X=7

Number of outputs 5 2 0

23
4. Write the output of the following MATLAB script for n=0, n=1, and n=5.
n= input(' Enter value of n = ');
t=0;
for k=0:n
t=t+k^3;
disp(t)
end
disp(['Total = ' , num2str(t)])

Input n=0 n=1 n=5

Outputs 0 0 0

Total = 0 1 1

Total = 1 9

36

100

225, Total = 225


Find the mathematical formula for 𝑡 calculated by the above script

𝑡= 𝑘

5. Consider the following MATLAB script. The user should enter the number
of courses then enter the score of each course. Then the program displays the
sum and the average of the scores. Correct one error in each line marked by (X)
and complete the missing statements in the lines marked with (M)
Mark Script Correction
(X) n=input['Enter the number of courses']; ()

(M) T=0;

(X) For i=(1:n)

(X) d=input([Score of course #',num2str(i),' = ']); D, ‘

T=T+D;
(M) end

(X) disp(['The total is : ',num2str(T)]; )

(X) disp(['The average is : ',num2str(T/d)]); T/n

24
6. Answer the following questions about the MATLAB script below:
Script Question Answer
m= 0; How many times does the 5
for i=1:5 program ask for input?
disp(m)
x= input('x:'); How many times does the 6
if x > m program display output?
m=m+2;
elseif x<m If the inputs are taken from 0
m=m-1; the sequence 1, 3, 2, 4, 3, 5,
end 4, 6, 5, … what are ALL the 2
end outputs?
4
disp(m)
3

7. Write a MATLAB script file that, given the value of N, prints out the
elements of the following N × N matrix element by element in row-major order
(all elements of the first row are printed out before any element of the second
row).
𝟏 𝟐 𝟑 … 𝑵
⎡𝟐 𝟑 𝟒 … 𝑵+𝟏 ⎤
⎢ ⎥
𝑨 = ⎢𝟑 𝟒 𝟓 … 𝑵+𝟐 ⎥
⎢⋮ ⋮ ⋮ ⋱ ⋮ ⎥
⎣𝑵 𝑵 + 𝟏 𝑵 + 𝟐 … 𝟐𝑵 − 𝟏⎦
8. For instance, if N=4, the program should display the following sequence of
numbers, one in each line: 1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, and 7.
dispmat.m
N=input('N= ');
for i=1:N
for j=1:N
A(i,j)=i+j-1
end
end

25
9. Given the value of 𝒙 and 𝒏, write a program using for-loop to calculate the
value of 𝐲 according to the following formula:
𝒏
𝒙𝒌
𝒚=
𝐬𝐢𝐧(𝒌) + 𝟐
𝒌 𝟎

sumsq1.m
x=input('x= '); n=input('n=')
S=0;
for k=0:n
S = S + x^n/(sin(k)+2);
end
disp(S)
Test Case: if x=2, and n=10, then y= 5.9608e+03

10. Write a MATLAB script to calculate the value of S


𝟏𝟎 𝒏

𝑺= 𝒏𝒎
𝒏 𝟓 𝒎 𝟎

sumsq2.m
S = 0;
for n=5:10
S1 = 0;
for m=0:n
S1 = S1 + n^m;
end
S = S + S1;
end

The value of S is 1.1567e+10

26
11. Use for-loop to write a script which takes a number 𝒏 and displays a
message describing 𝒏 as prime or not prime. Note that a prime number is
defined as a positive integer which has only two factors, itself and 1. For
instance, if 𝒏=17, your program should display the message ’17 is prime’
check_prime.m
n=input('Enter a number ? ');
b=' is prime';
for i=2:n-1
if rem(n,i)==0
b=' is not prime';
break
end
end
disp([mat2str(n), b])

12. Use nested for-loops to display all prime numbers in the interval [1000,
1100].
range_primes.m
for n=1000:1100
b=1;
for i=2:n-1
if rem(n,i)==0
b=0;
break
end
end
if b==1
disp([mat2str(n), ' is prime'])
end
end

27
13. The sequence of triangles shown in the figure is defined as follows:
i. Triangle #1 is a right-angle triangle with sides 3, 4, and 5,
ii. Triangle #2 is right-angle with sides 4, 5, and √𝟒𝟐 + 𝟓𝟐, …
iii. Triangle #𝒏 is right-angle with sides 𝒂𝒏 , 𝒃𝒏 , and 𝒄𝒏 such that
𝒂𝒏 < 𝒃𝒏 < 𝒄𝒏 , 𝒂𝒏 = 𝒃𝒏 𝟏, and 𝒃𝒏 = 𝒄𝒏 𝟏, i.e., the two sides of the right angle
of any triangle in the sequence are equal to the hypotenuse and the
largest side of the right angle of the preceding triangle in the sequence.
Use for-loop to write a MATLAB script which calculates the area of a square
drawn on the hypotenuse of the 𝒏th triangle in the sequence, for any value of
𝒏 given by the user. (Hint: this problem is closely related to the Fibonacci
sequence.)

fib_triangles.m
n=input('Enter n= ');
a=3; b=4;
for i=1:n
c=sqrt(a^2+b^2);
a=b;
b=c;
end
disp(['The square area= ', mat2str(c^2)])

28
14. Write a script which, given the value of 𝒙, 𝒏 and 𝒎, calculates the value of
S, where
𝒏 𝒎
𝒏 𝒌𝒙
𝑺= 𝒙 𝒆
𝒊 𝟏 𝒌 𝟏

Note that the 𝒙 𝒏 ∑𝒎


𝒌 𝟏𝒆
𝒌𝒙
is a common factor of all the terms of the outer
summation ∑𝒏𝒊 𝟏(… ), therefore 𝑺 = 𝒙 𝒏 ∑𝒎
𝒌 𝟏𝒆
𝒌𝒙 ∑𝒏𝒊 𝟏(𝟏) = 𝒏 𝒙 𝒏 ∑𝒎
𝒌 𝟏𝒆
𝒌𝒙

sumsq3.m
x=input('x = '); n=input(' n= '); m=input('m
= ');
S = 0;
for i=1:n
S1 = 0;
for k=1:m
S1 = S1 + exp(-k*x);
end
S = S + S1*(x^(-n));
end
disp(['The total= ', mat2str(S)])

Test Case: if x=2, n=5, and m=8, then S = 0.02446

29
Sheet 8 – Array Operations
Objectives
1. Work with different vector forms
2. Use element-by-element operators on vectors and matrixes.
3. Solve systems of linear equations using matrix operations.

Problems
1. Write a MATLAB function called ‘to_row’ which converts any given vector
to row form. The following examples demonstrate the function use cases.
Hint: use ‘error’ function to display the error message.
Command Result
>> to_row(1:4) ans = 1 2 3 4
>> to_row([1;2;3;4]) ans = 1 2 3 4
>> to_row([1,2;3,4]) Error using to_row
Input not a vector

to_row.m
%Set x value before excuting the script
% the result be stored in y
[m n]=size(x);
if m>1 && n==1
y=x';
elseif m==1 && n>=1
y=x;
else
error('Input not a vector')
end
disp(y)

30
2. The dot product of vectors a and b is defined as
𝒏

𝒂⋅𝒃= 𝒂𝒊 𝒃𝒊 = 𝒂𝟏 𝒃𝟏 + 𝒂𝟐 𝒃𝟐 + ⋯ + 𝒂𝒏 𝒃𝒏
𝒊 𝟏

where n is the dimensionality of the space and a = [a1, a2, ..., an], b= [b1, b2,
..., bn]. Write a MATLAB function called ‘dot_product’ which returns the dot
product of two given vectors, 𝒂 and 𝒃 of the same length n. Use ‘to_row’
defined in Problem 1 to align the input vectors. If the input vectors have
mismatching lengths, the function should display an error message ‘Input
vector length mismatch’. Test your function in the following cases:

Command Result
dot_product([1 2 3], [4 5 6]) ans = 32
dot_product([1 2 3], [4;5;6]) ans = 32
dot_product([1; 2; 3], [4;5;6]) ans = 32
dot_product([1; 2; 3], [4,5,6]) ans = 32
dot_product([1 2 3], [4 5 6 7]) Error using dot_product
Input vector length mismatch
dot_product([1 2; 3 4], [5 6;7 8]) Error using to_row
Input not a vector

Error in dot_product (line …)


a=to_row(a);

dot_product.m
x=input('Enter the first vector: ');
to_row % script of problem 9.1
a=x;
x=input('Enter the second vector: ');
to_row % script of problem 9.1
b=y;
if length(a)==length(b)
P=sum(a.*b);
disp(['Dot product = ', mat2str(P)])
else
error('Input vector length mismatch')
end

31
4. Given the equations:
𝟐𝒙 − 𝟑𝒚 + 𝒛 = 𝟏, 𝒙 − 𝒚 − 𝒛 = 𝟓, 𝟒𝒙 + 𝒚 + 𝟐𝒛 = 𝟏𝟎
a. Rewrite the equations in the form 𝐴𝑣 = 𝑏
𝟐 −𝟑 𝟏 𝒙 𝟏
𝟏 −𝟏 −𝟏 𝒚 = 𝟓
𝟒 𝟏 𝟐 𝒛 𝟏𝟎

b. Define 𝐴 and 𝑏 in MATLAB


>> A= [ 2 -3 1;1 -1 -1;4 1 2];
>> b= [1;5;10];

c. Write MATLAB statement to find the determinant of matrix A using MATLAB. Based on
the result, is matrix A invertible?
>> det(A)
ans = 21

d. Write MATLAB command to find the inverse of matrix A.


Inv(A)

e. Write MATLAB script to find the values of 𝑥, 𝑦 and 𝑧.


A= [ 2 -3 1;1 -1 -1;4 1 2];
b= [1;5;10];
v=inv(A)*b;
x=v(1)
y=v(2)
z=v(3)

32
5. In Euclidean space, a vector is a geometric object that has a magnitude
and a direction. The magnitude of a vector 𝒂 is denoted by ‖𝒂‖. The dot
product of two vectors 𝒂 and 𝒃 is defined by
𝒂 ⋅ 𝒃 = ‖𝒂‖ ‖𝒃‖ 𝐜𝐨𝐬 𝜽
where 𝜽 is the angle between 𝒂 and 𝒃. Use the ‘dot_product’ function
defined in Problem 2 to write a function that calculates the angle (in
radians) between two given vectors 𝒂 and 𝒃.
angle_between.m
clc
x=input('Enter the first vector: ');
to_row % script of problem 9.1
a=y;
x=input('Enter the second vector: ');
to_row % script of problem 9.1
b=y;

if length(a)==length(b)
P=sum(a.*b);
disp(['Dot product = ', mat2str(P)])
else
error('Input vector length mismatch')
end
prod1=sqrt(sum(a.*a))
prod2=sqrt(sum(b.*b))
theta_degree=acos(P/(prod1*prod2))*180/pi

33
Sheet 9 - Plotting
Objectives
1. Use vector operations for plotting functions
2. Customize graph plots

1. Given that x=1:0.1:2, plot each of the following functions versus x


f(x) statement
x=1:0.1:2;
𝒙𝟑 + 𝟑𝒙𝟐 + 𝟏 f1=x.^3+3*x.^2+1; plot(x,f1)

(𝐬𝐢𝐧 𝒙)𝟐 f2=sin(x).^2; plot(x,f2)

𝐬𝐢𝐧𝟐 𝒙 + 𝒙 𝐜𝐨𝐬𝟒 𝒙
f3=sin(x).^2+sin(x).^4; plot(x,f3)
𝒙
𝟐
𝒙 +𝟏 f4=x./(x.^2+1); plot(x,f4)
𝐜𝐨𝐬 𝒙
𝟏 + 𝐬𝐢𝐧 𝒙 f5=cos(x)./(1+sin(x)); plot(x,f5)
2. Create a script to plot the function
𝒕 𝒕
𝒙(𝒕) = 𝒆 𝑻 𝐬𝐢𝐧
𝒙𝟎
for 50 points in the interval 0 ≤ 𝑡 ≤ 25, where 𝑇 = 5 and 𝑥 = 4. Add grid,
proper title, and axis labels to the plot.

plot1.m
clc; clear
t=linspace(0,25,50);
T=5; x0=4;
f1=exp(-t/T).*sin(t/x0);
plot(t,f1)
xlabel('t'),
ylabel('f1'),
grid on
title('f1 versus t')
3. Consider the following two functions
𝒇(𝒕) = 𝟑𝒕𝟐 + 𝟐𝒕 − 𝟎. 𝟓, 𝒈(𝒕) = 𝟐 𝒕 𝒄𝒐𝒔(𝒕)
As shown in Figure 1, plot the following two separate graphs on the same
figure using 20 values for 𝒕 in the interval [𝟎, 𝟏𝟎]:
a. On the left, plot 𝒇(𝒕) and 𝒈(𝒕) versus 𝑡 in one graph with the following customization:
- Draw 𝒇(𝒕) in solid blue line, and 𝒈(𝒕) in red dotted line.
- Give a title to your graph and label the axes.

34
- Add a legend to the graph identifying 𝒇(𝒕) and 𝒈(𝒕) curves
b. On the right, plot 𝑔(𝑡) versus 𝑓(𝑡)
- Draw the curve using a solid blue line.
- Give a title to your graph and label the axes.
- Adjust the axis ranges as show in the figure

Figure 1:
Output of Problem 3
plot2.m
clc; clear
t=linspace(0,10,20);
f= 3*t.^2+2*t-0.5;
g=2*t.*cos(t);
subplot(1,2,1)
plot(t,f,'-b',t,g,':r'), xlabel('t'),
ylabel('f(t) & g(t)'),
title('f & g vs. t'), legend('f(t)','g(t)'),
axis([0 10 -100 400])
subplot(1,2,2)
plot(f,g,'-b'), xlabel('f(t)'),
ylabel('g(t)'),
title('g(t) vs. f(t)'), axis([0 300 -20 20])

35
4. Write a MATLAB function to calculate the coordinates of 𝑛 points on a
circle with radius 𝒓 and center (𝒙𝒄 , 𝒚𝒄 ) using the following two parametric
functions
𝒙(𝒕) = 𝒙𝒄 + 𝒓 𝒄𝒐𝒔(𝒕), 𝒚(𝒕) = 𝒚𝒄 + 𝒓 𝒔𝒊𝒏(𝒕), 𝟎 ≤ 𝒕 ≤ 𝟐𝝅
For example, to plot 100 points on a circle of radius 3 and center (5,5), the
function should be used in the following manner:
[x,y]=circle_points(3, 5, 5, 100);
plot(x,y);
circle_points.m
function [x,y]=circle_points(r,xc,yc,nc)
t=linspace(0,2*pi,nc);
x=xc+r*cos(t);
y=yc+r*sin(t);

Call the function multiple times and adjust the axis to plot the following
graph:

Figure 2: Output of Problem 4

[x1,y1]=circle_points(3, 5, 5, 100);
plot(x1,y1);
[x2,y2]=circle_points(2, 5, 5, 100);
hold on
plot(x2,y2);
[x3,y3]=circle_points(3, 11, 5, 100);
plot(x3,y3);
[x4,y4]=circle_points(2, 11, 5, 100);
plot(x4,y4);

36
Sheet 10 – While loop
Objectives
1. Use while-loop to repeat a task while a condition is satisfied
2. Use while-loop to repeat a task until a stopping condition is satisfied
3. Use while-loop to find the first occurrence that satisfies a condition
4. Use break statement to prematurely abort a while-loop.
5. Use while-loop to implement numerical approximation methods

Problems
1. Use while-loop to display the elements 𝒙 of the series 100, 50, 25, where
𝒙 > 𝟏.
desc_seq.m
x=100;
while x>1
disp(x)
x=x/2;
end

2. Write a MATLAB script to display all the elements 𝒙 of the series


𝟏, 𝟐, 𝟔, 𝟐𝟒, … where 𝒙 < 𝟏𝟎𝟎𝟎. Namely, the element 𝒙𝒊 = 𝒊 ⋅ 𝒙𝒊 𝟏 .
fact_seq.m
clc; clear
i=1; x=1;
while x<1000
disp(x)
i=i+1;
x=x*i;
end

37
3. Use hand tracing to find out the final value of n produced by the following
script for each initial value of n?
n = input('n?');
while n>5
if rem(n,2)==0
n = n/2;
else
n = 3*n+1;
end
end

Initial n n=12 n=13 n=20 n=11

Final n 3 5 5 5

4. Use hand tracing to find the outputs of the following MATLAB script for
each input value of N=8, N=12, N=15.
N=input('N = ? ');
num=1;
i=1;
while num <= N
if mod(N,num)==0
factors(i)=num;
i=i+1;
% disp(num);
end
num=num+1;
end
disp(factors);

Input N=8 N=12 N=15

Outputs 1 1 1

2 2 3

4 3 5

8 4 15

12

38
5. Write a script to find the smallest integer 𝒏, such that 𝒏! > 𝟏𝟎𝟔
find_first.m
clc; clear
n=1; p=1;
while p < 1E6
n=n+1;
p=p*n;
end
disp(n);

6. Use while-loop to find the smallest number 𝒏 such that the sum of the first
𝒏 elements of the geometric sequence (𝒂, 𝒂𝒓, 𝒂𝒓𝟐 , … ) is >1000. Consider 𝒂 and
𝒓 as inputs.
find_first_sum.m
clc; clear
n=0; s=0;
a=input('a= '); r=input('r= ');
while s <= 1000
s=s+a*r^n;
n=n+1;
end
disp(['n = ',mat2str(n)]);
disp(['Total= ',mat2str(s)])

39
7. Use while-loop to write a script to ask the user to enter numbers, one by
one, until the user enters number 0, then display the average of the numbers
provided by the user, excluding the 0.
average_interactive.m
clc; clear
n=0; s=0;
x=input('Enter a number: ');
while x~=0
s=s+x;
n=n+1;
x=input('Enter a number: ');
end
disp(['Average= ',mat2str(s/n)])

40
Sheet 11 – User-defined Functions
Objectives
1. Write function header defining function name, parameters and result
2. Execute functions from the Command Window
3. Call user-defined functions from within other functions

Problems
1. Given a user-defined function
function x=add(a,b)
x=a+b;
end
What is the output displayed by the following script?
Script Output
x=10;
y=add(2,3); 10
disp(x)
5
disp(y)

2. Given the user-defined function


function [a,b]=swap(s,t)
a=t;
b=t+s;
end
What is the output of the following program?
Script Output
x=5;
y=10; 15
[x,y]=swap(x,y);
10
disp(y)
disp(x)

3. Write a user-defined function called "find_range" which takes as input a


vector of numbers and returns as output the difference between the maximum
value and the minimum value of the given vector. Test your function using the
following case:
Example Output
>> find_range([1,5,10,8]) ans = 9

41
find_range.m

function r=find_range(x)

r=max(x)-min(x);

4. Write a user-defined function called ‘𝐦𝐞𝐚𝐧𝟑’ to find the mean of three


numbers 𝒂, 𝒃 and 𝒄.
mean3.m

function m=mean3(a,b,c)

m=(a+b+c)/3;

5. The volume, 𝒗, of a right circular cone is given by the formula


𝝅 𝟐
𝒗= 𝒓 𝒉
𝟑
where 𝒓 is the base radius and 𝒉 is the height of the cone. Write a MATLAB
function called "ConeBaseRadius" which takes the volume of the cone and
its height and calculates the base radius.
ConeBaseRadius.m

function r=ConeBaseRadius(v,h)

r=sqrt(3*v/(pi*h));

6. The number of distinct roots of a quadratic equation in the general form


𝟐
𝒂𝒙 + 𝒃𝒙 + 𝒄 = 𝟎 can be determined using the discriminant
𝚫 = 𝒃 − 𝟒𝒂𝒄. Write the following three user-defined functions:
𝟐

o ‘discriminant’: which calculates the discriminant of a quadratic equation


given its coefficients 𝒂, 𝒃 and 𝒄.
o ‘n_roots’: which determines the number of distinct real roots of a quadratic
equation given its coefficients, using the following rule:

42
𝟐, 𝚫>𝟎
𝒏 = 𝟏, 𝚫=𝟎
𝟎, 𝚫<𝟎
o ‘solve2’: which returns the two roots of a quadratic equation given its
𝒃±√𝚫
coefficients 𝒂, 𝒃 and 𝒄 using the formula 𝒙 =
𝟐𝒂

discriminant.m
function D=discriminant(a,b,c)
D=b^2-4*a*c;

nroots.m
function n=n_roots(a,b,c)
D=discriminant(a,b,c);
if D>1
n=2;
elseif D==0
n=1;
else
n=0;
end

solve2.m
function [x1,x2]=solve2(a,b,c)
D=discriminant(a,b,c);
x1=(-b-sqrt(D))/(2*a);
x2=(-b+sqrt(D))/(2*a);

43
7. Write a function called “time_parts” which takes a duration in seconds
and splits it into hours, minutes and seconds. For instance,
[h,m,s]=time_parts(10000), returns h=2, m=46 and s=40.

time_parts.m
function [h,m,s]=time_parts(seconds)
h= floor(seconds/(60*60));
seconds = seconds - 60*60*h;
m= floor(seconds/60);
s=seconds-60*m;

8. A prime number is defined as a positive integer which has only two factors,
itself and 1. Write the following two functions:
o ‘is_prime’ which takes a number 𝒏 then returns 1 if 𝒏 is prime and 0
otherwise.
o ‘range_primes’ which takes two numbers 𝒂 and 𝒃 and returns a vector
containing all the prime numbers in the interval [𝒂, 𝒃].
is_prime.m
function b=is_prime1(n)
b=1;
for i=2:n-1
if rem(n,i)==0
b=0;
break
end
end

44
range_primes.m
function r=range_prime1(a,b)
j=0;
for ii=a:b
b=is_prime1(ii);
if b==1
j=j+1;
r(j)=(ii);
end
end

9. Write a user-defined function linear_search which, given a key 𝒙,


searches a given vector 𝒂 and, if found, returns the location where the key was
found. Otherwise, returns 0. returns 0.

Example Output
>> linear_search(5, [1, 3, 5, 7]) ans = 3
>> linear_search(2, [1, 3, 5, 7]) ans = 0

linear_search.m
function L=linear_search(a,x)
L=0;
for i=1:length(x)
if x(i)==a
L=i;
break
end
end

45
Sheet 12 – Symbolic Math Toolbox
Objectives
1. Use symbolic math toolbox to solve equations
2. Use symbolic math toolbox to manipulate expressions

Problems
1. Using the Symbolic Math toolbox, write the statements required to solve
the following equations
a. 𝟕𝒙 + 𝟏𝟐 = 𝟎
syms x

solve(7*x+12)

b. 𝟑𝟗𝒙 − 𝟑𝒙𝟐 = 𝟏𝟎𝟖


syms x

solve(39*x-3*x^2==108)

c. 𝟐𝒙 − 𝟑𝒚 + 𝒛 = 𝟏,
𝒙 − 𝒚 − 𝒛 = 𝟓,
𝟒𝒙 + 𝒚 + 𝟐𝒛 = 𝟏𝟎
syms x y z

>> A=solve(2*x-3*y+z==1, x-y-z==5, 4*x+y+2*z==10)

X=A.x

y=A.y

z=A.z

d. 𝒙𝟏 + 𝟐𝒙𝟐 + 𝟑𝒙𝟑 = 𝟏𝟒
𝟒𝒙𝟏 + 𝟓𝒙𝟐 + 𝟔𝒙𝟑 = 𝟑𝟐
𝟕𝒙𝟏 + 𝟖𝒙𝟐 + 𝟗𝒙𝟑 = 𝟓𝟎
syms x1 x2 x3

>> A=solve(x1+2*x2+3*x3 ==14, 4*x1+5*x2+6*x3==32,

7*x1+8*x2+9*x3==50)

x1=A.x1

x2=A.x2

46
X3=A.x3

5. Write MATLAB statements which use Symbolic Math Toolbox to achieve


the following tasks:
a. Expand (𝒙 − 𝟏)(𝒙 + 𝟏)(𝒙𝟐 + 𝟏)
>> syms x
>> expand((x-1)*(x+1)*(x^2+1))

b. Factorize 𝒙𝟓 + 𝟐𝒙𝟒 − 𝟏𝟔𝒙 − 𝟑𝟐


Syms x
factor(x^5+2*x^4-16*x-32)

6. Write MATLAB statements to use the Symbolic Math toolbox to calculate


the following:
𝒅
a. [𝐬𝐢𝐧(𝒙𝟐 + 𝒂)]
𝒅𝒙
syms x a
diff(sin(x^2+a))

𝒅𝟐
b. (𝒙𝟐 𝒆 𝒙 )
𝒅𝒙𝟐
syms x
diff(x^2*exp(-x),2)

𝒅
c. 𝒙𝒔𝒊𝒏(𝒕) + 𝒕𝒔𝒊𝒏(𝒙)
𝒅𝒕
syms x t
diff(x*sin(t)+t*sin(x),t)

d. ∫ 𝒙𝒔𝒊𝒏(𝒙) 𝒅𝒙
syms x
int(x*sin(x))

e. ∫ 𝒌𝒔𝒊𝒏(𝒕) 𝒅𝒕
syms t k
int(k*sin(t),t)

𝒕
f. ∫ 𝒕 𝟏𝟎𝒙 𝒅𝒙
syms x t

47
int(10^x,-t,t)

𝒃
7. By definition, ∫𝒂 𝒇(𝒙) 𝒅𝒙 = the area under the curve 𝒇(𝒙) in a period [𝒂, 𝒃].
When 𝒇(𝒙) is difficult to integrate symbolically, engineers resort to an
approximation method which segments the area under the curve into 𝒏 slices of
𝒃 𝒂
width 𝚫 = 𝒏
each, and calculate the area of each slice as a rectangle of width 𝚫
and height 𝒇(𝒙) Therefore
𝒃 𝒏

𝒇(𝒙) 𝒅𝒙 ≅ 𝚫𝒇(𝒂 + 𝒌 𝚫),


𝒂 𝒌 𝟏
𝒃 𝒂
where 𝚫 =
𝒏
a. Use for-loop to write a MATLAB program to calculate and display
𝝅
𝑺 = ∫ 𝝅 𝒆𝐬𝐢𝐧 𝒙 𝒅𝒙. Take n=10
a=-pi ;
b=pi ;
n=10 ;
d=(b-a)/n ;
s=0 ;
for k=1:n
s=s + d * exp(sin(a+k*d)) ;
end

S= 7.9549

b. Use Symbolic Math toolbox to calculate and display the integration


syms x
f=exp(sin(x)); s=int(f,-pi,pi) ;
disp(double(s))

S= 7.9549

48

You might also like