M04 - Programming in Matlab - XXXX - CH04
M04 - Programming in Matlab - XXXX - CH04
Control Structures,
Loops, and File Handling
4.1 Introduction
Logical decision-making and loops are two very important components in writing a computer
program. It is important to properly learn the syntax of conditional and loop structures. In this
chapter, conditional statements and loops in MATLAB are discussed.
Frequently, a user has to load data that is available in external files, perform certain com-
putations on it, and store the results in output files. Such file handling exercises form an
important part of MATLAB programming since files facilitate systematic recording and dis-
play of data. The latter part of this chapter discusses the handling of different types of files in
MATLAB.
conditional constructs provided by MATLAB: the if construct and the switch construct. The
if construct has two possible forms. The simpler of the two has the following syntax:
if (expression)
Statements1
end
Statements2
Hint: Use the input command in R = input (‘your input here’,‘s’) format, where
the presence of s makes sure that the input words are converted into string.
Also, the command B = lower(A) converts any uppercase characters in A to the cor-
responding lowercase character and leaves all other characters unchanged.
Example 4.1
Assign different grades to students based on the conditions given Example 4.1:
Using
below, using an if-else construction.
if-else
Marks > 85 70–84 55–69 40–54 < 40 construction
Grade A B C D F
The MATLAB script for the problem is written here:
grading.m
% script file to display the grade based on
% subject marks
Note that there can be multiple statements following a condition, as can be observed from the
section between else and end sections in the above m-file.
Example 4.2
Example 4.2: Suppose you are asked to enter a number (1 to 7) and the program
A complex
should display the corresponding day of the week. You can do it
if-elseif
example
using an if-else construction in the following manner:
>>day = input(‘Enter a number for the day (1to 7)’);
>> if (day == 1)
disp (‘Monday’)
elseif (day == 2)
disp (‘Tuesday’)
elseif (day == 3)
disp (‘Wednesday’)
Example 4.3
The switch-case construct provides a more elegant solution to Example 4.3:
Example 4.2 as can be seen from the following code: Learning
switch-case
selection-2.m commands
% A switch-case example
day = input(‘Enter a number for the day ( 1 to 7)’)
disp (‘The day is :’ )
switch(day)
case 1
disp (‘Monday’)
case 2
disp (‘Tuesday’)
case 3
disp (‘Wednesday’)
case 4
disp (‘Thursday’)
case 5
disp (‘Friday’)
case 6
disp (‘Saturday’)
case 7
disp (‘Sunday’)
otherwise
disp (‘Not a valid entry for the day’)
end
4.3 Loops
A loop is a structure for repeating certain set of statements a number of times. MATLAB uses
two types of loops: the for loop, which is used when the number of passes is known, and the
while loop, which is used when the looping process must terminate when a specified condi-
tion is satisfied and thus the number of passes is not known in advance. The general form and
syntax of these loops is as follows:
In the for loop, the specified variable is at first initialized to the init_value and the block of
statements until the end keyword is executed. Then the variable is incremented by the step
value and the block of statements is again executed. This is repeated until the value of the vari-
able exceeds the final_value. Note that in the absence of the step variable in for loop, the step
size has the default value of one. Like the conditional structures, the loops also require an end
statement indicating the termination of the loop.
In the while loop, the expression in front of while is evaluated, and if it is true then the
block of statements until the end keyword is executed. The control then returns to the begin-
ning, where the expression in front of while is re-evaluated. If the expression is still true, then
the block of statements is again executed. This continues until the expression becomes false.
The expression usually involves one or more variables, which are dynamically updated within
the statement block.
In Example 4.4, the value of variable i is incremented by one with each execution of
the for loop, thus executing the successive product as fact_n = 1 × 2 × 3 … × n. which
is the value of n! (factorial of n). The following program accomplishes the same thing
using a while loop.
looping-2.m
% factorial using a while loop
n = input (‘input the number :’);
fact_n = n; i = 1;
while i <= (n - 1)
fact_n = fact_n * i;
i = i + 1;
end
disp (‘factorial of the number is :’),disp (fact_n);
Although in most situations a for loop can be replaced with a while loop and vice
versa, in case of a conditional repetition you should use a while loop. In the following
example, the use of a while loop is more appropriate than a for loop.
Example 4.5
Example 4.5:
The exponential power of x is approximated by the following infi-
Finding the
nite series:
sum of an infinite
ex = 1+ x + (x2/2!) + (x3/3!) + (x4/4!) + … series
Find out how many terms will be sufficient in the right-hand side of
the given expression to ensure that the result is within the 5% error
of the exact value. Assume x has a value of 5.
Solution
The m-file for this problem can be written as follows:
exp_power.m
% computing the exponential power with a series
x = 5;
exact = exp (x);
%computes the exact value
n = 1;
% n is number of terms
sum_terms = 1;
% stores the sum for n terms
error = (exact - sum_terms)*100/exact;
% percentage error value
while (error > 5)
n = n + 1;
next_term = power (x, n)/factorial (n);
sum_terms = sum_terms + next_term;
error = (exact - sum_terms)*100/exact;
end
In Example 4.5, the variable next_term computes the next term of the given series
within the while loop, which is then added to the variable sum_terms. The process
continues till the difference between the exact value of the series (given by the variable
exact) and the summation of computed terms is within a desired error level (taken as
5% here).
Example 4.6
Example 4.6: This example illustrates a nested loop structure. The program
A nested loop keeps asking the user whether he would like to continue comput-
example
ing the factorial of more numbers and displays the results until the
user selects the choice “No” (by entering n or N).
looping-3.m
% factorial for numbers using a nested loop
% structure
choice = ‘y’;
while(choice ~= ‘n’)
n = input (‘input the number :’);
fact_n = n;
for i = 1: n - 1
fact_n = fact_n * i;
end
disp ( ‘factorial of the number is :’),
disp (fact_n);
c = input (‘do you want to find the factorial
for another number ? (y/n):’, ‘s’);
choice = lower (c);
end
In Example 4.6, the for loop is nested inside the while loop. Nesting is possible for
any combination of loops and/or control structures, but nesting beyond a certain level is
not recommended, as it makes the program very difficult to interpret. Whenever we use
Here, as soon as a negative number is entered, the control is transferred to the end of the while
loop, and the program terminates. As an exercise question, replace break with continue
and see what happens.
M-files are ASCII (American Standard Code for Information Interchange) files written in
MATLAB language. ASCII refers to a format designed to make files usable across a wide vari-
ety of software. Being ASCII files, M-files can be created and edited in any word processor or
text editor. M-files are therefore machine independent. MAT-files on the other hand are binary
files and not ASCII files. Binary files are usually readable only by the software that created
them, so we cannot read a MAT-file with a word processor. In general, transferring binary files
across different machine types is not easy. However, MAT-files contain a machine signature
that allows them to be transferable. MAT files can also be manipulated by programs external to
MATLAB. Binary files provide more compact storage than ASCII files.
In the following section, we will discuss how to save data/statements/commands into files or
load data/ statements/commands from external files in MATLAB.
After this is typed, a file with the specified name is created in the current working directory.
A copy of all subsequent command window inputs (including your mistakes!) and most of the
resulting command window outputs are appended to this file (abc here). If no filename is speci-
fied, the default file name “diary.mat” is used.
If you want to access/modify certain entries in the recorded diary file, you can use one of the
following options:
The diary file must be present in the current working directory or within a folder that is located
in MATLAB path (you can use File/Set Path to do so). The advantage is that once a MATLAB
session has been recorded in a diary file, you can view all the entries of that session at a
later time.
diary off suspends the recording.
diary on turns it back on and appends the subsequent entries to the named diary file.
diary by itself, toggles the diary state.
get(0, ‘Diary’)lets you know whether the diary is on or off.
get(0, ‘DiaryFile’)lets you know the name of the current diary file.
Following is an example of recording a MATLAB session:
Example 4.7
Consider the following example of a MATLAB session: Example 4.7:
Recording a
>> diary (‘session-1’) MATLAB session
% begins recording the entries into file in a file
% ‘session-1.mat’
>> a = [1 2 3 4 5]
a =
1 2 3 4 5
>> b = a^2
??? Error using ==> ^
Matrix must be square.
>> b = a.^2
% note the use of a dot operator
b =
1 4 9 16 25
>> diary off
% recording suspended
>> c = a + b
c =
2 6 12 20 30
>> clc
% clears the screen
>> edit session-1
Note that nothing is recorded after the command diary off is issued.
The variable a is inaccessible now (though it was recorded in a diary file). Begin a fresh session
with the following:
>> a = [1 2 3 4 5]
a =
1 2 3 4 5
>> b = a.^2
b =
1 4 9 16 25
>> c = a + b
c =
2 6 12 20 30
>> save f1 a b c
% saves the variables a b and c into a file
% named ‘f1.mat’
The variable a is inaccessible, since we used clear all. Yet, the variable is saved in the file “f1.
mat”. To retrieve the saved variables into the workspace, type the following command:
>> load f1.mat
% load the file ‘f1.mat’
>> a
a =
1 2 3 4 5
Thus, using the save and load commands, you can anytime access all the workspace variables of
a particular session and resume your computation from where you left last time.
Some important file-handling commands are shown in Table 4.2:
Command Usage
save Saves all the workspace variables in the file matlab.mat
save f1 Saves all the workspace variables in the file f1.mat
save f1 Saves the workspace variables listed by variables in the file f1.mat
variables For example, save f1 a b c saves only the variables a, b, and c.
save f1 - Adds the workspace variables to the existing MAT-file f1.mat; if
append you do not use append option, the existing variables will be erased
and the present workspace variables will be placed instead
load Loads all the variables stored in the file matlab.mat
load f1.mat Loads all the variables stored in the file f1.mat
delete Deletes the file filename
filename
P = Reads the numeric data from the first sheet in the Excel file f1.xls
xlsread(‘f1’) and stores them in the matrix P. Make sure that the file f1.xls is
present in the MATLAB path
[P, Q] = Reads the numeric data from the first sheet in the Excel file f1.xls
xlsread(‘f1’) and stores them in the matrix P and reads the text data from the same
file and stores them in matrix Q
where fid can be any variable name. This variable will contain the address returned by
MATLAB to identify the particular file if it has been successfully opened. The filename is
the actual filename and should be placed in single quotes. The permission string speci-
fies whether the file will be opened for reading or for writing; for example, the string w per-
mits writing to the file. A full list of the various permissions can be obtained by typing help
fopen.
Again, the fid identifies the file that was opened using the fopen command. The format
refers to the formatting of the data. Its syntax is identical to that in the C language. For example,
to print a floating point number with two digits before the decimal point and three digits after
the decimal point, use %2.3f. The % symbol signifies that the value will be obtained from
a variable. All formatting must be contained within single quotes. All non-% characters will
appear directly. For example, if the format is %1.2f newtons %1.4f meters, and
%2.1f pascals\n then the line will appear as: x.xx newtons x.xxxx meters, and xx.x
pascals (\n signifies the carriage return). Following is a list of specifiers that allow you to
insert numbers into sentences using fprintf ():
1. %f: floating point number, decimal notation
2. %e: exponential notation
3. %g: either decimal or exponential notation, whichever is shorter
4. %d: integer
Finally, matrix is the name of the variable that will supply values to the % symbol marker. It is
important to note that MATLAB will read the matrix column-wise, meaning that the order in
which the values will appear in the output is each value in column 1, followed by each value in
column 2, and so on. Thus, it is often necessary to use the transpose of your matrix in order to
output the data to the file in the same form as it appears on the computer screen.
The arguments fid and format are the same as fprintf(). The argument size tells
fscanf() how many characters to read from the file. It is optional and it puts a limit on the
number of elements that can be read from the file. If it is not specified, then the entire file is
considered. Valid entries for size are as follows:
1. N: read at most N elements into a column vector
2. Inf: read at most to the end of the file
3. [M,N]: read at most M * N elements filling at least an M-by-N matrix, in column order.
N can be inf, but not M
The combination [A, count] is a vector returned by fscanf(), the first element of which
is a matrix A, holding all values read from the file. The second element count is the number of
items read from the file. count is optional.
Example 4.8
Let y be the function of x, such that: y = x3 + 2*x2 - 2*x +3 Example 4.8:
Find the value of y for each value of x in the interval (x = –1: . Writing into a
2 : 1). Store both x and y column-wise in a file “result.txt”. Then file and reading
data from it
use MATLAB commands to read back from the file “result.txt”,
and plot the values of y with respect to x, as stored in the file.
Solution
The MATLAB code for the specified task is given here:
handle_file.m
% Example of File handling
x = -1:.2:1;
y = x.^3 + 2*x.^2 - 2*x +3;
% y is a function of x (note the dot
% operator preceding the symbols ^ )
fid = fopen (‘result.txt’,‘w’); % opens a file named
% ‘result.txt’in write mode and gives the
% file an ID in the variable fid.
fprintf(fid,‘%6.2f %12.8f\n’, [x; y]);
% Writes into the file specified by ID, the
% values of x and y column wise.
fclose(fid);
% Now close the file.
A'
% Get the transpose of A.
The two columns indicate the values of x and y respectively. Now you can plot them with
the command:
>> plot (ans (:,1), ans(:,2))
>> xlabel(‘x’); ylabel(‘y’);
6
5.5
5
4.5
y 4
3.5
3
−1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 0.6 0.8
x
Example 4.9
This example illustrates the reading and modifying of formatted Example 4.9:
Reading and
text data. Let “phones.txt” be a file containing the phone numbers
modifying the for-
of some faculty in a department. Following are the contents of the
matted text data
file: in a text file
phones.txt
Acharya Shankar 5517
Bhat Balakrishna 3197
Sharma Murari 3177
The data has three different fields: last name, first name, and phone number. You can read
these fields with the following MATLAB statement:
[lname, fname, phone] = textread(‘phones.txt’, ‘%s %s %d’)
textread is used to read a formatted data from a text file. The general format is:
% [a,b,c,…] = textread(filename, format, n);
% filename: is a string containing the name of
% the file to be read,
% format: is a string containing the format
% primitives (as in fprintf), and
% n: is number of lines to be read (if not
% specified, the file is read until the end)
MATLAB responds to this command as:
lname =
‘Acharya’
‘Bhat’
‘Sharma’
‘Narayanan’
‘Gupta’
fname =
‘Shankar’
‘Balakrishna’
‘Murari’
'Ravi’
‘Hariom’
phone =
5517
3197
3177
5819
1208
The following program illustrates how to modify a certain phone number in the mentioned
text file:
phones2.m
% Updates the phone number of a person
%Read the phone numbers
[lname,fname, phone] = textread( ‘phones.txt’, ‘%s %s %d’ );
%Get the name and the new phone number
for i = 1:length(lname),
if ( strcmp( lname(i), name ) ),
phone(i) = new_phone;
end
end % Write the updated phone
% numbers into a new file
fclose( fid );
The changed number is displayed as entered by the user. Note that the mentioned
textread command results in only two fields. This is because the textread
command skips the columns that have an asterisk (*) in the format descriptor.
Following is another program that illustrates the method of modification in the name
fields of the file “phones.txt” :
phones3.m
%Updates the name of a person
%Get the old and new names form the user
old_name = input( ‘Enter the old name:’, ‘s’ );
new_name = input( ‘Enter the new name:’, ‘s’ );
%Open the input file
Let us read the output file to check whether the given name field is modified:
lname =
‘Acharya’
‘Bhat’
‘Sharma’
‘Narayanan’
‘Gupta’
fname =
‘Shankar’
‘Balakrishna’
‘Murari’
‘Ravi’
‘Radheshyam’
SUMMARY
In this chapter, we studied the basic loops and selection structures available in MATLAB.
Any loop or selection structure in MATLAB must be terminated by the end keyword;
otherwise it will lead to an error. While designing loops or control structures that take
user input, it is a good programming practice to provide an error message following loop
termination due to invalid user input. The commands break and continue find special
usage in this case.
MATLAB uses different file types for different purposes. Program codes are always
stored in m-files, whereas data are saved in files with an extension “.mat”. “.mat” files are
in binary file format; however, the user can also specify a particular storage format and
file extension name as per the requirement. Apart from handling external files through
fprintf and fscanf commands, MATLAB also provides special commands to deal
with the data that are written in tab separated or comma separated, or other specific file
formats.
EXERCISES
4.1. The cumulative amount for an investment with a compound interest is given by the fol-
lowing formula: a = p(1 + r)n, where a = cumulative amount at the end of the nth year,
p = initial sum, and r = annual interest rate.
Calculate the cumulative sum at the end of each year up to 10 years for an initial investment
of $10,000 with an annual interest rate of 5%.
4.2. Find the sum of the first n terms of the following series, where x and n are user inputs:
(a) Sum = 1 - (1/1!) + (2/2!) - (3/3!) + (4/4!) … (n/n!)
(b) Sum = x + (x2/2!) + (x4/4!) + (x6/6!) … (xn/n!)
(c) Sum = x - (x3/3!) + (x5/5!) - (x7/7!) … (xn/n!)
4.3. Write a MATLAB script that checks whether a number entered by the user is a perfect
number or not. (A perfect number is one whose all divisors sum up to give the number
itself. For example, the number 28 is a perfect number as 1 + 2 + 4 + 7 + 14 = 28.)
4.4. What does the following script do?
(a) What happens if the Boolean expression in the while statement is replaced by the
following?
v(i)>0 & i<=length (v)
(b) Change the script file to find the sum of the negative elements at the start of the vector.
4.5. Given two positive integers N1 and N2, write a program that calculates their greatest com-
mon divisor. The greatest common divisor can be calculated easily by iteratively replacing
the larger of the two numbers by the difference of the two numbers until the smaller of the
two numbers reaches zero. When the smallest number becomes zero, the other gives the
greatest common divisor.
You will need to use a while loop and an if-else statement. The larger of two num-
bers can be obtained using the built-in function max (A, B). The smaller of two numbers
can be obtained using the built-in function min (A, B).
4.6. Write a program to perform the numerical integration of finding the area of a quarter circle
as follows. The area of a small strip of width dx at a distance x from the center is given
as dx*h. If we integrate the area for x = 0 to x = R, we get the area of the quarter circle.
h can be expressed in terms of x and R. The integration of area dx*h can be implemented
as a summation with x incremented as x = x + dx. Implement this procedure in a MATLAB
program, in which the user inputs the radius R and the increment dx. The program should
finally display the error in the computed result based on the actual value of area (p *R2/4).
Observe the variation of computed area with respect to the increment dx.
R
h
dx