• No results found

MATLAB: Strings and File IO

N/A
N/A
Protected

Academic year: 2021

Share "MATLAB: Strings and File IO"

Copied!
26
0
0

Loading.... (view fulltext now)

Full text

(1)

Kipp Martin University of Chicago Booth School of Business

(2)

The following files are used in this lecture.

I filein.txt

I fileIO.m

(3)

Strings

(4)

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.

(5)

In MATLAB you can also work with strings. Astring is a sequence of characters. The sequence can be digits, letters, symbols, and spaces enclosed by single quotation marks. Examples of string variables are

x = ’abcd123’ y = ’ae _ bx%$#(’

In MATLAB everything is anarrayso what have we created? >> whos

Name Size Bytes Class

x 1x7 14 char

y 1x12 24 char

(6)

Since a string is an array, you can access parts of the string just like you would any other array. For example

>> y(5:7) ans = _ b >> x(1, 3) ans = c >> x(1,:) ans = abcd123 6

(7)

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

(8)

We can addressstudent recordlike any other matrix of numbers.

>> student_record(2, [1:2, 10]) ans =

Joe

What! How did we getJoe? What will

student_record(2, [1, 2, 5]) give?

(9)

Now what about something like:

x = [’Hello’ ; ’Goodbye’] What will happen?

As an alternative to thecharfunction you can use the strvact

function (it will automaticallypad). >> x = strvcat(’Hello’, ’Goodbye’) x =

Hello Goodbye >> whos

Name Size Bytes Class

(10)

Here are some useful string functions in MATLAB.

Thestrcmpfunction. This function will compare two strings and return a true if they are equal. False if not.

Very useful inif statements.

>> x =strcmp(’hello’, ’goodbye’) x = 0

>> y = strcmp(’abc’, ’abc’) y = 1

(11)

Thestrcatfunction. 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 =

(12)

We may wish to convert string data to numbers. Usestr2num. >> x = ’17.45’; >> y = str2num(x) y = 17.4500 >> whos

Name Size Bytes Class

x 1x5 10 char

y 1x1 8 double

(13)

We may wish doubles to strings. Usenum2str. >> x = 77.11; >> y = num2str( x) y = 77.11 >> whos

Name Size Bytes Class

x 1x1 8 double

(14)

It is pretty easy to read from and write to text files using MATLAB. See Chapter 4 of Gilat.

Let’s start with reading a file. Consider the filefilein.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 withfileIO.m

(15)

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

(16)

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

(17)

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 aandb I Use

%[^,]

to read all characters until acomma is found. I Burn off the commas with

(18)

Read the third line: HiAgain

Use the code fgetl(fid);

v8 = fscanf(fid, ’%s’, 1)

I use thefgetl(fid); to make sure I have read any control characters before going to the next line

(19)

Now read the fourth line 1 54 3 4

with the code

x = fscanf(fid, ’%f %f %f %f’, 4) What isx?

(20)

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

(21)

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

(22)

In-class Exercise: Read the file (studentData.txt) and create a structure,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?

(23)

Now let’s write the input file we worked with. First open a file with

write permission.

fid = fopen(’fileout.txt’, ’w’);

If you replace thewwith adata will be appended to the end of the file.

Write the first line.

fprintf(fid, ’Hi %-5.2f Goodbye %i\n’, 1.77, 34)

I We use\nto move the file pointer to a new line

I The%-5.2f and%iget replaced by 1.77 and 34, respectively. (the “minus” inf -5.2f causes left justification

(24)

Write the next two lines of text.

fprintf(fid, ’a b, c, d\n’) fprintf(fid, ’HiAgain\n’)

Next print the line ofintegers.

fprintf(fid, ’%i %i %i %i\n’, 1, 54, 3, 4)

(25)

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

(26)

Note that when we printed, we specified the file id (in this casefid)

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 the screen with thedisp() function.

References

Related documents