Ennuma1l-Activity 3
Ennuma1l-Activity 3
Name: Date:
Section: Instructor:
I. Learning Outcomes:
At the end of the laboratory activity, the students should be able to:
1. Familiarize MATLAB environment, its capabilities, functions, and basic commands.
2. Use MATLAB loops for different uses.
FOR LOOP
IF-ELSE STATEMENT
Example:
Syntax
a=5;
if a<0
fprintf(‘The number %d is a negative number’,a);
elseif a>0
fprintf(‘The number %d is a posivitve number’,a);
else
fprintf(‘The number %d is a non-negative and non-positive number’,a);
end
Output:
The number 5 is a positive number.
Explanation:
COLLEGE OF Engineering and Architecture
If the first logical statement is true, therefore it will run the command below it and end.
But if it is false, it will proceed with the next logical statement (elseif) and run the
command. But if no true statements, it will run the command under else and end the if-
else structure.
a. Problem:
a. Create a MATLAB program that sort numbers into two division: Odd or Even.
The computer should randomize 10 integers. Then, the random numbers are stored in
odd or even variable. The output should be a horizontal matrix of 10 integers, odd
numbers and even numbers
Sample Output:
Command:
x = randi([-10 100],1,10)
Odd = x(mod(x,2)==1);
Even = x(mod(x,2)==0);
fprintf('Odd = \n');
disp(Odd);
fprintf('Even = \n');
disp(Even);
COLLEGE OF Engineering and Architecture
For Loop
Command:
num =[];
Even = [];
Odd = [];
for x=1:10
random = randi([1,100]);
if mod(random,2)==1
Odd = [Odd,random];
else
Even = [Even,random];
end
num = [num,random];
end
COLLEGE OF Engineering and Architecture
fprintf('x = \n');
disp(num);
fprintf('Odd = \n');
disp(Odd);
fprintf('Even = \n');
disp(Even);
COLLEGE OF Engineering and Architecture
2.
a. Problem:
Create a MATLAB program that tells whether the number is odd or even. The computer
should ask the user to enter 10 integers. The output should be in tabular form. The first
column should show the entered number and the second column should show the type of
number.
Sample Output:
Command:
Number = [];
Type = [];
for x = 1:10
y = input('Enter a Number:');
if mod(y,2)==0
Type = [Type;"Even"];
else
Type = [Type;"Odd"];
end
Number = [Number; y];
end
T = table(Number,Type)
COLLEGE OF Engineering and Architecture
3.
a. Problem:
Define a function of 𝑥, 𝑓(𝑥) = 𝑥 2 − sin 𝑥 + 𝑒 −𝑥
Create a MATLAB program that tells the value of the function when the user enters a
value of 𝑥.
Sample Output:
Command: