1. Objectives
Completing
all tasks in this assignment will help you:
·
write nested selection statements
·
use relational operators and
functions to find the number of values in a vector that satisfy particular
conditions
·
use the functions rem and sum.
First skim, and then
carefully read the entire assignment
before starting any tasks.
2. Finding the minimum
Write a
program that accepts three numbers as input and prints the minimum of the three
numbers.
Does your program give the correct output if two or more of the values are
equal? If exactly two of the values are
equal, does it matter whether the equal values are lower or higher than the
third? Ensure that your program gives
the correct output for all possible scenarios.
Save your script file as MinOfThree.m
3. Counting Digits
Design a
program that determines and prints the number of odd, even, and zero digits in
an integer value read from the user.
Divide your task into three parts:
Part A: Read the number as a string
The problem becomes much easier to handle if you read the integer value first
as a string. We can use the input function in a novel way to
accomplish this. Type the following at
the Command window and observe the
type of variable that num becomes:
>>num = input(‘Enter a number: ‘, ‘s’);
Enter a number: 7801
Part B: Convert the string to a double array
We want now
to convert our string to a numeric array with the proper values.
Recall that we can convert a character to an integer by performing any
mathematical operation on it, like addition or subtraction. Unfortunately, adding 0 to the string, as we did in
lecture, will not work because the
integer equivalents to the characters are not the same as the values they represent:
>>num + 0 %using num from the example above
ans =
55
56 48 49
Perhaps we shouldn’t add 0 but something else.
Can you see a way to add or subtract a particular value from string num to get the values you
seek? Does it work for all input
values?
Part C: Count the digits
You should have, by now, found a way to turn the original string into an array
of numbers whose values are the same as those represented by the original
characters.
The logical equality operator == and the functions rem and sum will be useful in this next
part. Use MATLAB’s help facility for more
information on sum and rem if required.
Inspect carefully the following statements:
>>x = [5 8 9 11 –2 0 9];
>>x == 9
ans =
0
0 1 0 0 0 1
>>sum( x == 9 )
ans =
2
>>rem(x, 3) == 0
ans =
0
0 1 0 0 1 1
How would you interpret the value returned by sum( x == 9 )? Can you use variations of that technique to find the number of
values in the array that are odd, even and zero?
Save your script file as CountDigits.m
4. Submitting Your Work
Type your
name (and your partner’s name if you have one), student ID, and the date at the
top of each M-file. Print each file and sign them along with
your partner. Give the signed documents
to the teaching assistant at the end of the lab session.