Professional Documents
Culture Documents
Semester 1 2018/2019
Experiment 1
Variable: Assignment, Class,
Value, Operator
1.1 Objectives
• To understand how to create and assign a variable.
• To understand various classes, the differences and the implementation.
• To understand data input and output.
1
EXPERIMENT 1. VARIABLE 2
workspace for showing variables and their values, as well as Current Folder
window for showing files in the working directory. The path of current work-
ing directory is given in the bar above the source code editor. In addition,
we can interactively use MATLAB by entering some expressions in the Com-
mand Window.
GNU Octave is a free software licensed under the GNU General Pub-
lic License (GPL) which has powerful mathematics-oriented syntax that are
largely compatible with MATLAB. The IDE of GNU Octave is illustrated in
Figure 1.2. Like in MATLAB IDE, there are source code editor, workspace,
current folder window, and command window in the IDE of GNU Octave.
Their functions are similar to those in MATLAB. Even though all commands
in this module are dedicated for MATLAB, they are supposed to be success-
fully executed by GNU Octave.
1.3.2 Variable
A variable is used to store a value. Typically, a variable has a name, a type or
class1 , and its value. The value assignment can be executed by using symbol
’=’ (without quotes). As for the variable name, there are some rules that
should be followed:
1
Type in MATLAB is called class.
EXPERIMENT 1. VARIABLE 3
There are 7 kind of classes in MATLAB: logical, char, numeric, table, cell,
struct, and function handle (@). The size and range of numerical variable’s
classes are given in Table 1.1. A variable declaration is not necessary in
MATLAB as it will be assigned by MATLAB to the default class. By default,
the class of a numerical variable is double. The command class can be used
to check the class of a variable.
A class can be seen as a combination of a type and the operations that can
be performed on values of that type. Some operators, utilized in MATLAB,
are given in Table 1.2, with precedence ordered from highest to lowest level.
EXPERIMENT 1. VARIABLE 4
Operation Operator
() parentheses
e exponential operation for the exponent
of 10 (e.g., 2 ∗ 10 ∧ 3 is equal to 2e3)
∧ exponentiation (e.g., 2 ∧ 3 = 8)
∗ multiplication
arithmetic
/ division (divided by, e.g. 6/3 = 2)
\ division (divided into, e.g. 6\3 = 0.5)
+ addition
− negation, substraction
< less than
<= less than or equal to
> greater than
relational
>= greater than or equal to
== equal to
∼= NOT equal to
∼ element-wise NOT
& element-wise AND
logical | element-wise OR
&& logical operator AND
|| logical operator OR
1.4 Practice
1. Start MATLAB and type the following code in the script editor.
1 a = i n p u t ( ’ Enter your name : ’ , ’ s ’ ) ;
2 f p r i n t f ( ’ Good day , %s ! \n ’ , a )
2. Change variable a in line 1 of Task 1 with variable name, then run the
script. Enter any different name with that in Task 1.
Question: What is the output shown in the Command Window ? Is it
the same with Task 1 or not? Why ?
3. Fix the source code so that the name that you have entered will be
shown when you run it. Note: keep using variable name instead of a.
5. Write a simple script with an input: radius (r), and output: area, as
the area of a circle. Save the script with name: circleArea.m. Hint:
2
Type ’help anycommand ’ (without quote) in the Command Window.
EXPERIMENT 1. VARIABLE 6
(a) 3\6 ∧ 2
(b) ∼ (−2 > 3) & (3\12 >= 4)
(c) int8(128) + 1
(d) uint16(−20) ∗ 3
(e) int8(−129) < −128
Experiment 2
Selection Statements
2.1 Objectives
• To understand how to create and to use selection or branching state-
ments.
7
EXPERIMENT 2. SELECTION STATEMENTS 8
1 i f condition
2 action
3 end
4
1 i f condition1
2 action1
3 e l s e i f condition2
4 action2
5 e l s e i f condition3
6 action3
7 else
8 actionn
9 end
10
Do NOT putting a space between else and if in the keyword elseif, i.e.,
else if.
However, this is not a very efficient code: all three logical expressions must
be evaluated, regardless of the range in which x falls. If x is less than −1,
the first expression is true and 1 would be assigned to y. However, the next
two if statements’ expressions are still evaluated. Instead of writing it this
way, the statements can be nested so that the entire if-else statement ends
when an expression is found to be true:
1 i f x < −1
2 y = 1;
3 else
4 i f x <= 2
5 y = xˆ2;
6 else
7 y = 4;
8 end
9 end
10
EXPERIMENT 2. SELECTION STATEMENTS 11
Function
isequal returns logical 1 if input arguments are equal,
or 0 if it is not.
isletter returns logical 1 if the character argument is a letter of the alphabet,
or 0 if it is not.
isempty returns logical 1 if a variable is empty,
or 0 if it is not.
2.4 Practice
1. Write an If statement that would print ”Hey, you get overtime!” if
the value of a variable hours is greater than 2. Test the statement for
values of hours less than, equal to, and greater than 2. Try both in the
script editor and Command Window.
Would it be easier to do this in the Command Window or in a script ?
2. Write the following script in the editor, run with any input possible,
and discuss the results.
1 l e t t e r = i n p u t ( ’ Choice (Y/N) : ’ , ’ s ’ ) ;
2
3 i f l e t t e r == ’ y ’ | | l e t t e r == ’Y ’
4 d i s p ( ’ Action 1 ’ )
5 end
6
7 i f l e t t e r == ’ y ’ | | ’Y ’
8 d i s p ( ’ Action 2 ’ )
9 end
10
3. Write a script that will prompt the user for a monthly income. If the
user enters an invalid number, i.e, less than 0, display an error message,
for example: ”Sorry, it is not a valid number”. Otherwise, calculate the
tax money which is 10% of the income, and then print the result. Try
any of function: fprintf, error, or disp, to print out the message.
4. Write a script that will prompt the user for a quiz score in the range
from 0 to 10. Firstly, check the score whether or not it is in the range
and return an error message if it is not. Otherwise, returns a corre-
sponding letter grade according to the following scheme:
9 or 10 is an ’A’,
8 is a ’B’,
7 is a ’C’,
6 is a ’D’,
and anything below that is an ’F’.
Use elseif clause.
5. Use nested is-else and switch statements for the problem in No.4.
Hint: use if-else statement for error-checking and switch statement
for the rest.
EXPERIMENT 2. SELECTION STATEMENTS 13
3.1 Objectives
• To understand how to create and to use looping statements.
14
EXPERIMENT 3. LOOP STATEMENTS 15
There are two elements in for statement: (1) loop variable that is used to
iterate through values, and (2) action of the loop which is the statement(s)
that is(are) repeated. The range can be specified using any vector, but
normally the easiest way is to use the colon operator like a:b:c, where a, b,
and c are the integer numbers indicating the start, the increment/decrement
interval, and the end of the range, respectively. The interval can be a positive
(increment) or negative number (decrement). When b is negative, a > c must
be satisfied.
3.4 Practice
1. (a) Write a for loop script that will print a column of five * as the
following
1 ∗
2 ∗
3 ∗
4 ∗
5 ∗
6
(b) Write a for loop script that will print a row of five * as the
following
1 ∗ ∗ ∗ ∗ ∗
2
2. Using nested for loop, write a script that will print a triangle of stars
as the following
1 ∗
2 ∗ ∗
3 ∗ ∗ ∗
4
Hint: use the loop variable of the outer loop in the range of the inner
loop.
3. Trace the following script to figure out what the result will be, and
then type it into MATLAB or Octave to verify the result.
1 vec = [ 5 0 3 −2 10 13 −5 1 7 −1];
2 outmin = vec ( 1 ) ;
3
4 f o r i = 2 : l e n g t h ( vec )
5 i f vec ( i ) < outmin
6 outmin = vec ( i ) ;
7 end
8 end
9
10 d i s p ( [ outmin ] )
11
4. (a) Trace the following script to figure out what the result will be,
and then type it into MATLAB or Octave to verify the results.
EXPERIMENT 3. LOOP STATEMENTS 18
1 count = 0 ;
2 number = 1 0 ;
3
4 w h i l e number > 0
5 f p r i n t f ( ’ number i s %d \n ’ , number )
6 number = number − 2 ;
7 count = count + 1 ;
8 end
9 f p r i n t f ( ’ count i s %d \n ’ , count )
10
5. Trace the following script to figure out what the result will be, and
then type it into MATLAB or Octave to verify the result. Try to enter
negative number(s).
1 n = 10;
2 f p r i n t f ( ’ P l e a s e e n t e r %d p o s i t i v e numbers \n\n ’ , n ) ;
3 for i = 1:n
4 inputnum = i n p u t ( ’ Enter a p o s i t i v e number : ’ ) ;
5 w h i l e inputnum < 0
6 inputnum = i n p u t ( ’ I n v a l i d ! Enter a p o s i t i v e number : ’ ) ;
7 end
8 f p r i n t f ( ’ Thanks , you e n t e r e d a %d \n ’ , inputnum ) ;
9 end
Experiment 4
Function
4.1 Objectives
• To understand how to create and to use function.
The name of the file must be the same as the function’s name.
19
EXPERIMENT 4. FUNCTION 20
4.4 Practice
1. Given the following function header :
1 function doit (a , b)
1 do i t (3 , 6 , 9)
1 x = 3.4;
2 y = 7.2;
3 doit (x , y)
2. Write a function calcTriangle that will calculate and return the area
of a triangle. Pass the base and the height to the function as input
arguments.
4. Write four separate functions to calculate the volume and surface area
of a hollow cylinder by accomplishing these tasks:
(a) A function to prompt the user and read in the radius of the cylin-
der base and the height of the cylinder.
(b) A function to calculate and return the volume of the cylinder.
(c) A function to calculate and return the surface area of the. cylinder
(d) A function to display the results.
Note: The volume is given by πr2 h, and the surface area is 2πrh
Experiment 5
Array
5.1 Objectives
• To understand how to create, to modify, and to use scalar, vectors, and
matrices.
22
EXPERIMENT 5. ARRAY 23
1 rv1 = [ 1 3 5 7 ]
2 rv2 = [ 1 , 3 , 5 , 7 ]
3 rv3 = 1 : 2 : 7 % colon operator c r e a t e s vector as
4 % min . v a l u e : s t e p v a l u e : max . v a l u e
5
6 rv4 = l i n s p a c e ( 1 , 2 , 5 ) % l i n s p a c e f u n c t i o n c r e a t e s
7 % e q u a l l y spaced vector .
8 rv5 = z e r o s ( 1 , 4 )
9 rv6 = o n e s ( 1 , 4 )
Moreover, a matrix can be formed from several vectors like the following
1 rv1 = [ 1 , 3 , 5 , 7 ] ;
2 rv2 = 1 : 2 : 7 ;
3 m5 = [ rv1 ; rv2 ]
4
5 cv1 = [ 1 , 3 , 5 , 7 ] ’ ;
6 cv2 = [ 1 ; 3 ; 5 ; 7 ] ;
7 m6 = [ cv1 cv2 ]
the elements in order by columns. For example, with the matrix m shown in
Figure 5.1,
1 >> m( [ 1 2 4 ] )
2 ans =
3 3 4 6
An entire row or column could also be changed, by using colon operator. For
example,
1 >> m( : , 2 : 3 ) = 2
EXPERIMENT 5. ARRAY 25
2 m=
3 3 2 2
4 4 2 2
If there is a gap between the current matrix and the row or column being
added, MATLAB will fill in with zeros. For example,
1 >> m( : , 5 ) = [ 2 8 ]
2 m=
3 3 5 7 0 2
4 4 6 8 0 8
6 2 x 3 l o g i c a l array
7
8 0 1 1
9 0 1 1
EXPERIMENT 5. ARRAY 27
5.4 Practice
1. How can you use the colon operator, i.e. ”:”, to generate the vector
shown below?
1 v =
2 10 7 4 1 −2 −5
3. Let array
1 >> A =
2 [1 1 0 1
3 0 2 0 2
4 3 1 1 3]
29