You are on page 1of 35

ENG 1060

Computing for Engineers


Lecturer: Dr V. Ganapathy
Lecture 11:
Lecture Outline
• MATLAB can be used to generate text files full of
information.

– For example you could create a table of information


which may be read into excel or exported to
another program.

• To investigate this use of MATLAB we will consider


the following:

• String manipulation
• Text file opening and closing
• The commands sprintf and fprintf
• The commands fgetl and fgets
2
Last Lecture
• In the last two lectures we considered function files.

• They allow programmers to compartmentalize an


algorithm.

• Function files allow a user to work on their small


section of codes, independently of other
programmers.

• This allows a programmer the opportunity to


upgrade a small component of a larger program
without altering other parts of the program.

3
TODAY’S LECTURE
• Today you will be learning several MATLAB commands -
a summary of the commands will be provided at the end
of the lecture for you to review.

• Although the commands are specific to MATLAB, almost


identical commands are used regularly in other
programming languages.

– In particular the languages C, C++ and Fortran all use


similar commands.

• Knowledge of these commands in MATLAB will help you


learn these other languages in future.

4
An Engineering Example…
• Flow past an aircraft is an active research area.

• To perform this task thousands of simulations are


run to determine what the flow in the wake of an
aircraft will do.

To tell the computer what to run


and when, I need thousands of
text files.

How do we write these text


files?

We use MATLAB. 5
String Manipulation
Creating a string in MATLAB
• Creating a string in MATLAB is easy! Enclose
the string in single quotes:

Variable1 = 'This is a string';

Variable2 = 'This is another string';

Third_Var = "This is not a string";

• MATLAB returns an error message if you type


the third command.

6
String Manipulation
• A string is essentially an array of letters:
Variable1 = 'This is a string';

>> Variable1(1)
ans = As with any other array, you
T can refer to individual elements
>> Variable1(2) within a string variable.
ans =
h You can also manipulate
>> Variable1(3) individual elements of a string:
ans =
i
>> Variable1(4)
ans =
>> Variable1(5) = 'A'
s
>> Variable1(11:16) Variable1 =
ans =
string
ThisAis a string
>> >>
7
String Manipulation
Creating a string from other variables
• You may want to change a number (either a double
or an integer) into a string, you can then use this in
creating other strings.

• The command num2str can achieve this for you:

MATRIX = [3.9872, pi; 4.13 2.6843];

String = num2str(MATRIX)

String = MATLAB returns String back to


the user.
3.9872 3.1416
Note that we have only
4.13 2.6843 converted the numbers to string
to four decimal places.
8
String Manipulation
• In order to get num2str to output more (or less)
decimal places to the string, we have to enter the
number of decimal places required:
>> variable = 3*pi;
>> string1 = num2str(variable,5)
string1 =
9.4248
What has gone wrong
>> string1 = num2str(variable,8)
here?
string1 =
MATLAB has not printed
9.424778
out 3 to 25 decimal
places…
>> string1 = num2str(variable,16)
string1 = This is an example of roundof
9.424777960769379 error, MATLAB only stores
number to 16 decimal places
>> string1 = num2str(variable,25) on my computer - it will not
string1 = print out any further decimal
9.4247779607693793 places using the num2str
>> command. 9
String Manipulation
Linking strings together
• As with many other programming languages,
MATLAB will provide an error message if you
attempt the following:
>> string_a = 'I have a fern in my office.';
>> string_b = ' It has green leaves.';

>> string_c = string_a + string_b


??? Error using ==> plus
Matrix dimensions must agree.

• If you want to add two strings together, you can use


the command strcat instead:
>> string_c = strcat(string_a,string_b)
string_c =
I have a fern in my office. It has green leaves.
>> 10
The sprintf Command
A command that can do it all!
• The sprintf command allows you to create strings, add
strings together and convert numbers to strings. In general,
we write:

String = sprintf(format,A,…)
• The format defines what the new string variable will look
like.

• A,… is a list of variables used by the format.

• Lets look at some simple examples…

11
The sprintf Command
Some Simple Examples

• We'll start by using sprintf to


create simple strings:

Variable1 = sprintf('This is a string');

Variable2 = sprintf('This is another string');

Third_Var = sprintf('A 3rd string');

12
The sprintf Command
Formatting strings using sprintf
• Now we will use sprintf to add two strings together:

Variable1 = sprintf(' I am interested in the number ');

Variable2 = num2str(pi,5);

Final_string = sprintf('%s %s',Variable1,Variable2)

Final_string =
I am interested
• Notice, that I haveinused
the the
number 3.1416 in the format to
%s command
inform sprintf that I will be entering in a string. There are two
strings entered here, Variable1 and Variable2.

13
The sprintf Command
Formatting strings using sprintf
• We can also use sprintf to include numbers in a
string:

Variable1 = sprintf(' I am interested in the number '

Final_string = sprintf('%s %f',Variable1,pi)

Final_string =
I• am interested
Notice, that I havein thethenumber
used 3.141593
%f command in the format to
inform sprintf that I will be entering in a floating point number.
The floating point number in this case is the number . Notice
that MATLAB prints this number to 8 decimal places.

14
The sprintf Command
Formatting strings using sprintf
• In fact it is possible to specify the following
types of numbers to include in a string:

%i : include an integer to a string


%f : include a floating point number to a string
%e : include a number with scientific notation

• Here are some examples:


>> sprintf('%i',round(pi)) >> sprintf('%e',sqrt(pi))

ans = ans =
3 1.772454e+000

15
The sprintf Command
Formatting strings using sprintf
• Finally, you can also specify the number of
decimal places, and also the number of
string elements that a number will take up:

• Consider the following two examples:


>> sprintf('%i%i',round(pi),round(exp(1)/2))
The second
ans = command
31 tells MATLAB
to use 5
>> sprintf('%5i%5i',round(pi),round(exp(1)/2)) spaces for
each number
ans =
3 1 16
The sprintf Command
Formatting strings using sprintf
• Finally, you can also specify the number of decimal
places, and also the number of string elements that
a number will take up:

• Consider the following two examples:

>> sprintf('%20.4f',pi/2) The first command tells MATLAB


to write /2 using 20 spaces and 4
ans = decimal places.
1.5708
The second command tells
>> sprintf('%20.18f', pi/2) MATLAB to write /2 using 20
spaces and 18 decimal places.
ans =
1.570796326794896600 Note the roundoff error.
17
Opening and Closing Text Files
File ID's and using
fopen
• Now that we can create strings, we will now consider how to write to and
read from a textfile.

• The first thing we have to do is tell MATLAB to open a file to either write to
or read from.
• To do this we use the command fopen:

FID = fopen(filename,permission)
• FID is a variable MATLAB uses to identify the file we are using(fid is a
number assigned to a file when it is opened, and it is used in all reading,
writing and control operations on that file).

• permission is a variable informing MATLAB what we would like to do with


the file.

18
Opening and Closing Text Files

File ID's and using fopen


• Lets consider some examples:
– To open a file to write to: 'Fullfile' allows me
to write the
Directory = ‘z:\'
directory and
Filename = 'text_file_example.txt'
filename as
separate strings
file_id = fopen(fullfile(Directory,Filename),'w');
and add them
together so that
MATLAB knows
– To open a file to read from where to open a file
for reading or
Directory = 'c:\'
writing.
Filename = 'text_file_example.txt'
When reading from
file_id = fopen(fullfile(Directory,Filename),'r');
a file, you must
ensure that the file
exists first. 19
Opening and Closing Text Files

File ID's and using fopen


• If the directory or filename does not exist, MATLAB
will not return an error.

• Assume that the directory c:\matlab_example does


not exist

Directory = 'c:\matlab_example';
Filename = 'text_file_example.txt';

file_id = fopen(fullfile(Directory,Filename),'r');
• In this case, MATLAB sets file_id = -1. The value -1
disp(file_id);
indicates that the file does not exist.

20
The fprintf Command
Writing to a text file
• Now that we have opened a text file, we can
write strings to the text file.

• To do this there is a new command called


fprintf.

fprintf(file_ID,FORMAT,A,...)

• fprintf is identical to sprintf, except that we


use the file_id variable to tell MATLAB where
to write the new string.

21
The fprintf Command
An example
• The following code writes data to a text-file:
%%% Open a text file to write information to.
directory = ‘z:\';
filename = 'example_file.txt';
fid = fopen(fullfile(directory,filename),'w');

%%% write some lines of text to the textfile


fprintf(fid,'This file contains pi to the power of n \n \n');
fprintf(fid,' n pi^n\n');
fprintf(fid,'--------------------\n');

%%% Write some numbers to the textfile


for n = 1:10
fprintf(fid,'%5i%15.4f\n',n,pi^n);
end NOTE: The command \
n instructs MATLAB to
%%% Close the textfile. provide a carriage
fclose(fid); return.
22
The fprintf Command
An example Contd..
• The following is the text file which we created:
This file contains pi to the power of n

n pi^n
--------------------
1 3.1416
2 9.8696
3 31.0063
4 97.4091
5 306.0197
6 961.3892
7 3020.2932
8 9488.5310
9 29809.0993
23
The fprintf Command
Writing to a the command window
• We can also use fprintf instead of the disp
command.

• If I don't specify a file id, then anything


which I create using fprintf will be output to
the command window:

Example Coding: Command


window output:
for n = 1:4 1 3.1416
fprintf('%5i%15.4f\n',n,pi^n); 2 9.8696
End 3 31.0063
4 97.4091

24
Reading data from a text file
Reading a line of code from a file
• There are two ways to read information
from a textfile. You can then store this
information into variables in MATLAB.

• The first command is fgetl.

• The second command is fscanf.

• We will look at each command individually.

25
Reading data from a text file
• Using the fgetl command, we can read the next line from a
text file. Recall the textfile we created in the previous
example.

directory = ‘z:\';
filename = 'example_file.txt';
fid = fopen(fullfile(directory,filename),'r');

text_string = fgetl(fid);
text_string = fgetl(fid);
text_string = fgetl(fid);
text_string

• Using this, the following is printed to the command


fclose(fid);
window:

text_string =
n pi^n
>> 26
Reading data from a text file
Reading a line of code from a file
• This means that we can get MATLAB to read a file into a
series of strings. We could use this to read in data for a
program to work.

• We can then convert the string to numbers using the


str2num command. For example:

directory = ‘z:\';
filename = 'example_file.txt'; We have now
fid = fopen(fullfile(directory,filename),'r'); read in all the
text from the
for jj = 1:4
buffer = fgetl(fid); example text file
end and converted all
of the numbers
for jj = 1:10
string = fgetl(fid); to a matrix called
Numb(:,jj) = str2num(string); Numb.
end 27
Reading data from a text file
The fscanf command
• There is a second way to read information from a
text file. Read formatted data from text file.

VARIABLE = fscanf(FID,FORMAT,A,…)

• VARIABLE is a variable containing all of the


information that you have read in.

• For example imagine we have written a text file


called exp.txt that looks like

0.00 1.00000000
0.10 1.10517092
...
1.00 2.71828183
28
Reading data from a text file
The fscanf command

• To read information from this file I could write:

fid = fopen('exp.txt', 'r');


A = fscanf(fid, '%g %g', [2 inf]) % It has two rows
now.
A = A';
fclose(fid)
• This code has now read in all of the data from the
text file and has stored the information as a matrix A.

29
Fscanf
Read formatted data from file
Syntax
A = fscanf(fid, format)
[A,count] = fscanf(fid, format, size)
Description
A = fscanf(fid, format)
reads data from the file specified by fid, converts it according to
the specified format string, and returns it in matrix A.
Argument fid is an integer file identifier obtained from fopen.
format is a string specifying the format of the data to be read.
[A,count] = fscanf(fid, format, size)
Reads the amount of data specified by size, converts it according
to the specified format string, and returns it along with
a count of values successfully read.
size
isan argument that determines how much data is read. Valid options are
n
Read at most n numbers, characters, or strings.
Inf
Read to the end of the file.
[m,n]
Read at most (m*n) numbers, characters, or strings. Fill a matrix of at most m
30
Opening and Closing Text Files

Closing files - the fclose command


• It is essential that you close a text file after
you have finished accessing it (for example
at the end of the code).

• To do this use the command:

fclose(file_id);
• To close all the open text files, you can type:

fclose('all');
31
Commands you have learnt
To open and close a text file
FID = fopen(FILENAME,PERMISSION)
opens the file FILENAME for read/write access.

fclose(fid)
closes the file FILENAME

To convert from numbers to strings


number = str2num(string)
converts the values in the variable string, to a number
stored in the variable number.

string = num2str(number)
converts the values in the variable number, to a string
stored in the variable string. 32
Commands you have learnt
To write information to a file
fprintf(FID,FORMAT,A,...)
writes information to a text file using the format
provided by the program. The variables A,… are
used by the format to determine the output to the
text file.

To write information to a string variabl


string = sprintf(FORMAT,A,...)
writes information to a string varaible called
'string' using the format provided by the
program. The variables A,… are used by the
format to determine the output to the string
variable. 33
Commands you have learnt
To read information from a file
TLINE = fgetl(FID) returns the next line of a
file associated with file identifier FID as a
MATLAB string called TLINE.

VAR = fscanf(FID,FORMAT,A,...)
reads information from a text file using the
format provided by the program. The
variables A,… are used by the format to
determine the input to the text file.

34
Conclusion
• In today's lecture we have
considered how to:
– Create text strings
– Read information from a file
– Write information to a file

• Using these commands, you can


ask MATLAB to read in data from
any text file.

35

You might also like