MATLAB TUTORIAL 3
By Norhan Abdalla
Outline:
■ Input /Output Control
■ Logical Structures
■ Repetition Structures
INPUT & OUTPUT
CONTROL
User Defined Input
■ This is mainly when the
program deals with a person
other than the programmer.
■ Using the command ‘input’:
▪ It can be a scalar
▪ It can be a matrix
▪ It can be a string:
• Having this ‘s’ as a parameter , means
that you don’t have to insert the string
in a single quotation
Output
■ Using the command ‘disp()’
■ If you want to include the apostrophe , you have to use it twice unless
MATLAB will interpret it as terminating the string.
Try this:
■ You can use a combination of the ‘input’ and ‘disp’
functions to mimic a conversation.
Try this using
an M-file
Formatted Output
■ fprintf A function controls the output and adjust its
format.
• General form:
fprintf( format setting , variable….)
• % is a place holder for the variable and the variable is
specified later.
You can’t hold
a place by just
using ‘%’, a
formatting style
must be used
Formatting the Output
■ To insert new line , use (‘n’)
Type
Field
Result
%f Fixed-point notation
%e Exponential notation
%d Decimal notation( doesn’t include trailing
zeros
%g Whichever is shorter , %f or %e
%c Character information( one character at a
time
%s String of characters( the entire string)
Format
command
Result
n linefeed
r Carriage return
t Tab
b backspace
Formatting the Output
■ Adjusting the precision :
■ If a variable is a two dimensional matrix , MATLAB uses the values one
column at a time.
■ Try this , What do you notice?
8.4 reserves a place
for 8 digits 4 of them
are decimals
Formatting Output
■ To output in a file , you first have to create a file
,open an output file and assign an identifier to it.
■ If you want to include a ‘%’ in an fprintf function ,
you must use it twice unless MATLAB will interpret
it as a place holder.
identifier Function that opens a
file
File’s name Write data to the file
The output in the file
LOGICAL STRUCTURES
Relation & Logical Operators
■ MATLAB uses number 1 for true and 0
for false ( actually it takes any non zero
number as true)
■ Notice the difference between ==(equal operator) and
= (assignment operator).
Relational
Operator
Interpretation
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to
Relation & Logical Operators
Logical
Operator
Interpretation
& And
~ Not
| Or
xor Exclusive or
&& And (with scalars)
|| Or (with scalars)
■ The difference between & and
&& is that && is used for
scalar quantities only.
■ & is used for expressions.
Logical Functions
Find
■ find Searches a matrix and
identifies which element in that
matrix meets a given condition.
■ Try this:
Indexes
Elements
Try this using
an M-file
Practice:
𝑥 =
1 10 42
5 8 78
56 45 9
6
23
13
y =
1 2 3
4 10 12
7 21 27
z = 10 22 5 13
23 22 8 9
• Find the elements in each matrix that are greater than 10.
• Find the row and column numbers for elements in each matrix that contains
values greater than 10 and less than 40.
• Find the values in each matrix that are greater than 10 and less than 40.
• Use the length command together with results from the find command to
determine how many values in each matrix are between 0 and 10 or
between 70 and 80.
• Define the following matrices:
Selection Structures
■ The general form :
if comparison
{ statements }
end
Selection Structures
■ This structure allows us to execute a series of
statements if the condition is true , and skip
those steps if the condition is false.
■ If x is a matrix ( x = 0:0.5:2;) , ‘if’ statement is
true only ,if it is true for every element in the
matrix.
• Hint :
MATLAB includes a function called ‘beep’ that causes the
computer to “beep” at the user.
Selection Structures
■ This structure allows us to check multiple criteria while
keeping the code easy to read.
■ Remember that : if age is a matrix , every condition is true for
all the elements evaluates to true.
Try to change
age and notice
the result
Practice:
■ Try this:
■ Grading Marks:
• Prompt the user to enter the mark
• Check the mark based on the mark table
• Display the mark
Mark Grade
90 to 100 A
80 to 90 B
70 to 80 C
60 to 70 D
Less than 60 F
Selection Structures
Switch
■ This structure allows you to choose between multiple
outcomes , based on some criteria.
■ General form:
Switch variable
case option1
code for option 1 if true
case option2
code for option 2 if true
otherwise
code to be executed if non of the cases were true
end
REPETITION
STRUCTURES
Basic Parts for a Loop
■ Parameter used to terminate the loop.
■ Initialization of the parameter.
■ Process that changes the parameter at each iteration.
( unless it becomes unstoppable )
■ Comparison –using the parameter –to a certain condition to
decide when to end the loop.
■ Calculation inside the loop
Initialize a
parameter
Condition
for the
loop
start
calculation
Types of Loops
■ For loop  When you know how many times of
operations’ iterations to repeat the loop.
■ While loop  It repeats the instructions till a certain
condition is met.
■ Midpoint break loop It is useful for situations where the
commands in the loop must be executed at least once ,till
some condition is met.
Remember in
C++ the do-while
loop?
For Loop:
■ General form:
for index = [ matrix]
commands to be executed
end
■ If k (the index) is a matrix,
MATLAB uses an entire column as
the index each time through the
loop.
■ Hint : once you have completed the
for loop , the index k retains the
last value used.
• For example if the loop repeated 5 times
, after breaking out of it k will be 5
K is a matrix ,
but at each
iteration ,it
takes one value
only.
New element is
added to the
matrix each
time
Practice:
■ A list of test scores , count the number of students above 90.
Ex :
■ Calculate the factorial with a for loop.
■ Use a counter to find how many values greater than 30 , x = [ 45,23,17,34,85,33].
■ Repeat the above exercise with the find command.
■ Use a for loop to sum the elements of x , check your result with the sum function.
While Loop:
■ General form:
while condition
commands to be executed
end
■ Hint :
• The variable used to control the
while loop must be updated every
time through the loop. If not,
you‘ll generate an infinite loop.
• In case of instructions that may
take a lot of time to be executed,
you can always exit the
calculation of a loop manually ,
type ctrl+c
Practice:
■ Consider x = [ 43 ,29 , 16 , 32, 85, 37] , use a while loop to
count how many values that are greater than 35.
■ Use a while to sum the elements in x.
■ Use a while loop to create a vector containing 10 elements
as shown:
Τ
1
1 , Τ
1
2 , Τ
1
3 , Τ
1
4 ……….. Τ
1
10
■ Use a while loop to create a vector containing 10 elements
as shown:
Τ
1
1 , Τ
−1
2 , Τ
1
3 , Τ
−1
4 ……….. Τ
−1
10
Break and Continue:
■ break  Used to terminate a
loop permanently even if the
comparison is still true.
■ continue  Used to ignore the
current iteration and continues
with the loop.
Midpoint Break Loop:
■ In this structure , the loop is
entered , calculations are
processed , and a decision is
made at some arbitrary point to
exit the loop.
■ The loop must be executed at
least once.
1 indicates
true, while
the
condition is
always true
The loop is
executed once
Or it will keep running until the
condition of num_candy <0 is false
You break
from a mid
point in the
loop
Nested Loops:
■ Examine the following
example:
• A loop for finding the sum of
every column in a matrix.
■ Hint :
• To know how much time your
calculations take to be
complete you can you the
command :
tic – toc
tic  before
the instructions
toc  after the
instructions

Matlab tutorial 3

  • 1.
    MATLAB TUTORIAL 3 ByNorhan Abdalla
  • 2.
    Outline: ■ Input /OutputControl ■ Logical Structures ■ Repetition Structures
  • 3.
  • 4.
    User Defined Input ■This is mainly when the program deals with a person other than the programmer. ■ Using the command ‘input’: ▪ It can be a scalar ▪ It can be a matrix ▪ It can be a string: • Having this ‘s’ as a parameter , means that you don’t have to insert the string in a single quotation
  • 5.
    Output ■ Using thecommand ‘disp()’ ■ If you want to include the apostrophe , you have to use it twice unless MATLAB will interpret it as terminating the string.
  • 6.
    Try this: ■ Youcan use a combination of the ‘input’ and ‘disp’ functions to mimic a conversation. Try this using an M-file
  • 7.
    Formatted Output ■ fprintfA function controls the output and adjust its format. • General form: fprintf( format setting , variable….) • % is a place holder for the variable and the variable is specified later. You can’t hold a place by just using ‘%’, a formatting style must be used
  • 8.
    Formatting the Output ■To insert new line , use (‘n’) Type Field Result %f Fixed-point notation %e Exponential notation %d Decimal notation( doesn’t include trailing zeros %g Whichever is shorter , %f or %e %c Character information( one character at a time %s String of characters( the entire string) Format command Result n linefeed r Carriage return t Tab b backspace
  • 9.
    Formatting the Output ■Adjusting the precision : ■ If a variable is a two dimensional matrix , MATLAB uses the values one column at a time. ■ Try this , What do you notice? 8.4 reserves a place for 8 digits 4 of them are decimals
  • 10.
    Formatting Output ■ Tooutput in a file , you first have to create a file ,open an output file and assign an identifier to it. ■ If you want to include a ‘%’ in an fprintf function , you must use it twice unless MATLAB will interpret it as a place holder. identifier Function that opens a file File’s name Write data to the file The output in the file
  • 11.
  • 12.
    Relation & LogicalOperators ■ MATLAB uses number 1 for true and 0 for false ( actually it takes any non zero number as true) ■ Notice the difference between ==(equal operator) and = (assignment operator). Relational Operator Interpretation < Less than <= Less than or equal > Greater than >= Greater than or equal to == Equal to ~= Not equal to
  • 13.
    Relation & LogicalOperators Logical Operator Interpretation & And ~ Not | Or xor Exclusive or && And (with scalars) || Or (with scalars) ■ The difference between & and && is that && is used for scalar quantities only. ■ & is used for expressions.
  • 14.
    Logical Functions Find ■ findSearches a matrix and identifies which element in that matrix meets a given condition. ■ Try this: Indexes Elements Try this using an M-file
  • 15.
    Practice: 𝑥 = 1 1042 5 8 78 56 45 9 6 23 13 y = 1 2 3 4 10 12 7 21 27 z = 10 22 5 13 23 22 8 9 • Find the elements in each matrix that are greater than 10. • Find the row and column numbers for elements in each matrix that contains values greater than 10 and less than 40. • Find the values in each matrix that are greater than 10 and less than 40. • Use the length command together with results from the find command to determine how many values in each matrix are between 0 and 10 or between 70 and 80. • Define the following matrices:
  • 16.
    Selection Structures ■ Thegeneral form : if comparison { statements } end
  • 17.
    Selection Structures ■ Thisstructure allows us to execute a series of statements if the condition is true , and skip those steps if the condition is false. ■ If x is a matrix ( x = 0:0.5:2;) , ‘if’ statement is true only ,if it is true for every element in the matrix. • Hint : MATLAB includes a function called ‘beep’ that causes the computer to “beep” at the user.
  • 18.
    Selection Structures ■ Thisstructure allows us to check multiple criteria while keeping the code easy to read. ■ Remember that : if age is a matrix , every condition is true for all the elements evaluates to true. Try to change age and notice the result
  • 19.
    Practice: ■ Try this: ■Grading Marks: • Prompt the user to enter the mark • Check the mark based on the mark table • Display the mark Mark Grade 90 to 100 A 80 to 90 B 70 to 80 C 60 to 70 D Less than 60 F
  • 20.
    Selection Structures Switch ■ Thisstructure allows you to choose between multiple outcomes , based on some criteria. ■ General form: Switch variable case option1 code for option 1 if true case option2 code for option 2 if true otherwise code to be executed if non of the cases were true end
  • 21.
  • 22.
    Basic Parts fora Loop ■ Parameter used to terminate the loop. ■ Initialization of the parameter. ■ Process that changes the parameter at each iteration. ( unless it becomes unstoppable ) ■ Comparison –using the parameter –to a certain condition to decide when to end the loop. ■ Calculation inside the loop Initialize a parameter Condition for the loop start calculation
  • 23.
    Types of Loops ■For loop  When you know how many times of operations’ iterations to repeat the loop. ■ While loop  It repeats the instructions till a certain condition is met. ■ Midpoint break loop It is useful for situations where the commands in the loop must be executed at least once ,till some condition is met. Remember in C++ the do-while loop?
  • 24.
    For Loop: ■ Generalform: for index = [ matrix] commands to be executed end ■ If k (the index) is a matrix, MATLAB uses an entire column as the index each time through the loop. ■ Hint : once you have completed the for loop , the index k retains the last value used. • For example if the loop repeated 5 times , after breaking out of it k will be 5 K is a matrix , but at each iteration ,it takes one value only. New element is added to the matrix each time
  • 25.
    Practice: ■ A listof test scores , count the number of students above 90. Ex : ■ Calculate the factorial with a for loop. ■ Use a counter to find how many values greater than 30 , x = [ 45,23,17,34,85,33]. ■ Repeat the above exercise with the find command. ■ Use a for loop to sum the elements of x , check your result with the sum function.
  • 26.
    While Loop: ■ Generalform: while condition commands to be executed end ■ Hint : • The variable used to control the while loop must be updated every time through the loop. If not, you‘ll generate an infinite loop. • In case of instructions that may take a lot of time to be executed, you can always exit the calculation of a loop manually , type ctrl+c
  • 27.
    Practice: ■ Consider x= [ 43 ,29 , 16 , 32, 85, 37] , use a while loop to count how many values that are greater than 35. ■ Use a while to sum the elements in x. ■ Use a while loop to create a vector containing 10 elements as shown: Τ 1 1 , Τ 1 2 , Τ 1 3 , Τ 1 4 ……….. Τ 1 10 ■ Use a while loop to create a vector containing 10 elements as shown: Τ 1 1 , Τ −1 2 , Τ 1 3 , Τ −1 4 ……….. Τ −1 10
  • 28.
    Break and Continue: ■break  Used to terminate a loop permanently even if the comparison is still true. ■ continue  Used to ignore the current iteration and continues with the loop.
  • 29.
    Midpoint Break Loop: ■In this structure , the loop is entered , calculations are processed , and a decision is made at some arbitrary point to exit the loop. ■ The loop must be executed at least once. 1 indicates true, while the condition is always true The loop is executed once Or it will keep running until the condition of num_candy <0 is false You break from a mid point in the loop
  • 30.
    Nested Loops: ■ Examinethe following example: • A loop for finding the sum of every column in a matrix. ■ Hint : • To know how much time your calculations take to be complete you can you the command : tic – toc tic  before the instructions toc  after the instructions