Thursday, 6 June 2013

MATLAB FILE IO - Syntax - Example Read Write

            This is a simple example for accessing text files in MATLAB. It is always a trouble to process a signal or image in HDL directly. Using this we can convert a signal or an image into a text file and can be used to process in HDL (verilog, VHDL), etc.
             First the required commands for file io are described, followed by the code example for a sine wave write and read.

Open file, or obtain information about open files
fileID = fopen(filename)
fileID = fopen(filename, permission)
fileID = fopen(filename, permission, machineformat)
fileID = fopen(filename, permission, machineformat, encoding)
[fileID, message] = fopen(filename, ...)
fIDs = fopen('all')
[filename, permission, machineformat, encoding] = fopen(fileID)
fileID = fopen(filename) opens the file filename for read access, and returns an integer file identifier.
fileID = fopen(filename, permission) opens the file with the specified permission.
fileID = fopen(filename, permission, machineformat) specifies the order for reading or writing bytes or bits in the file.
[filename, permission, machineformat, encoding] = fopen(fileID) returns the file name, permission, machine format, and encoding that a previous call to fopen used when it opened the specified file. fopen does not read information from the file to determine these output values. An invalid fileID returns empty strings for all output arguments.
Input Arguments
String in single quotation marks that specifies the name of the file to open. Can include a full or partial path.
If you open a file with read access and fopen cannot find filename in the current folder, fopen searches along the MATLAB search path. Otherwise, fopen creates a file in the current directory.
String that describes the type of access for the file: read, write, append, or update. Also specifies whether to open files in binary or text mode.
To open files in binary mode, specify one of the following:
Open file for reading (default).
Open or create new file for writing. Discard existing contents, if any.
Open or create new file for writing. Append data to the end of the file.
Open file for reading and writing.
Open or create new file for reading and writing. Discard existing contents, if any.
Open or create new file for reading and writing. Append data to the end of the file.
Append without automatic flushing. (Used with tape drives.)
Write without automatic flushing. (Used with tape drives.)
To read and write to the same file:
  • Open the file in update mode (with a permission that includes a plus sign, '+').
  • Call fseek or frewind between read and write operations. For example, do not call fread followed by fwrite, or fwrite followed by fread, unless you call fseek or frewind between them.
To open files in text mode, attach the letter 't' to the permission, such as 'rt' or 'wt+'. For better performance, do not use text mode. The following applies on Windows systems, in text mode:
  • Read operations that encounter a carriage return followed by a newline character ('\r\n') remove the carriage return from the input.
  • Write operations insert a carriage return before any newline character in the output.

Write data to text file
fprintf(fileID, format, A, ...)
fprintf(format, A, ...)
count = fprintf(...)
fprintf(fileID, format, A, ...) applies the format to all elements of array A and any additional array arguments in column order, and writes the data to a text file. fprintf uses the encoding scheme specified in the call to fopen.
fprintf(format, A, ...) formats data and displays the results on the screen.
count = fprintf(...) returns the number of bytes that fprintf writes.
Input Arguments
One of the following:
  • An integer file identifier obtained from fopen.
  • 1 for standard output (the screen).
  • 2 for standard error.
Default: 1 (the screen)
String in single quotation marks that describes the format of the output fields. Can include combinations of the following:
  • Percent sign followed by a conversion character, such as '%s' for strings.
  • Operators that describe field width, precision, and other options.
  • Literal text to print.
  • Escape characters, including:
Single quotation mark
Percent character
Form feed
New line
Carriage return
Horizontal tab
Vertical tab
Hexadecimal number, N
Octal number, N
Conversion characters and optional operators appear in the following order (includes spaces for clarity):


Close one or all open files

Syntax  :         fclose(fileID)

Read data from text file
A = fscanf(fileID, format)
A = fscanf(fileID, format, sizeA)
[A, count] = fscanf(...)
A = fscanf(fileID, format) reads and converts data from a text file into array A in column order. To convert, fscanf uses the format and the encoding scheme associated with the file. To set the encoding scheme, use fopen. The fscanf function reapplies the format throughout the entire file, and positions the file pointer at the end-of-file marker. If fscanf cannot match the format to the data, it reads only the portion that matches into A and stops processing.
A = fscanf(fileID, format, sizeA) reads sizeA elements into A, and positions the file pointer after the last element read. sizeA can be an integer, or can have the form [m,n].
[A, count] = fscanf(...) returns the number of elements that fscanf successfully reads.
Input Arguments
Integer file identifier obtained from fopen.
String enclosed in single quotation marks that describes each type of element (field). Includes one or more of the following specifiers.
Field Type
Integer, signed
Base 10
Base determined from the values. Defaults to base 10. If initial digits are 0x or 0X, it is base 16. If initial digit is 0, it is base 8.
%ld or %li
64-bit values, base 10, 8, or 16
Integer, unsigned
Base 10
Base 8 (octal)
Base 16 (hexadecimal)
%lu, %lo, %lx
64-bit values, base 10, 8, or 16
Floating-point number
Floating-point fields can contain any of the following (not case sensitive): Inf, -Inf, NaN, or -NaN.
Character string
Read series of characters, until find white space.
Read any single character, including white space.
(To read multiple characters, specify field length.)
Read only characters in the brackets, until the first nonmatching character or white space.

%input('Enter no of samples: ');

fid = fopen('sinewav.txt', 'w');
fprintf(fid, '%0.3hx\n', x);
disp('File write successful.....')

fid1 = fopen('sinewav.txt', 'r');
c = fscanf(fid1, '%g %g', [1 inf]);
disp('File is successful read...');
figure, stem(n,c,'-*m');
title('Sinusoidal Signal from text file');

If you've any problem, plz let us know. We'll assist you to overcome it. Write to us to

Viewers  comments are encouraged. 
This helps us to much more.
Thank you!!!



Post a Comment

Search Here...