Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
34 views

M04 - Programming in Matlab - XXXX - CH04

This document discusses control structures, loops, and file handling in MATLAB. It covers conditional statements like if-else and switch-case structures that allow logical decision making in programs. It also discusses various loops and nested loops. The latter part of the chapter talks about handling different file types in MATLAB, which is important for tasks like loading data from files, performing computations, and storing results.

Uploaded by

Insignia D.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

M04 - Programming in Matlab - XXXX - CH04

This document discusses control structures, loops, and file handling in MATLAB. It covers conditional statements like if-else and switch-case structures that allow logical decision making in programs. It also discusses various loops and nested loops. The latter part of the chapter talks about handling different file types in MATLAB, which is important for tasks like loading data from files, performing computations, and storing results.

Uploaded by

Insignia D.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

4

Control Structures,
Loops, and File Handling

After studying this chapter, you should be able to:


 use conditional statements in programs  learn file handling in MATLAB
 learn various loops, nested loops,
and conditional breaking of control
structures

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.

4.2 Conditional Statements


In simple programs, execution begins with the first statement of the program and proceeds
in a straight-line manner to the last statement with every statement along the way executed
once. However, general problem solving requires the ability to control which statements are
executed and which do not depend on certain conditions. For example, an engineer may have
to use a different set of formulas depending on the value of a given parameter. Thus, condi-
tional decision-making is one of the basic features of a programming exercise. There are two

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 105 1/15/2014 2:22:55 PM


Control Structures, Loops, and File Handling  É 106

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

Expression refers to the logical Expression that determines whether Statements1 is to be


executed.
Statements1 consists of a group of statements.
Statements2 consists of statements following the if construct.
end is the keyword given to terminate the group of commands.
When an if statement is reached within a program, the expression following the keyword if
is evaluated. If the expression is true, the statements denoted by Statements1 are executed, oth-
erwise they are not executed. In either case, program execution proceeds to the next statement,
denoted by Statements2, in the program. In other words, the statements denoted by Statements2
are executed regardless of the execution of Statements1.
Consider the following example. Given the marks obtained by a student in a certain subject,
the following program displays “Pass”, if the marks are greater than 35:
>> marks = 57;
% the variable has to be assigned a value
% before we can use it in an expression;
>> if (marks > 35)
disp (‘Pass’)
end
% it will not display anything unless you put an ‘end’

Time for Practice 4.1


An electricity board charges the following rates to domestic users to discourage large con-
sumption of energy:
1. For the first 100 units: 40 cents/unit
2. For the next 200 units: 50 cents/unit
3. Beyond 300 units: 60 cents/unit.
All users are charged a minimum of $200. If the bill amount so estimated is more than $250,
then an additional surcharge of 15% (of bill amount) is added. Write a program to read the
number of units consumed and print the total electricity bill.

On execution, MATLAB displays “Pass”.


Consider another example as follows:
>> a = 3; b = 2;
>> if (a > b) disp (‘a is larger’); disp(‘b is smaller’); end
>>c = 5

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 106 1/15/2014 2:22:55 PM


107 Ñ 
  Conditional Statements

MATLAB responds as follows:


a is larger
b is smaller
c = 5
The second form of the if statement deals with programming situations where different actions
are to be performed based on the value of a logical expression. This form of the if construct
has the following syntax:
if (Expression1): logical expression
  Statements1: statements to be executed if Expression1 is true
elseif (Expression2): logical expression
  Statements2: statements to be executed if Expression2 is true
else
  Statements3: statements to be executed if Expressions 1 and 2 are not true
end: denotes the end of if block
 Statements4: statements following the if block
The logical expression in the above if construct involves the relational (or comparison) opera-
tors, such as greater than (>), less than (<), equal to (==), not equal to (~=), and greater than or
equal to (>=), which can also be combined with logical operators such as AND (&), OR (||), and
NOT (~). The following example illustrates the use of the if-elseif-else construction.

Time for Practice 4.2


Write an m-file program that uses the switch-case construction to display a number cor-
responding to a day (supposing that numbers one to seven belong to days in the order of
Monday to Sunday, respectively) when the user enters its first three letters. Make sure that your
program displays the correct result regardless of whether the input is in capital or small letters.

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

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 107 1/15/2014 2:22:55 PM


Control Structures, Loops, and File Handling  É 108

marks = input(‘Enter the marks :’) % prompts the


  % user to enter the marks at the command prompt
if (marks >= 85)
  disp (‘Grade: A’);
elseif (marks >= 70)
  disp (‘Grade: B’);
elseif (marks >= 55)
  disp (‘Grade: C’);
elseif (marks >= 40)
disp (‘Grade: D’);
else
  disp (‘Grade: F’);
disp (‘You have to take the course again’);
end

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.

4.2.1 The switch-case Selection Structures


The general form of the switch-case construction is given here:
switch switch_expr
case case_expr1
  statements
case case_expr2
 statements
case case_expr3
 statements
otherwise
 statements
end
In the switch-case construction the switch_expr is a variable name, and the case expressions are
either numeric or character constants. Depending upon which one of the case expressions matches
the value of the switch_expr variable, the block of statements under that case expression is exe-
cuted. The statements under other case expressions are not executed. If none of the case expressions
matches the switch_expr, the block of statements under the otherwise section is executed. Using
end statement is a must at the termination of every if-else or switch-case construction.
Note: Unlike other programming languages, the case sections do not require any break state-
ments, since the switch statement here does not follow the “fall-through” principle.

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)

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 108 1/15/2014 2:22:55 PM


109 Ñ 
 Loops

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:

for variable = init_value: step : final_value while (expression)


 statements   statements
end end

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

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 109 1/15/2014 2:22:55 PM


Control Structures, Loops, and File Handling  É 110

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.

Example 4.4: Example 4.4


Find the The following two script files compute the factorial of a given
factorial usage of number using for and while loops:
for and while
loops looping-1.m
% factorial using a for loop
n = input (‘input the number :’);
fact_n = 1; % initialization of the variable fact_n
for i = 1: n
fact_n = fact_n * i;
end
disp(‘factorial of the number is :’)
disp (fact_n);

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.

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 110 1/15/2014 2:22:55 PM


111 Ñ 
 Loops

Time for Practice 4.3


The above codes for factorial in Example 4.4 do not produce right results if the input is a nega-
tive number or zero. Make the necessary changes in the code to generalize it for these cases.
Use the loop structures and the conditional statements to do the same.

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

disp (‘the exact value = ’), disp (exact)


disp (‘computed value = ’), disp (sum_terms)
disp (‘no. of terms required = ’), disp (n)

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).

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 111 1/15/2014 2:22:56 PM


Control Structures, Loops, and File Handling  É 112

The output of the program is:


>> the exact value =
  148.4132
computed value =
  141.3806
no. of terms required =
  10

Time for Practice 4.4


Write a program to evaluate sine value of an angle (in degrees) entered by the user using
the following series.
sin (x) = 1 - x 3/3! + x 5/5! - …
Prompt the user to enter the number of terms to evaluate. Display the percentage error
involved based on the difference between the values estimated and computes using the
standard C++ library function. The program should terminate if a negative angle is entered.

4.4  Nested Loops


Loops and/or conditional statements can also have a nested structure, where one loop contains
another loop within its statement block.

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

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 112 1/15/2014 2:22:56 PM


113 Ñ 
  Breaking Control Structures (Break and Continue)

nesting, it is a good programming practice to use appropriate indentation to indicate the


statements belonging to a particular loop or control structure.
Note that MATLAB also provides a library function factorial to compute the
factorial of a number and you can verify your results using this function.

4.5  Breaking Control Structures (Break and Continue)


There are two commands in MATLAB, break and continue, that can be used for any
abnormal termination of a loop.
The break command terminates the execution of a for or while loop. Statements in the
loop that appear after the break statement are not executed. In nested loops, break exits only
from the loop in which it occurs. Control passes to the statement that follows the end of that loop.
The continue command passes the control to the next iteration of the for or while loop
in which it appears, skipping any remaining statements in the body of the loop. In nested loops,
continue passes control to the next iteration of the for or while loop that encloses it.
Thus, the difference between a break and a continue statement is that while break
transfers the control to the end of the loop, continue transfers the control to the beginning of
the loop in which it appears.
In the code for factorial, what will happen if the user inputs a negative number? You may like
to quit the program in this case or simply ignore that entry and continue on with a new entry.
How do we accomplish this? Try the following code:
looping-4.m
% factorial for numbers using a nested loop
% structure
% breaking the control for a negative number
choice = ‘y’;
while(choice ~= ‘n’)
n = input (‘input the number :’);
if (n < 0)
disp (‘Invalid input for a factorial’)
break;
% transfers the control to the end of the loop
end
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

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.

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 113 1/15/2014 2:22:56 PM


Control Structures, Loops, and File Handling  É 114

4.6  File Types in Matlab


MATLAB uses several types of files. Table 4.1 shows some of the most common MATLAB
files:

Table 4.1  MATLAB file extensions

File Extension File Type/Description


.m These are program files, known as M-files. When you execute a .m file,
all the statements in it are processed in sequence as if they were entered
at the command prompt. Files with .m extension are also used for
MATLAB functions.
.mat These are MATLAB data files, used to save the names and values of the
variables created during a MATLAB session.
.mdl These are files of models that are created with Simulink and other
Blocksets/ Toolboxes of MATLAB.
.fig These are the figure files. Any plot in MATLAB is stored in files with .fig
extension. However, you can choose to save these plots with other file
extensions (such as .jpg, .tif, .eps, etc.) by using the Export menu (select
File/Export in a .fig file).

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.

4.7  Recording a MATLAB Session


You can keep track of every action performed during a MATLAB session using the diary com-
mand. The syntax of this command is:
diary (‘abc.m’) or diary(‘abc.mat’)

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.

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 114 1/15/2014 2:22:56 PM


115 Ñ 
  Recording a MATLAB Session

If you want to access/modify certain entries in the recorded diary file, you can use one of the
following options:

>> type ‘file name’


or,
>> edit ‘file name’

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

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 115 1/15/2014 2:22:56 PM


Control Structures, Loops, and File Handling  É 116

% displays the diary file as below:


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
% must use dot operator
b =
1 4 9 16 25
diary off
% recording suspended

Note that nothing is recorded after the command diary off is issued.

4.8 Saving and Retrieving Workspace Variables


and Spreadsheet Data
In certain situations, we may not be interested in saving all the statements and outputs in the
session to a file, but we may like to save only the variables used in that session so that we can access
them when we restart working on MATLAB at a later point of time. The diary command does not
solve this purpose. Try the following soon after the previous MATLAB session in Example 4.7.
>> clear all
% clears all the variable from MATLAB Workspace
>> a
??? Undefined function or variable ‘a’.

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’

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 116 1/15/2014 2:22:56 PM


117 Ñ 
  Handling External Files

>> clear all


% clear the Workspace now
>> a
??? Undefined function or variable ‘a’.

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:

Table 4.2  File-handling commands

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

4.9  Handling External Files


Non-.mat input/output files are handled in a manner similar to that in the C programming
language, namely with the fopen, fscanf, fprintf, and fclose commands.

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 117 1/15/2014 2:22:56 PM


Control Structures, Loops, and File Handling  É 118

4.9.1  Opening a File


In order to operate on any external file, first the file must be opened in the following way:
fid = fopen(‘filename’,‘permission’),

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.

4.9.2  Writing to a File


The fprintf command allows you to write to the file. Its format is as follows:
fprintf(fid,‘format’,matrix)

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.

4.9.3  Reading from a File


The fscanf command is used to read from a specified file. It has the following syntax:
[A, count] = fscanf (fid, format, size)

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

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 118 1/15/2014 2:22:56 PM


119 Ñ 
  Handling External Files

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.

4.9.4  Closing a File


After opening and reading or writing to/from a file, it is good practice to close the file. This tells
MATLAB that you are done with the file. If you do not close a file, it may remain open and
eventually MATLAB will run out of file-ID’s and give you a mysterious error. So, close your
files once the job is over with the following command:
fclose(fid);
Here is a short summary of some of the most important MATLAB file handling functions:
1. ID=fopen (name, permission) opens the file specified by name with the specified
permission (‘r’ stands for read, ‘w’ stands for write, ‘a’ stands for append) and a value
is stored to ID with which the file can be accessed later.
2. Fclose (ID) closes the file specified by ID.
3. Fprintf (ID, format, A,...) writes formatted data to the file specified by ID.
format is a string containing C conversion specifications. If no parameter ID is passed,
fprintf writes to the screen.
4. [A, count]=fscanf (ID, format, size) reads formatted data from the file
specified by ID. format is a string containing C conversion specifications. The size
parameter puts a limit on the number of elements to be read from the file (optional). The
data read from the file are stored to A. If the optional output parameter count is used, it is
assigned the number of elements successfully read.
5. fseek(ID, offset, origin) changes the file position inside the file specified by ID
to the location specified by the offset parameter relative to the location specified by the
origin parameter. There are three possible values for origin: ‘bof’ or -1 refers to
the beginning of the file, ‘cof’ or 0 refers to the actual file position, ‘eof’ or 1 refers to the
end of the file. If the value of offset is greater than zero, the position is moved toward
the end of the file; if it is less than zero, the position is moved toward the beginning of the file.

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.

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 119 1/15/2014 2:22:56 PM


Control Structures, Loops, and File Handling  É 120

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.

fid = fopen (‘result.txt’);


% Open the file ‘result.txt’, and assign it an
  % ID with variable fid.
A = fscanf (fid,‘%g %g’,[2 inf])
% Scan the data stored in the file and store it
% into a matrix A. Matrix A has two rows now.

A'
% Get the transpose of A.

This program results in the value of A as:


ans =
-1.0000 6.0000
-0.8000 5.3680
-0.6000 4.7040
-0.4000 4.0560
-0.2000 3.4720
0      3.0000
0.2000 2.6880
0.4000 2.5840
0.6000 2.7360
0.8000 3.1920
1.0000 4.0000

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’);

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 120 1/15/2014 2:22:56 PM


121 Ñ 
  MATLAB Import Wizard

Figure 4.1 shows the resulting plot:

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

Figure 4.1  Plot

Time for Practice 4.5


Use MATLAB to create a table of square roots, squares, and cubes of first 10 even numbers.
The results should be stored in a file. Follow this scan and get the cubes of the numbers and
display them at the MATLAB command prompt.

4.10 File Handling (Specific Formats) [csvread, csvwrite,


dlmread, and dlmwrite]
For some input/output formats, there is an easier way of handling files.  Comma-separated
variable (.csv) files can be read/written using the csvread/csvwrite  commands. These
commands are derived from the more general dlmread/dlmwrite  commands which can
read/write data separated by delimiters such as tab, space, and comma. See the help for each of
these commands for more details.

4.11  MATLAB Import Wizard


The MATLAB also facilitates a Graphical User Interface (GUI) for importing data from files in
different formats into the MATLAB workspace. You can use the MATLAB command uiimport
to start the import wizard, and then follow the directions given. Use MATLAB help to see the
details of MATLAB import wizard.

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

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 121 1/15/2014 2:22:56 PM


Control Structures, Loops, and File Handling  É 122

Narayanan Ravi 5819


Gupta Hariom 1208

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

name = input( ‘Enter the last name of the person: ’, ‘s’ );


new_phone = input( ‘Enter the new phone number: ’ );

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 122 1/15/2014 2:22:57 PM


123 Ñ 
  MATLAB Import Wizard

%Find the person and update the 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

fid = fopen( ‘phones_new.txt’, ‘wt’ );


for i = 1:length (fname),
fprintf( fid, ‘%s %s %d \n’, lname{i}, fname{i}, phone(i) );
end

fclose( fid );

Executing this program requires user inputs as follows:


Enter the last name of the person: Sharma
Enter the new phone number: 1234

You can verify the changed number with:


>> edit phones_new.txt

or, using the following MATLAB command:


>> [lname,phone] = textread(‘phones_new.txt’, ‘%s %*s %d’)
lname =
‘Acharya’
‘Bhat’
‘Sharma’
‘Narayanan’
‘Gupta’
phone =
5517
3197
1234
5819
1208

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.

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 123 1/15/2014 2:22:57 PM


Control Structures, Loops, and File Handling  É 124

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

fid1 = fopen( ‘phones.txt’, ‘rt’ );


%Open the output file
fid2 = fopen( ‘phones4.txt’, ‘wt’ );

%Read the input file one line at a time


line = fgets( fid1 );

while ( line > 0 ),

%Replace the old name with the new name


line2 = strrep( line, old_name, new_name );

%Write to the output file


fprintf( fid2, ‘%s’, line2 );

%Read the next line of the input file


  line = fgets( fid1 );
end
%Close the files
status = fclose( ‘all’ );

Execute this program with the following user input:

Enter the old name: Hariom


Enter the new name: Radheshyam

Let us read the output file to check whether the given name field is modified:

>> [lname,fname] = textread( ‘phones4.txt’, ‘%s %s %*d’ )

lname =
  ‘Acharya’
  ‘Bhat’
  ‘Sharma’
  ‘Narayanan’
  ‘Gupta’

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 124 1/15/2014 2:22:57 PM


125 Ñ Programming Tips and Pitfalls

fname =
‘Shankar’
‘Balakrishna’
‘Murari’
‘Ravi’
‘Radheshyam’

The display indicates the changes.

Time for Practice 4.6


For the given text file "phones.txt" in the previous Example 4.9, write an m-file program
that takes the user input as the old phone number and asks for the new phone number to
modify the number and write the names and new numbers in a new text file.

Programming Tips and Pitfalls


1. An unbalanced control structure, such as missing an end statement can result in errors.
The key to avoid such mistakes is to consistently apply reasonable indentation conventions
throughout your programs, which also greatly improves the program’s readability.
2. Not providing a terminating condition in the body of a while structure results in a logical
error called an infinite loop, where the repetition structure never terminates. You must verify
if the terminating condition becomes false at some point.
3. Be careful in using floating-point numbers in terminating conditions. Floating-point num-
bers are represented only approximately by most computers. Thus, you may find out
(1/3)*3 - 1 is actually not equal to zero.
4. Using operator == for assignment and using operator = for equality are logical errors.
5. When using the files, make sure that you are in the right directory and that your file name is
typed correctly. MATLAB may not give any error if you make a mistake.
6. Always remember to close a file after writing in it.
7. Remember that different extensions in MATLAB imply different file types. Therefore,
always make sure that you are saving the file with the right extension.

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.

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 125 1/15/2014 2:22:57 PM


Control Structures, Loops, and File Handling É 126

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?

v = input(‘Enter a vector ’);


i = 1;
s = 0;
while i<=length (v) & v(i)>0
s = s + v(i);
i = i + 1;
end
disp (sprintf(‘The total is %4.2f.’,s))

(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.

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 126 1/15/2014 2:22:58 PM


127 Ñ 
 Exercises

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

M04_PROGRAMMING IN MATLAB_XXXX_CH04.indd 127 1/15/2014 2:22:58 PM

You might also like