Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

LAB-03-Contitional Statements and Loops-Solutions

Uploaded by

hufuo0faypi0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

LAB-03-Contitional Statements and Loops-Solutions

Uploaded by

hufuo0faypi0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

University of frères Mentouri Engineering: Sciences and Technologies

Faculty of Science and Technology Cours of MATLAB


Department of electronics Academic-Year: 2023-2024

LAB#3: CONTIONAL STATEMENTS AND LOOPS


Exercise 01: Write a MATLAB script to compute the absolute value of a number x, the value of x is given by the
user. Use an elseif statement to handle cases where x is negative, then save the program in a script file (called
MyScript.m) and run it for the values of x; 3, -8 and 0.
Exercise 02: Write a MATLAB script that takes the current hour as input and outputs a greeting message
depending on the time of day:
▪ Morning: 6:00 AM - 11:59 AM
▪ Afternoon: 12:00 PM - 5:59 PM
▪ Evening: 6:00 PM - 11:59 PM
▪ Night: 12:00 AM - 5:59 AM
1) Write two versions of the program, the first one with elseif and the second one with the switch statement.
2) Save each program in a script file and run them for the current hour in your system (use the command
clock to retrieve the current hour of your system).
Exercise 03: Write a MATLAB program that takes three side lengths (a, b, and c) as inputs, classifies the triangle
as either equilateral, isosceles, or scalen and print the result to the console.
o Equilateral triangle: All three sides of the triangle are equal
o Isosceles triangle: All two sides of the triangle are equal
o Scalene triangle: No sides of the triangle are equal
Exercise 04: Write a MATLAB program to find the sum of all even numbers from 1 to a user-specified number.
Run the program for the integer numbers -3 and 9 and save the results in a MAT file.
Exercise 05: Write a script that uses a for loop to compute and plot the finite Fourier series given by the sum in
the equation below, for the interval 𝑥 = [0, 8𝜋]. The plot you should see is called the 'sawtooth function'.
100
sin⁡(𝑛𝑥)
𝑦(𝑥) = ∑
𝑛
𝑥=1

Exercise 06: Write a MATLAB program to fill in the matrix A = [amn] using loops. The matrix entries are
calculated as fellow:
𝑚𝑛 𝑚
𝑎𝑚𝑛 = +
4 2𝑛
Consider 𝑚⁡ ∈ ⁡ {1, . . . , 100} and 𝑛⁡ ∈ ⁡ {1, . . . , 20}, run this code in the command window, display A, then save it
in a MAT file.
Exercise 07: Write a MATLAB program to display the numbers from a user specified start number to a user
specified stop number. Assume that the second number the user enters will be larger than the first number.
▪ Use the while loop to solve this problem.
▪ Run the program for start number =4 and Stop number: 12, and verify that it operates correctly.
Exercise 08: Create a MATLAB program consisting of the MATLAB code in the figure and save it in a script
file named “MyProgram”.
clear; clc;
▪ Run the program and verify that the values in the array numbers numbers = 1:0.5:5;
are displayed. for k = 1:1:length(numbers)
▪ Determine the size and value(s) of the variable k after the loop val = numbers(k);
has been executed for the program. fprintf('%0.1f ', val);
▪ Explain the functionality of this program. end
▪ Rewrite this program by using the while loop. fprintf('\n');

Exercise 09: Write a MATLAB program that reads a sequence of float numbers ending in zero (0) from keyboard
and find their sum and average.

1|Page
University of frères Mentouri Engineering: Sciences and Technologies
Faculty of Science and Technology Cours of MATLAB
Department of electronics Academic-Year: 2023-2024

LAB#3: CONTDETIONAL STATEMENTS AND LOOPS – SOLUTIONS


Solution of exercise 01
MATLAB script
% Exercise: absolute value of a number x
% 1. Prompt the user to enter their age.
x = input('Enter a number x: ');

% 2. Use the if…else statement to determine the absolute value of x.


if x >= 0
abs_value = x;
else
abs_value = -x;
end

% 3. Display the determined life stage.


disp(['The absolute value of x is: ', num2str(abs_value)]);

Save the program in a script file (called MyScript.m) and run it for the values of x; 3, -8 and 0.
Script file myscript.m

After running the script file on the command window, you should get the following results:

2|Page
University of frères Mentouri Engineering: Sciences and Technologies
Faculty of Science and Technology Cours of MATLAB
Department of electronics Academic-Year: 2023-2024

Solution of exercise 02
The MATLAB script that takes the current hour as input and outputs a greeting message depending on the time
of day:
▪ Morning: 6:00 AM - 11:59 AM
▪ Afternoon: 12:00 PM - 5:59 PM
▪ Evening: 6:00 PM - 11:59 PM
▪ Night: 12:00 AM - 5:59 AM

The clock function calculates the current date and time from the system time. The statement c = clock returns a
six-element date vector containing the current date and time in decimal form: [year month day hour minute
seconds]. The current hour value is the fourth element of the vector (current hour =c(4)).
First version of the program with the if…else statement:
% exercise 2: time_greeting
% 1. retrieve current hour.
format shortg
c = clock;
current_hour=c(4);

% 2. Use the elseif statement to display the greeting


if current_hour >= 6 && current_hour < 12
disp('Good Morning!');

elseif current_hour >= 12 && current_hour < 18


disp('Good Afternoon!');

elseif current_hour >= 18 && current_hour < 24


disp('Good Evening!');

else
disp('Good Night!');
end

Second version of the program with the switch statement:


% exercise 2: time_greeting-version 02
% 1. retrieve current hour.
format shortg
c = clock;
current_hour=c(4);

% 2. Use the switch statement to display the greeting.


switch true
case current_hour >= 6 && current_hour < 12
disp('Good Morning!');
case current_hour >= 12 && current_hour < 18
disp('Good Afternoon!');
case current_hour >= 18 && current_hour < 24
disp('Good Evening!');
otherwise
disp('Good Night!');
end

1) Save each program in a script file and run them for the current hour in your system.
Running version 1

3|Page
University of frères Mentouri Engineering: Sciences and Technologies
Faculty of Science and Technology Cours of MATLAB
Department of electronics Academic-Year: 2023-2024

Running version 2

Solution of exercise 03
Write a MATLAB program that takes three side lengths (a, b, and c) as inputs and classifies the triangle as either
equilateral, isosceles, or scalen.
▪ Equilateral triangle: All three sides of the triangle are equal
▪ Isosceles triangle: All two sides of the triangle are equal
▪ Scalene triangle: No sides of the triangle are equal

4|Page
University of frères Mentouri Engineering: Sciences and Technologies
Faculty of Science and Technology Cours of MATLAB
Department of electronics Academic-Year: 2023-2024

% exercise 3: Classify triangle


% 1. Input values of the three sides of the triangle.
a = input('Enter the side a of the triangle: ');
b = input('Enter the side b of the triangle: ');
c = input('Enter the side c of the triangle: ');

%2: classification of the triangle


if a == b && b == c
disp('Equilateral triangle');
elseif a == b || b == c || a == c
disp('Isosceles triangle');
else
disp('Scalene triangle');
end

Explanations:
o If all three sides are equal (a == b && b == c), it prints "Equilateral triangle".
o If at least two sides are equal (a == b || b == c || a == c), it prints "Isosceles triangle".
o If none of the above conditions are met, it concludes that it's a "Scalene triangle".

Solution of exercise 04

% Exercise 04: sum of evens


n = input('Enter a positive integer: ');
if n <= 0
error('Input must be a positive integer.');
end

sum_even = 0;

for i = 2:2:n
sum_even = sum_even + i;
end

disp(['The sum of even numbers from 1 to ', num2str(n), ' is: ', num2str(sum_even)]);

Running the program for n=-3, then for n=9

5|Page
University of frères Mentouri Engineering: Sciences and Technologies
Faculty of Science and Technology Cours of MATLAB
Department of electronics Academic-Year: 2023-2024

Solution of exercise 05
Write a script that uses a for loop to compute and plot the finite Fourier series given by the sum in the equation
below, for the interval 𝑥 = [0, 8𝜋]. The plot you should see is called the 'sawtooth function'.
100
sin⁡(𝑛𝑥)
𝑦(𝑥) = ∑
𝑛
𝑥=1

x = linspace(0, 8*pi, 1000); % Generate x values


y = zeros(size(x)); % Initialize y to zeros

% Compute the Fourier series


for n = 1:100
y = y + (sin(n*x))/n;
end

% Plot the sawtooth function


figure;
plot(x, y);
title('Sawtooth Function');
xlabel('x');
ylabel('y(x)');

Resulting Plot of the Sawtooth function

Solution of exercise 06
MATLAB program

6|Page
University of frères Mentouri Engineering: Sciences and Technologies
Faculty of Science and Technology Cours of MATLAB
Department of electronics Academic-Year: 2023-2024

% Define the dimensions of the matrix


m_max = 100;
n_max = 20;

% Initialize matrix A
A = zeros(m_max, n_max);

% Fill in the matrix A using loops


for m = 1:m_max
for n = 1:n_max
A(m, n) = (m * n) / (4 + m/(2 * n));
end
end

% Display the resulting matrix A


disp('Matrix A:');
disp(A);

% Save the resulting matrix A to a MAT file


save('matrix_A.mat', 'A');

Results

Solution of exercise 07
Explanation: This program prompts the user to enter the start and stop numbers. Then, it checks if the stop number
is indeed larger than the start number. If not, it throws an error, by using the error function of MATLAB.
After that, it enters a while loop. As long as current_number (initial value is the value of start number) is less
than or equal to the stop number, it will execute the loop body (it displays the current number and then increments
current_number by 1). The loop continues until current_number is greater than stop_number.

7|Page
University of frères Mentouri Engineering: Sciences and Technologies
Faculty of Science and Technology Cours of MATLAB
Department of electronics Academic-Year: 2023-2024

% exercise 05: display_numbers


start_number = input('Enter the start number: ');
stop_number = input('Enter the stop number (larger than start number): ');

if stop_number <= start_number


error('Stop number must be larger than start number.');
end

current_number = start_number;

while current_number <= stop_number


disp(current_number);
current_number = current_number + 1;
end

Running the program for 4 and 12:

In case the first number is greater than the second one, it displays the following error message

Solution of exercise 08
After running the script:
As shown in the figure below, the values in the array numbers are:

8|Page
University of frères Mentouri Engineering: Sciences and Technologies
Faculty of Science and Technology Cours of MATLAB
Department of electronics Academic-Year: 2023-2024

The size and value of variable k after running the program are shown in the figure below:

Functionality: This script generates a vector of numbers from 1 to 5 with a step size of 0.5, then uses a for loop
to iterate through the elements of the numbers array and print each value in formatted manner. The loop continues
as long as k is less than or equal to the length of the numbers array.
fprintf: This is a function in MATLAB used for formatted printing. It allows you to print text and variables with
specific formatting. Thus, the statement fprintf('%0.1f ', val); is used to print the value of val with one digit
before the decimal point and one digit after, and it separates it from the next value by a space. For example, if val
is 3.456, it will be printed as "3.5 " (one digit before the decimal point, one digit after, and a space after), as shown
in the figure below:

The same program with the while loop


clear; clc;
numbers = 1:0.5:5;
k = 1;
while k <= length(numbers)
val = numbers(k);
fprintf('%0.1f ', val);
k = k + 1;
end
fprintf('\n');

9|Page
University of frères Mentouri Engineering: Sciences and Technologies
Faculty of Science and Technology Cours of MATLAB
Department of electronics Academic-Year: 2023-2024

Solution of exercise 09
MATLAB program

% Initialize variables
sum_numbers = 0;
count = 0;

% Read numbers from the user


while true
% Read a number from the user
num = input('Enter a float number (0 to exit): ');

% Check if the user entered zero


if num == 0
break;
end

% Update the sum and count


sum_numbers = sum_numbers + num;
count = count + 1;
end

% Calculate the average


if count > 0
average = sum_numbers / count;
else
average = 0;
end

% Display the sum and average


disp(['Sum of numbers: ', num2str(sum_numbers)]);
disp(['Average of numbers: ', num2str(average)]);

Example of running it for the numbers {-1.5, 6.2, 7.1, 15.23, 0}

10 | P a g e

You might also like