Practical 4: For- and While- Loops, If-statements

Site: learnonline
Course: MATLAB
Book: Practical 4: For- and While- Loops, If-statements
Printed by: Guest user
Date: Saturday, 23 November 2024, 4:19 PM

Description

MATLAB Short Course

Practical 4

For- and While- Loops, If-statements

  • Use sequence controls- for, while, if-else
  • Create a for- loop to repeatedly execute statements a fixed number of times.
  • Create a while- loop to execute commands as long as a certain condition is met.
  • Use relational and Boolean operators
  • Use if-else constructions to change the order of execution.
  • Understand the purpose of count variables.

Working through this Practical

Go through this practical at your own pace and learn about the MATLAB environment in more detail.

  • The exercises are indented and on separate pages with shaded areas. Do these!
  • Ask your MATLAB eTutor if you have any questions or need advice using the Practical's Forum
  • MATLAB code will always be denoted by the Courier font.
  • An arrow > at the start of the line in an exercise indicates an activity for you to complete.
  • Use the arrows on the top right and bottom right of this display to move between pages, or select a page using the left hand navigation pane.
  • You can also print this resource as a single document (using the print icon in 1.9 or the Admin section in 2.5/2.6).

Please submit your responses to the activities within this practical for formative feedback from your MATLAB eTutor. Use this word document as a template to prepare your responses for submission.

Command Sequence Controls

MATLAB offers features to allow you to control the sequencing of commands by setting conditions. The following table shows the main types.

Command Action Example
for - loop Executes a set of commands repeatedly by incrementing a variable by a given step size until the set maximum is reached. For each hour from 1pm to 12pm, print the statement “it is <hour> o’clock”.
while - loop Executes a set of commands if a condition after while is true. You are asked to count during one minute. In other words, while chronometer hand have not done a whole circle, keep counting. In this case you do not know what will be your last number.
if-else statements

Executes a set of commands once, if a given condition is met, else- executes a set of commands, if the given condition is not met.

If the hour of the day is 6pm, print the statement “it is dinner-time, it’s <hour> o’clock”. Else the hour of the day is not 6pm, print the statement “it is not dinner-time, it’s <hour> o’clock”.

Syntax and Looping

The Syntax for for and while loops is as follows

for- loop syntax

for <variable> = <start>:<step>:<finish>

<commands>…..

……………..

end

while- loop syntax

while <condition>

<commands>…..%executed if condition is true

……………..

end

Example: for-loop versus while - loop

for i = 1:1:10

i=i+1 %***********

end

  • Note: the commandfor i=1:1:10’ does not create an array.
  • Note: the command ‘for i=1:1:10’ is equivalent to ‘for i=1:10’.

Now, let’s do the same by using while- loop

i=1; %we need to have a starting point to be able

to check the condition at the first time

while i<12 % to check is whether i<12 or not

i=i+1 %this command is the same as in for-loop

% we should get the next value of i

end

This way is a bit longer, so if you definitely know how many times you will need to do some commands, use for –loop. As you will see below, there are some situations, when using while-loop is the only way to solve the problem.

Example: (from a past MATLAB test)

> Calculate the sum S of elements ai =√2i-1, i=1, 2, ..., until the sum will exceed 20. Type in the following code and examine the output.

S=0; % Initial assignment for sum to be able to

% check condition

i=1; % first value for i is 1

while S<20 %condition to check

S=S+sqrt(2*i-1); % recurrent formula for S

i=i+1; % next i

end

number_of_loops=i-1 % do you know why i-1?

S % shows the final value

 

> Exercise: Understanding Looping

Type the above for- loop into MATLAB. How many times will the starred line of the previous example be executed? What are starting point, increment (step) and ending point of this loop?

Start:

Step:

End:

Total number of loops:

Operators

Relational Operators

Symbol Example Meaning of Example
< a<6 true if a is less than 6
<= a<=6 true if a is less than or equal to 6
> a>6 true if a is greater than 6
>= a>=6 true if a is greater than or equal to 6
== a==6

true if a is equal to 6 (note double equals sign)

~= a~=6 true if a is not equal to 6

Boolean Operators

Symbol Definition Example Meaning of Example
& And

(a>2) & (a<6)

a is greater than 2 and less than 6
| Or

(a>2) | (a<6)

a is less than 2 or greater than 6
~ Not ~(a==6) a is not equal to 6

 

Simple if- statements

if <expression>

<commands>…%executed only when

%expression is true

end

Example:

% This code assigns the value of x to negativeValue

% only if x is negative

x = 4;

if x<0

negativeValue = x

end

Exercise: Using Relational Operators

> What is wrong with the following code? Type it in MATLAB to check the error message.

% This code assigns the value of x to zeroValue only % if x is zero

x=4

if x=0

zeroValue = x

end

> What happens when x equals to zero or x is not zero?

if Statements

Complex if-elseif-else-end statements:

if <expression 1>

<command> % evaluated if expression 1 is true

elseif <expression 2>

<command> % evaluated if expression 2 is true

elseif expression3

<command> % evaluated if expression 3 is true

….

else

<command> % evaluated if none of expressions are true

end

Example:

% If x is negative, assign value of x to negativeValue

% If x is positive, assign value of x to positiveValue

% If x is zero, assign value of x to zeroValue

x=4

if x<0

negativeValue = x

elseif x>0

positiveValue = x

else

zeroValue = x

end

Exercise: Using if- statements

> Verify that the above code is correct by checking with a positive, negative and zero value of x. It will be faster to run the code from a script M-file.

> Why don’t we need to check if x is actually zero when assigning it to zeroValue?

Counter Variable

Often, loops involve a count or a counter variable that is updated each time the code within a certain condition is executed.

Exercise: Counter variable

> Type in the following code and verify the result.

wink Tip: Clear the Command Window by going to Edit>Clear Command Window.

% determine the number of elements in allNumbers bigger

% than 100

count = 0                         % initialize count

allNumbers = 200*rand(1,10);      % array of random numbers

for index = 1:1:10
    
if allNumbers(index)>100
         
count = count+1;        % update count
    
end

end
count                             % print count

Indenting

Indenting

Note that the above code has indents under each of for and if statement

Indenting makes code more readable, as you can see the logical structure which becomes especially important when you have several for/if statements in one M-file. While working on this practical, make sure that you follow this formatting convention.

Exercise: Counter variable

> Reconsider the above example without indenting. Which is easier to read?

 

wink Tip: There is an option called Smart Indent, which will indent highlighted code properly and automatically. See Indent>Smart Indent (the first icon) in the M-file Editor menu bar.

Example:

% determine the number of elements in allNumbers bigger
% than 100

count = 0;
for index = 1:1:10
if allNumbers(index)>100
count = count+1;
end

end
count

Debugging

 

Exercise:

> Complete the exercises in the script M-file for this week. Run each cell separately and follow the instructions, making sure that you also add in the required code marked by starred lines.

wink Tip: If you are having trouble finding an error, try commenting out a few lines to determine the line that is causing i. If you comment out a line containing for, while or if-else, don’t forget to comment out the corresponding end statements.

> Fill in the correspondent commands doing what required within **....**.

%% Practical 4

% Enter your name, student ID and the date here

%---------------------------------------------------------

%% Exercise 1

% Use a for- loop to print out the square of integers from 1 up to %maxValue.

maxValue = 10;
for num = % ** increment num from 1 to maxValue **
    num % this line simply prints num
    square = num^2 % this line prints the square
end

> Use array operations from Practical 3 to solve the problem in Exercise 1.

%% Exercise 2

% Use a while- loop to print out the square of integers from 1 up to

% maxValue.

maxValue = 10;
num=1;
while % ** num is not bigger than maxValue **
   
num % this line simply prints num
    square = num^2 % this line prints the square
   
num=num+1;
end

%--------------------------------------------------------

%% Exercise 3

% Sam gets paid compound interest at a rate defined at 5% per annum.

% Calculate his resulting investment each year and after 10 years.

% Change the rate on the 8th year to 5.75%

 

rate = 0.05;
investment = 5000;
for year = % ** increment the year from 1 to 10 **
    if % ** year is 8 **
       rate = 0.0575
    end
    year % this line simply prints the year
    investment = (1+rate)* investment % compounding function
end

%---------------------------------------------------------

%% Exercise 4

% create a graph that draws a straight line from the point (0,0) to

% every other

% point of the set (1,0), (1,1), (1,2), (1,3), (1,4).

hold on %allows us to plot multiple lines on a graph
for y = %** increment y **
    plot([0,1],[0,y]); % plot x coordinate and y coordinate arrays
end

hold off

%---------------------------------------------------------

%% Exercise 5A

% Use an if-else statement to check if an integer is either a prime % or a square number.

% Make sure you change the value of the integer.

% Check the help file to find a function that checks if a number is

% prime.

% note that this function works on both arrays and scalars.

integer = 4;
if % ** check if integer is a prime **
    Prime = integer % => If condition is met
elseif % ** check if the number is square **
   
Square = integer % => Else condition is met
end

%--------------------------------------------------------------

%% Exercise 5B

% Add some lines of code in the correct place above to check if the

% number is divisible by 6 and assign it to variable FactorOf6.

%% Exercise 5C

% Modify the above code as follows:

% Use a for-loop to check if each integer from 1 to 100 is a prime, % square or divisible by 6.

% Collect the integers that meet the above conditions to the % correspondent arrays Prime, Square or FactorOf6.

% Create count variables pCount, sCount and fCount which are updated % each time you find a new Prime, Square or FactorOf6 element and use % these counters to add new elements to your arrays.

% Print Prime, Square & FactorOf6 after your for- loop is finished.

Questions?

You may also wish to discuss these questions within the Practical 4 forum, also embedded below. If you think you know the answer, you are welcome to respond.

 

Submit

Please submit your response to Practical 4 for feedback (also embedded below). Use this word document as a template.