EE3252 Electronic Engineering Labs II
MATLAB : Session 2
Reading/Writing text files
The syntax is almost the same than in the C Language. The basic
functions in Matlab are:
Open a file:
file_id = fopen(file_name,'mode')
Read a line from a file:
data_line = fgetl(file_id);
Get the variables from the line of data:
variable = sscanf(dat_line,'%f')
Read formatted data from a file:
array=fscanf(file_id,'%e%c',[4,inf])
Write text on a file:
fprintf(file_id,' %s \n', text_variable)
fprintf(file_id,'%8.2f\t', data_variable)
Close a file:
fclose(file_id);
Example
Program:
i:\public\teaching\eleceng\EE3252\lab2.m
Data:
i:\public\teaching\eleceng\EE3252\temp1.txt
Mona. Ghassemian Sep-Nov 2002
EE3252 Electronic Engineering Labs II
Example of reading and plotting data (lab2.m):
filename=input('Input the filename:','s');
fid=fopen(filename,'r');
array=fscanf(fid,'%e%c',[4,inf]);
plot(array([1],:),array([3],:));
fclose(fid);
xlabel('Time(us)')
ylabel('Voltage(v)')
title('Waveform demonstration')
grid
Demonstrating how to calculate the area under a
curve.
You can create a curve,either by putting values of X1 and Y1 or
generating them with a function such as cos, sin,…
function ar = area(x1,y1)
% AREA Area between a curve and the X axis
index=1; acc_area=0;
while( index < length(x1) )
base = x1(index+1) - x1(index);
height = y1(index);
acc_area = acc_area + base*height;
index = index + 1 ;
end
ar = acc_area;
Mona. Ghassemian Sep-Nov 2002
EE3252 Electronic Engineering Labs II
Demonstrating how to read data from file and
plotting data as figures
FOPEN Open file
FPRINTF Write formatted data to file
FCLOSE Close file.
FSCANF Read formatted data from file.
filename=input('Input the filename:','s');
fid=fopen(filename,'r');
% 'r' read
% 'w' write (create if necessary)
array=fscanf(fid,'%e%c',[4,inf]);
% Use %c to read space characters
plot(array([1],:),array([3],:));
fclose(fid);
xlabel('Time(us)')
ylabel('Voltage(v)')
title('Waveform demonstration')
grid
Mona. Ghassemian Sep-Nov 2002
EE3252 Electronic Engineering Labs II
To show how you can save your data in a text file
FPRINTF Write formatted data to file
x = 0:.1:1; y = [x; exp(x)];
fid = fopen('exp.txt','w');
fprintf(fid,'%6.2f %12.8f\n',y);
% The special formats \n,\r,\t,\b,\f can be used to produce linefeed,
% carriage return, tab, backspace, and form feed characters respectively.
% Use \\ to produce a backslash character and %% to produce the percent
% character.
fclose(fid);
Exercise:
1) Investigate more about the area.m .See if you can find a more accurate method for
calculating the area under a curve.
2) Try creating a file(result.txt) with the cosgen function’s result in it. Then open the
file (result.txt) and plot and print it . (use your own numbers for Amplitude, Frequency
& Phase.)
Mona. Ghassemian Sep-Nov 2002