Sei sulla pagina 1di 12

1

Name:

Date:

Section:

Score:

WORKSHEET Conditional Statements in MATLAB


Instructions: This shall serve as your proof of attendance for this meeting. Write what is asked of you on
the space provided beside each item.
To create a script, click File, then New, then M-file.
In which window does the new script file open?

Type the following code on the Editor Window:


radius = 5
area = pi * (radius^2)
Save the script file as script1.m. On your command window, type the following:
>> script1
Note what happens after you enter the command. On your Editor Window, click the Play button. Note
what happens after clicking.
How do you run a script file?

On your Editor Window, create a script file and type the following line. Run the program afterwards.
disp('Hello world!');
Replace the code with each of the following lines:
disp('Hello world!\n');
disp('Hello\tworld!');
disp('Hello\t\tworld!');
disp((1:3)');
disp('ChE is fun!');

How does the disp function work?

Remove the semicolon in each of the provided lines of code. Are there any changes in the program execution?

2
Run each of the following lines. Use the Editor Window.
fprintf('%d\n',3);
fprintf('%d\n',10/3);
fprintf('%d',10);
fprintf('%g\n',10/3);
fprintf('%g\n',10/3);
fprintf('%g is a boring number.\n',5);
fprintf('But these are OK: %g\t%g\n',23,25);
fprintf('And these are OK: %g %g\n',12,17);
How does the fprintf function work?

Run each of the following lines. Use the Editor Window.


fprintf('%0.5g\n',(1+sqrt(5))/2);
fprintf('%0.5g\n',1/7);
fprintf('%15.5f\n',1/7);
fprintf('%d\n',round(pi));
fprintf('%s\n','hello');
fprintf('The array is %dx%d.\n',2,3);
disp('abcdefghijklmnopqrstuvwxyz'+0);
disp('abcdefghijklmnopqrstuvwxyz'+1);
disp('ABCDEFGHIJKLMNOPQRSTUVWXYZ'+0);
disp('a');
disp('a'+'b');
disp('This is the ASCII code for characters.'+0);
What further conclusions can you make regarding the output functions disp and fprintf?

The simplest input function in MATLAB is called input. The input function is used in an assignment
statement. To call it, the user is prompted for an input, and whatever the user types will be stored in the
variable named on the left of the assigned statement. To make it easier to read the prompt, put a colon and
then a space after the prompt.
Type the following command on your Editor Window and run the program.
radius = input(Enter the radius: )

Try adding a semicolon at the end of the statement.


What happens with the variable assignment?

For string inputs:


letter = input(Enter a letter: , s)
What happens with the variable assignment?

3
Enter the following code on your Editor Window and run the program:
num = input(Enter number: );
if num < 0
num = abs(num);
end
What does the program do?

Now consider the following program that uses if-else statements:


if rand < 0.5
fprintf(It was less than 0.5!);
else
fprintf(It was not less than 0.5!);
end
What is the difference between the first programs if-statement and the second programs if-else statement?

Finally, consider the two programs shown below.


R = ceil(rand*3); %This generates a random number from 1 to 3.
if R == 1
disp('Your luck has ran out.');
elseif R == 2
disp('You''ll be lucky today!');
else
disp('You don''t believe in luck.');
end
H = input('Input your height in cm: ');
W = input('Input your weight in kg: ');
BMI = W/(H/100)^2;
if BMI > 30
disp('You are obese.');
elseif BMI > 25
disp('You are overweight.');
elseif BMI > 18.5
disp('You are normal.');
elseif BMI > 16
disp('You are underweight.');
else
disp('You must be anorexic!');
end
In general, when does one use an if-else statement and an elseif statement?

MODULE 3

Conditional Statements in MATLAB

OBJECTIVE
At the end of this module, you should be able to:
1. Create programs in MATLAB using script files
2. Recognize the difference between data types
3. Use the output functions of MATLAB (disp and fprintf)
4. Create programs using conditional statements in MATLAB

m-FILES
Programs in MATLAB are contained in .m files. These are codes that may be written as plain-text files,
but must have an .m extension in order to be recognized as a MATLAB file. M-files may be in a form
of a script, or a function.
Note: A program can exist, and may be free of errors, but may not run because the current directory is not set to the
same path as that of the m-file.
Script files have no input/output parameters in their name. When you run a script file, the variables
become part of the MATLAB Workspace. Script files are often used for tasks that are unchanging, or
that need trial documentation. Programmers often use a script file to test the execution of a program code
for a specific parameter, and use a function file to run a code for any set of parameters.
To code a script, go to File, click on New, and click Script. A separate editor window will open. Codes are
written on this window. MATLABs Editor Window is equipped with a debugger that automatically
detects errors in syntax (such as an extra parenthesis or a misplaced symbol). It does not, however, detect
errors in logic. You would need to run the program to identify several other errors that might occur, such
as:
1. Inconsistent referencing of variables;
2. Calling of wrong functions;
3. Prohibited matrix operations
On your Editor Window, write the following code:
theta = linspace(1.6,4.6);
tandata = tan(theta);
plot(theta, tandata);
xlabel(\theta (radians));
ylabel(tan(\theta));
grid on;
axis([min(theta) max(theta) -5 5]);
Save the file as tanplot.m in your folder. Now go MATLABs Command Window, and type in
tanplot. A figure window should open with the following plot:

The code can be executed in two ways:


1. Typing in the name of the script file in the Command Window. This will require you to save your
work first. Modifying the codes after will also necessitate saving, so that the changes will be
evident upon execution.
2.

Using the play button


found in the Editor Window. This removes the need to manually save
the file, as MATLAB automatically saves the changes before executing the code.

While typing in codes, you will also see an asterisk in the title tab at the bottom of the Editor Window.
This indicates current editing.
If you open another script file, MATLAB automatically opens another editor window.

DATA TYPES
MATLAB has 14 fundamental data types. The most common are enumerated below:
1. For floating/real numbers (numbers with decimal places)
a. single: single-precision data type; storage requirement is less than double data type,
but has less precision and a smaller range
b. double: double-precision data type; stores a larger value than a single data type;
MATLAB uses this as its default data type
c. int (int8, int16, int32, int64): stores signed and unsigned integers; has less
storage than single or double
2. For characters (either a single character or a series of characters [also known as a string]): char
3. For true or false values (either 1 or 0): logical

The most straightforward way of getting output from a MATLAB code is to enter a variable name,
assignment, or expression without the use of a semicolon. In the absence of a variable, MATLAB
assumes a default variable ans that stores the output temporarily.
Aside from this, MATLAB has two built-in functions that facilitate the output of a program:
1. Using the disp statement
2. Using the fprintf statement

disp
The disp statement displays the value of a variable or an array without printing the array/variable name.
The command allows for a neater display of output. Run the following codes on your Editor Window:
x=5;
disp(x)
disp(I am spiderman!)
a=2; b=6;
disp([a b])
a = Hello world! ;
b = My name is Charlie and I own a factory;
disp([a b])
The third set of codes displays the value of the variable (as strings) in one row vector. Note that the two
values can be treated as two elements in a vector, arranged as a row. Now, try displaying the two variables
in a column:
disp([a; b])
MATLAB returns an error message. By treating the two variables as elements, arranging them in one
column is impossible because they have different lengths (or dimensions). Only elements of the same
length can be displayed properly. If you want MATLAB to display the two strings as a column, the
following command will do the trick:
d = char(a,b)
disp(d)
The char command forms an array with the two strings as elements of a column. Thus, MATLAB
displays now an array with two rows of strings.
The disp statement only displays output of variables with the same data type. For example:
x = 3;
disp ([The hours left for sleep is x]);
The above code will display The hours left for sleep is x and not The hours left for
sleep is 3. An additional function will allow the latter statement to be displayed:
x = 3;
disp ([The hours left for sleep is num2str(x)]);
The num2str function converts the variable containing the numeric data type to a variable containing a
string. Notice that the two variables are arranged as a vector with two elements. Another example:
disp([Pi is , num2str(pi,2)]) %displays 2 digits
disp([Pi is , num2str(pi,8)]) %displays 8 digits

fprintf
The fprintf function allows the user to display a variable content alongside a text string. The syntax is
shown below:
fprintf(string %placeholder, variable)
As an example, you may try the following code:
fprintf(The value is %d., 4^3)
%d refers to a placeholder. The placeholder specifies where the value of the expression is to be printed. d
refers to the type of data that is being printed. The following table summarizes these placeholders:
Syntax

Meaning

%d
%f
%e
%g
%c
%s

Integers
Floating numbers ( values with decimal)
Scientific notation
More compact form of either %f or %e
Single character
Character string

Try the following code:


x=2;
fprintf(The value of the square root of %.2f is %.4g, x, sqrt(x));
In the code above, %.2f is the placeholder for x, and %.4g is the placeholder for sqrt(x). If there is a
number prior to the identifier of the placeholder, it will be used to specify the width (i.e. the allocated
number of characters) or the precision (number of significant digits or decimal places). The placement of
the number with respect to the dot will define if it is to specify width (if before) or precision (if after). As
an example, what would the following code display?
x=2;
fprintf(The value of the square root of %9.2f is %.4g\n, x, sqrt(x));
There are several commands used alongside fprintf to indicate formatting/display of characters. For
example, writing in the symbol % usually denotes a placeholder. But what if you would like to display the
symbol to denote a percentage? The following table shows the solution to these concerns:
Syntax

Output

''
%%
\\
\n
\t

'
%
\
New line
Horizontal tabbing

8
Try the following examples that use variables containing vectors and matrices:
x = 1:4;
w = sqrt(x);
fprintf (%.4f\n, x)
fprintf (The value of w is %.3f\n, w)
A = [2 4 6; 3 6 9; 4 8 12];
fprintf (The numbers are %d %d %d\n, A)

RELATIONAL OPERATORS
Relational operators allow for the creation of logical expressions in MATLAB. Logical expressions
evaluated as true return 1 as a value, while expressions evaluated as false return 0. These operators are
sometimes used singularly or in combination with other operators
Operator

Meaning

<
>
==
~=
<=
>=

Less than
Greater than
Equal to
Not Equal to
Less than or equal to
Greater than or equal to

Try the following statements in your Command Window to see what MATLAB returns as a value:
>>
>>
>>
>>
>>

5<3
45>=45
4==6
5==5
0~=1

The following table (already shown in Module 3) summarizes the hierarchy of operations in MATLAB:
Operator

Meaning

( )
^ .^ '
~
* / .* ./
+ :
> >= < <= == ~=
&&
||

Parenthesis
Exponentiation, Transposition
Not
Multiplication, Division
Addition, Subtraction
Colon Operator
Relational Operators
And (true if both conditions are true)
Or (true if one condition is true

What would be the final value of the following expression, if entered in MATLABs Command Window?
>> -1 * 2 > 0 & 2 == 2 & 1 > 7

CONDITIONAL STATEMENTS IN MATLAB


Conditional statements in programming are employed when the user wants to control the execution of a
program. The program may not proceed in sequence if one condition is not met. MATLAB has to make
a choice whether to execute a command or not.
The if statement chooses whether an action, or a group of action, is executed. Consider the following
code:
x = input(Whats your age? );
if x <= 20
disp(youre young!)
end
The program shown above asks the user to input a number. Then it decides if the number if less than or
equal to 20. If it is, the statement youre young! is displayed. If the number is greater than 20, then the
program ends.
The if statement has the following syntax:
if condition
action
end
The condition is actually a logical expression that is either true or false.
expression/command that will be executed if the condition is true.

The action is the

As an example: you are to write a script that checks if a value of a variable is negative. If it is, the value is
changed to a positive number. If it is positive, nothing is changed. The following may be the code you
created:
num = -4;
if num < 0
num = abs(num)
end
The condition for the program above is the logical expression num < 0. Since the num variable contains
the number -4, then the expression is true. The action, which is num = abs(num), is then executed.
Note that the action statement does not a have a semicolon, so the output is not suppressed.
When two actions are desired, the if-else statement can be used:
if condition
action1
else
action2
end
In this case, when the condition in the if-statement is true, then the program executes action1. If the
condition is false, then the program executes action2.

10
As an example: you are to prompt the user for a radius value. Use the value to calculate the area. Check
whether the radius given by the user is valid (i.e., a positive number). If not, the value is changed to a
positive number. If it is, the value is not changed.
The code may look like the following:
clc
clear
radius = input(Please enter the radius: );
if radius<=0
radius = abs(radius);
area = pi*(radius^2);
fprintf(The area is %.5f., area);
else
area = pi*(radius^2);
fprintf(The area is %.5f., area);
end
A side note: always make it a habit to include clc and clear in your script file. This clears your
Command Window (making it neater) and Workspace (removing all other variables that are not needed).
What happens when more than 2 actions or conditions are desired?
Consider this problem: Prompt the user for the value of x. The program should be able to choose which
f(x) to use, show the value afterwards:

f ( x ) x2
4

for x 1
for 1 x 1
for x 2

We can code this in three ways. The first one is by using three if-statements separately:
x = input(Enter value of x: );
if x < -1
y = 1;
disp(y);
end
if x >= -1 && x <= 2
y = x^2;
disp(y);
end
if x > 2
y = 4;
disp(y);
end
The second if-statement uses the relational operator for and (&&). This logical expression becomes
only true when both the left-hand and right-hand conditions are true. The or operator (||), on the
other hand, becomes true even if only one of the two conditions are true.

11
Another way of coding the problem is by using nested if-statements. Nesting means using a function
inside that same function:
x = input(Enter value of x: );
if x < -1
y = 1;
disp(y);
else
if x >= -1 && x <= 2
y = x^2;
disp(y);
else
y = 4;
disp(y);
end
end
The else-statement contains another if-else-statement.
The last method of coding the problem is using the else-if statement. Else-if statements are used
when two or more actions (and conditions) are desired:
if condition1
action1
elseif condition2
action2
elseif condition3
action3
end
To illustrate, the aforementioned problem may be coded using else-if statements:
x = input(Enter value of x: );
if x < -1
y = 1;
disp(y);
elseif x >= -1 && x <= 2
y = x^2;
disp(y);
elseif x > 2
y = 4;
disp(y);
end
The approach is more straightforward than using nested if-statements.

EXERCISES
1.

Simulate the ROCK-PAPER-SCISSORS, with MATLAB as the users opponent. The user must
be asked for his choice at the start of each round. Do 3 rounds of the game, with scoring for each
round.

12
2.

Prompt the user for a range of values for a variable x. Then, it uses the menu function to present
choices between sin(x), cos(x), and tan(x). The script will then give the table of values of whichever
function of x the user chooses. Select the proper conditional statement for this problem.

Potrebbero piacerti anche