Upload
truongquynh
View
221
Download
1
Embed Size (px)
Citation preview
MATLAB: Strings and File IO
Kipp MartinUniversity of Chicago
Booth School of Business
February 9, 2012
1
Strings
I In MATLAB everything is an array
I We can have an array of numbers (doubles)
I We can have an array of strings
In this module we first look at strings.
4
Strings
In MATLAB you can also work with strings. A string is a sequenceof characters. The sequence can be digits, letters, symbols, andspaces enclosed by single quotation marks. Examples of stringvariables are
x = ’abcd123’
y = ’ae _ bx%$#(’
In MATLAB everything is an array so what have we created?
>> whos
Name Size Bytes Class
x 1x7 14 char
y 1x12 24 char
Each character takes two bytes.
5
Strings
Since a string is an array, you can access parts of the string justlike you would any other array. For example
>> y(5:7)
ans =
_ b
>> x(1, 3)
ans =
c
>> x(1,:)
ans =
abcd1236
Strings
It is also possible to define matrices where each row is a string.
>> student_record =char(’Name:’, ’Joe Schmoe’, ’Quiz 1 Score’, ...
’96’)
student_record =
Name:
Joe Schmoe
Quiz 1 Score
96
>> whos student_record
Name Size Bytes Class
student_record 4x12 96 char
Why 4 by 12? Where does the 12 come from?
7
Strings
We can address student record like any other matrix of numbers.
>> student_record(2, [1:2, 10])
ans =
Joe
What! How did we get Joe?
What will
student_record(2, [1, 2, 5])
give?
8
Strings
Now what about something like:
x = [’Hello’ ; ’Goodbye’]
What will happen?
As an alternative to the char function you can use the strvactfunction (it will automatically pad).
>> x = strvcat(’Hello’, ’Goodbye’)
x =
Hello
Goodbye
>> whos
Name Size Bytes Class
x 2x7 28 char
9
Strings
Here are some useful string functions in MATLAB.
The strcmp function. This function will compare two strings andreturn a true if they are equal. False if not.
Very useful in if statements.
>> x =strcmp(’hello’, ’goodbye’)
x = 0
>> y = strcmp(’abc’, ’abc’)
y = 1
10
Strings
The strcat function. This function is the equivalent of the &operator in VBA for strings.
This function allows us to concatenate strings.
>> x = ’William’;
>> y = strcat(x, ’ Barret’, ’ Travis’)
y =
William Barret Travis
11
Strings
We may wish to convert string data to numbers. Use str2num.
>> x = ’17.45’;
>> y = str2num(x)
y =
17.4500
>> whos
Name Size Bytes Class
x 1x5 10 char
y 1x1 8 double
12
Strings
We may wish doubles to strings. Use num2str.
>> x = 77.11;
>> y = num2str( x)
y =
77.11
>> whos
Name Size Bytes Class
x 1x1 8 double
y 1x5 10 char
13
File Input-Output
It is pretty easy to read from and write to text files usingMATLAB. See Chapter 4 of Gilat.
Let’s start with reading a file. Consider the file filein.txt
Hi 1.77 Goodbye 34
a b, c, d
HiAgain
1 54 3 4
17 16.6 77.7 7 9 10 11.4
27.2 11.9
Read the above file with fileIO.m
14
File Input-Output
First – open the file.
In VBA we had
testFile = "C:\temp\data.txt"
Open testFile For Input As #1
In MATLAB we have:
fid = fopen(’filein.txt’);
I am assuming filein.txt is in the MATLAB path.
15
File Input-Output
Read the first line:
Hi 1.77 Goodbye 34
Use the code:
v1 = fscanf(fid, ’%s’, 1)
v2 = fscanf(fid, ’%f’, 1)
v3 = fscanf(fid, ’%s’, 1)
v4 = fscanf(fid, ’%f’, 1)
I Use the ’%s’ to read a string
I We read the first string until we hit the white space delimiter.
I The 1 is telling to read one string
I Use the ’%f’ to read a floating point number
16
File Input-Output
Read the second line using the comma as a delimiter:
a b, c, d
Use the code
v5 = fscanf(fid, ’%[^,]’, 1)
fscanf(fid, ’%[,]’, 1) ; %trash the comma
v6 = fscanf(fid, ’%[^,]’, 1)
fscanf(fid, ’%[,]’, 1) ; %trash the comma
v7 = fscanf(fid, ’%s’, 1)
I I want to preserve the white space between a and bI Use
%[^,]
to read all characters until a comma is found.I Burn off the commas with
%[,]17
File Input-Output
Read the third line:
HiAgain
Use the code
fgetl(fid);
v8 = fscanf(fid, ’%s’, 1)
I use the fgetl(fid); to make sure I have read any controlcharacters before going to the next line
18
File Input-Output
Now read the fourth line
1 54 3 4
with the code
x = fscanf(fid, ’%f %f %f %f’, 4)
What is x?
19
File Input-Output
Now read the all of the remaining numbers
17 16.6 77.7 7 9 10 11.4
27.2 11.9
using the code:
k = 1;
while ~feof(fid);
A(k ) = fscanf(fid, ’%f’, 1);
k = k + 1;
end;
20
File Input-Output
Create a Structure From a File: Consider the following data set(studentData.txt)
Tom,Jones,57
Bill,Uehling,100
Mary,Honda,95
Kathy,Murigami,67
Bill,Jones,99
Jill,Doe,83
Mark,Anderson,56
Jody,Ruebush,99
Alice,Tyx,89
Mary,Chin,100
Richard,Valens,77
Tom,Choi,80
Dave,Sweeney,45
Download this file at the data link.21
File Input-Output
In-class Exercise: Read the file (studentData.txt) and create astructure, studentStruct, that has the following properties:
I FirstName
I LastName
I Quiz1
Question: Instead of writing code to read a file, why not
A = load(’studentData.txt’)
and let MATLAB do the work?
22
File Input-Output
Now let’s write the input file we worked with. First open a file withwrite permission.
fid = fopen(’fileout.txt’, ’w’);
If you replace the w with a data will be appended to the end of thefile.
Write the first line.
fprintf(fid, ’Hi %-5.2f Goodbye %i\n’, 1.77, 34)
I We use \n to move the file pointer to a new line
I The %-5.2f and %i get replaced by 1.77 and 34, respectively.(the “minus” inf -5.2f causes left justification
23
File Input-Output
Write the next two lines of text.
fprintf(fid, ’a b, c, d\n’)
fprintf(fid, ’HiAgain\n’)
Next print the line of integers.
fprintf(fid, ’%i %i %i %i\n’, 1, 54, 3, 4)
24
File Input-Output
Write the line of seven real numbers and then a new line.
for i=1:7
fprintf(fid, ’%-5.1f’, A( i))
end
fprintf(fid, ’\n’)
and then the last line
fprintf(fid, ’%-5.1f %-5.1f \n’, 27.2, 11.9)
25
File Input-Output
Note that when we printed, we specified the file id (in this case fid)
fprintf(fid, ’%-5.1f %-5.1f \n’, 27.2, 11.9)
You can also print directly to the screen
fprintf(’Print Directly to the screen\n’)
Note that the file id is missing.
If you do not care about formatting you can also print to thescreen with the disp() function.
26