لقطة شاشة ٢٠٢٤-١٢-٠٢ في ٢.٣٩.٢٧ م
لقطة شاشة ٢٠٢٤-١٢-٠٢ في ٢.٣٩.٢٧ م
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
(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
(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√
>> 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: 𝑣 = 𝑑/𝑡 )
>> 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 𝑑 = 𝑔 𝑡 )
>> 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:
>> 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
>> k = 0.05;
>> g = 9.81;
>> t = 3;
>> g/k*(t+(exp(-0.05*t)-1)/k)
ans = 42.018
>> 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;
>> ( -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;
>> ( -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
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.
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
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
8
3. Write MATLAB statements to perform the following tasks:
(a) Create a matrix, 𝐴, of 5×5 random values between 0 and 1.
>> 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 𝑥
(e) Extract a 3×3 matrix from the top-right corner of matrix A and store it in variable 𝑦
>> 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.
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
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) Create a vector, 𝑥, with 50 random integer numbers between 5 and 15.
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
>> round(9.25)
ans = 9
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;
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= ');
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= ');
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)
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)])
Outputs 0 0 0
Total = 0 1 1
Total = 1 9
36
100
𝑡= 𝑘
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;
T=T+D;
(M) end
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
𝑺= 𝒏𝒎
𝒏 𝟓 𝒎 𝟎
sumsq2.m
S = 0;
for n=5:10
S1 = 0;
for m=0:n
S1 = S1 + n^m;
end
S = S + S1;
end
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
𝒏 𝒎
𝒏 𝒌𝒙
𝑺= 𝒙 𝒆
𝒊 𝟏 𝒌 𝟏
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)])
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
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 𝐴𝑣 = 𝑏
𝟐 −𝟑 𝟏 𝒙 𝟏
𝟏 −𝟏 −𝟏 𝒚 = 𝟓
𝟒 𝟏 𝟐 𝒛 𝟏𝟎
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
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
𝐬𝐢𝐧𝟐 𝒙 + 𝒙 𝐜𝐨𝐬𝟒 𝒙
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:
[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
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
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);
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)
41
find_range.m
function r=find_range(x)
r=max(x)-min(x);
function m=mean3(a,b,c)
m=(a+b+c)/3;
function r=ConeBaseRadius(v,h)
r=sqrt(3*v/(pi*h));
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
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)
solve(39*x-3*x^2==108)
c. 𝟐𝒙 − 𝟑𝒚 + 𝒛 = 𝟏,
𝒙 − 𝒚 − 𝒛 = 𝟓,
𝟒𝒙 + 𝒚 + 𝟐𝒛 = 𝟏𝟎
syms x y z
X=A.x
y=A.y
z=A.z
d. 𝒙𝟏 + 𝟐𝒙𝟐 + 𝟑𝒙𝟑 = 𝟏𝟒
𝟒𝒙𝟏 + 𝟓𝒙𝟐 + 𝟔𝒙𝟑 = 𝟑𝟐
𝟕𝒙𝟏 + 𝟖𝒙𝟐 + 𝟗𝒙𝟑 = 𝟓𝟎
syms x1 x2 x3
7*x1+8*x2+9*x3==50)
x1=A.x1
x2=A.x2
46
X3=A.x3
𝒅𝟐
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
𝒃 𝒏
S= 7.9549
S= 7.9549
48