cs111_matlab_io
cs111_matlab_io
1
The textread Function The textread Function
n The textread function skips the columns n Example: Searching for telephone
that have an asterisk (*) in the format numbers
descriptor name = ‘Selim’;
n [fname, phone] = for ii = 1:length(fname),
textread( 'phones.txt', '%s %*s %*s %d' ) if ( strcmp( fname(ii), name ) ),
disp( phone(ii) );
n The load command (with ASCII option)
end
assumes all of the data is of a single end be careful about the
type but textread is more flexible usage of cell arrays
2
Closing Files Writing Binary Data
n status = fclose( fid ) n count = fwrite( fid, array, precision )
closes the file with file id fid writes data in array in binary format
n If the closing operation is successful, n fid: file id of the file opened using fopen
status will be 0 n array: array of values to write
n If the closing operation is unsuccessful, n count: number of values written to the file
status will be -1 n MATLAB writes data in column order (if
n status = fclose( ‘all’ ) array is [1 2;3 4;5 6], data is written as
1, 3, 5, 2, 4, 6)
closes all open files (except for standard
output and standard error) n You can use array’ to write in row order
3
Binary I/O Examples Writing Formatted Text Data
%Read the passwords from the binary file passwd.dat
%Open the file n count = fprintf(fid,format,val1,val2,…)
[ fid, msg ] = fopen( 'passwd.dat', 'rb' );
if ( fid < 1 ), writes formatted text data in a user-
error( msg );
end specified format
%Read the passwords
[ passwords2, count ] = fread( fid, [100 8], 'char' ); n fid: file id (if fid is missing, data is written
fprintf( '%d characters were read\n', count );
%Close the file to the standard output device (command
status = fclose( fid );
if ( status ~= 0 ), window)
end
error( 'Could not close the file' );
n format: same as what we have been using
(combination of format specifiers that start
with %)
n count: number of characters written
Spring 2004 CS 111 19 Spring 2004 CS 111 20
4
Formatted Text I/O Examples Formatted Text I/O Examples
% Script file: table.m
% Purpose: To create a table of square roots, squares, and cubes. %Updates the phone number of a person
% Open the file. %Get the name and new phone number
fid = fopen('table.dat' , 'wt' ); name = input( 'Enter the last name of the person: ' , 's' );
new_phone = input( 'Enter the new phone number: ' );
% Print the title of the table.
fprintf(fid, ' Table of Square Roots, Squares, and Cubes\n\n' ); %Read the phone numbers
% Print column headings [fname,lname,rank,phone] = textread ( 'phones.txt', '%s %s %s %d' );
fprintf(fid, ' Number Square Root Square Cube\n ');
fprintf(fid, ' ====== =========== ====== ====\n '); %Find the person and update the phone number
for i = 1:length(lname),
% Generate the required data if ( strcmp( lname(i), name ) ),
ii = 1: 10; phone(i) = new_phone;
square_root = sqrt (ii);
square = ii.^ 2; end
cube = ii.^3; end