Académique Documents
Professionnel Documents
Culture Documents
Name:
Date:
Section:
Score:
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!');
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?
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: )
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?
MODULE 3
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:
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
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
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.