0% found this document useful (0 votes)
9 views5 pages

cs111_matlab_io

The document provides an overview of basic MATLAB functions for handling data files, including saving and loading data in binary and ASCII formats. It explains the use of the textread function for reading formatted ASCII files, file opening and closing procedures, and examples of reading and writing binary and formatted text data. Additionally, it covers the exist function to check for the existence of variables and files in the workspace.

Uploaded by

bny3553
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views5 pages

cs111_matlab_io

The document provides an overview of basic MATLAB functions for handling data files, including saving and loading data in binary and ASCII formats. It explains the use of the textread function for reading formatted ASCII files, file opening and closing procedures, and examples of reading and writing binary and formatted text data. Additionally, it covers the exist function to check for the existence of variables and files in the workspace.

Uploaded by

bny3553
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

MATLAB Basics: Data Files

n save filename var1 var2 …


→ binary
Input/Output Functions n save homework.mat x y
n save x.dat x –ascii → ascii
n load filename
Selim Aksoy n load filename.mat → binary
Bilkent University n load x.dat –ascii → ascii
Department of Computer Engineering
[email protected]

Spring 2004 CS 111 2

The textread Function The textread Function


n It is designed to read ASCII files that n [a,b,c,…] = textread(filename,format,n)
are formatted into columns of data n filename: a string that is the name of the
n Each column can be of a different type file to be read
n It is useful for importing tables of data n format: a string containing the format
primitives (just like in fprintf)
printed out by other applications
n n: number of lines to read (if not specified,
the file is read until the end)

Spring 2004 CS 111 3 Spring 2004 CS 111 4

The textread Function The textread Function


n Example: Assume that you have a file n [fname,lname,rank,phone] =
called phones.txt textread( 'phones.txt', '%s %s %s %d' )
Varol Akman Prof 1538 n fname = n phone =
Selim Aksoy AsstProf 3405 1537
Erol Arkun Prof 2249 'Varol‘
'Selim‘ 3405
Cevdet Aykanat Prof 1625
Mehmet Baray Prof 1208 'Erol‘ 2249
Cengiz Çelik Instructor 2613 'Cevdet‘ 1625
Ilyas Çiçekli AsstProf 1589 'Mehmet‘ 1208
David Davenport AsstProf 1248 'Cengiz‘ 2613
... ... ...
cell array double array
Spring 2004 CS 111 5 Spring 2004 CS 111 6

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

Spring 2004 CS 111 7 Spring 2004 CS 111 8

File Processing Opening Files


n File types: n fid = fopen( filename, permission )
n Binary files opens the file filename in the mode specified
by permission
n Data is stored in program readable format
fid is the file id (a positive integer) that is assigned
Processing is fast
n
n
to the file by MATLAB
n Text (ASCII) files n fid is used for all reading, writing and control
n Data is stored in human readable format operations on that file
n Processing is slower n file id 1 is the standard output device and file id 2
is the standard error device
n fid will contain -1 if the file could not be opened

Spring 2004 CS 111 9 Spring 2004 CS 111 10

Opening Files Opening Files


n Permission can be: n Examples:
‘r’: open file for reading (default)
fid = fopen( ‘example.dat’, ‘r’ )
n
n
‘w’: open file, or create a new file, for writing;
opens a binary file for input
n

discard existing contents, if any


n ‘a’: open file, or create a new file, for writing; n fid = fopen( ‘example.dat’, ‘wt’ )
append data to the end of the file opens a text file for output (if example.dat
n ‘r+’: open file for reading and writing already exists, it will be deleted)
n ‘w+’: open file, or create a new file, for reading
and writing; discard existing contents, if any n fid = fopen( ‘example.dat’, ‘at’ )
n ‘a+’: open file, or create a new file, for reading opens a text file for output (if example.dat
and writing; append data to the end of the file already exists, new data will be appended
n Add ‘t’ to the permission string for a text file to the end)
Spring 2004 CS 111 11 Spring 2004 CS 111 12

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

Spring 2004 CS 111 13 Spring 2004 CS 111 14

Writing Binary Data Reading Binary Data


n Precision (platform independent) can be: n [array,count] = fread(fid,size,precision)
n ‘char’: 8-bit characters reads binary data in a user-specified
format
n ‘uchar’: 8-bit unsigned characters
n size: number of values to read
n ‘int16’: 16-bit integer n n: read exactly n values (array will be a column
n ‘int32’: 32-bit integer vector with length n)
n ‘uint16’: 16-bit unsigned integer n Inf: read until the end of the file (column vector)
n [n m]: read exactly n x m values (array will be a
n ‘uint32’: 32-bit unsigned integer n-by-m matrix)
n ‘float32’: 32-bit floating point n array: array that contains the data
n ‘float64’: 64-bit floating point n count: number of values read from the file
Spring 2004 CS 111 15 Spring 2004 CS 111 16

Binary I/O Examples Binary I/O Examples


%
%
Script file: binary_io.m
Purpose: To illustrate the use of binary i/o functions.
%Randomly generate 100 passwords with 8 characters
passwords = [];
% Prompt for file name
filename = input('Enter file name: ','s'); for ii = 1:100, %Generate each password
% Generate the data array
s = [];
out_array = randn(1,10000); for jj = 1:8, %Generate each character of each password
% Open the output file for writing.
t = char( round( ('z'-'a')*rand + 'a' ) );
[fid,msg] = fopen(filename,'w'); s = [ s t ];
% Was the open successful? end
if fid > 0
% Write the output data.
passwords = strvcat( passwords, s );
count = fwrite(fid,out_array,'float64'); end
% Tell user
disp([int2str(count) ' values written...']);
% Close the file %Write passwords to a binary file passwd.dat
status = fclose(fid);
else %Open the file
% Output file open failed. Display message.
disp(msg);
[ fid, msg ] = fopen( 'passwd.dat', 'wb' );
end if ( fid < 1 ),
% Now try to recover the data. Open the file for reading.
error ( msg );
[fid,msg] = fopen(filename,'r'); end
% Was the open successful? %Write the passwords
if fid > 0
% Read the input data.
count = fwrite ( fid, passwords, 'char' );
[in_array, count] = fread(fid,[100 100],'float64'); fprintf( '%d characters were written\n', count );
% Tell user
disp([int2str(count) ' values read...']);
%Close the file
% Close the file status = fclose( fid );
status = fclose(fid); if ( status ~= 0 ),
else
% Input file open failed. Display message.
disp(msg);
error ( 'Could not close the file' );
end end
Spring 2004 CS 111 17 Spring 2004 CS 111 18

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

Writing Formatted Text Data Reading Formatted Text Data


n Make sure there is a one-to-one n [array,count] = fscanf(fid,format,size)
correspondence between format specifiers reads formatted text data in a user-
and types of data in variables specified format
n Format strings are scanned from left to right n fid: file id
n Program goes back to the beginning of the n format: same as format in fprintf
format string if there are still values to write
(format string is recycled) n size: same as size in fread
n If you want to print the actual % character, n array: array that receives the data
you can use %% in the format string n count: number of elements read

Spring 2004 CS 111 21 Spring 2004 CS 111 22

Reading Formatted Text Data Reading Formatted Text Data


n line = fgetl( fid ) n line = fgets( fid )
reads the next line excluding the end- reads the next line including the end-of-
of-line characters from a file as a line characters from a file as a character
character string string
n line: character array that receives the data n line: character array that receives the data
n line is set to -1 if fgetl encounters the end n line is set to -1 if fgets encounters the end
of a file of a file

Spring 2004 CS 111 23 Spring 2004 CS 111 24

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

% Create the output array %Write the updated phone numbers


out = [ ii' square_root' square' cube']; fid = fopen( 'phones2.txt', 'wt' );
for i = 1:length(fname),
% Print the data fprintf( fid, '%s %s %s %d\n', fname{i}, lname{i}, rank{i},
for ii = 1:10
fprintf (fid, ' %2d %11.4f %6d %8d\ n',out(ii,:)); phone(i) );
end end
fclose( fid );
% Close the file.
status = fclose(fid);
Spring 2004 CS 111 25 Spring 2004 CS 111 26

Formatted Text I/O Examples The exist Function


%Updates the name of a person

%Get the old and new names


n ident = exist( ‘item’, ‘kind’ )
old_name = input( 'Enter the old name: ', 's' );
new_name = input( 'Enter the new name: ', 's' ); checks the existing of ‘item’
%Open the input file
fid1 = fopen( 'phones.txt ', 'rt' );
n item: name of the item to search for
%Open the output file
fid2 = fopen( 'phones3.txt', 'wt' ); n kind: optional value for restricting the
%Read lines one by one
line = fgets( fid1 );
search for a specific kind of item (possible
while ( line > 0 ),
%Replace the old name with the new name
values are ‘var’, ‘file’, ‘builtin’, ‘dir’)
ident: a value based on the type of the
line2 = strrep( line, old_name, new_name );
%Write to the new file n
fprintf( fid2, '%s', line2 );
%Read the next line
line = fgets( fid1 );
item
end
%Close the file
status = fclose( 'all' );
Spring 2004 CS 111 27 Spring 2004 CS 111 28

The exist Function Examples


n exist( 'phones.txt' )
n Values returned by exist can be: ans =
2
n 0: item not found n exist( 'phones5.txt' )
ans =
n 1: item is a variable in the current 0
workspace n clear
n x = 5;
n 2: item is an m-file or a file of unknown n exist( 'x' )
type ans =
1
n 5: item is a built -in function n exist( 'y' )
ans =
n 7: item is a directory 0
n exist( ' sum' )
ans =
5
Spring 2004 CS 111 29 Spring 2004 CS 111 30

You might also like