Reading txt file in streaming

10 views (last 30 days)
Paolo on 13 Sep 2014
Commented: Paolo on 13 Sep 2014
I have a txt file containing 1 day of equity price tick-by-tick and I would like to read the file line-by-line. In details, I would like to read a new line every 2 seconds (for example) and store the new line at the end of an array and then plot it in real-time. In few words, replicate a streaming data (and plot it) as it was in real-time, but with static data, saved into a txt file.
Thank you
Best regards, Paolo

Answers (1)

Geoff Hayes
Geoff Hayes on 13 Sep 2014
Paolo - without knowing the details of your text file (are there any header rows? is it a comma-separated file? does each row have the same number of columns? is all the data numeric or a mix of numbers and strings?) there can be several ways to read in the data (see importdata, textscan, dlmread, csvread).
But if you want to just read in the data line-by-line, here is one way
% assume that you are running code in folder your file exists
% open the file
fid = fopen('myFileName.txt');
if fid>0
% loop until end of file is reached
while ~feof(fid)
% read the current line
line = fgetl(fid);
% extract data from the line
% plot the data
% wait two seconds until continuing with next line
% close the file
The above code will read each line of the file, do some processing on that line (to be filled in by you), plot the data (again to be filled in by you), and then pause for two seconds before continuing with next line.
If you could read in all of the data into a matrix (numeric or cell) the above code would simplify but its "structure" would remain the same - you would just loop over each row in the matrix, do the processing on that row, plot the data, and then pause for two seconds.
  1 Comment
Paolo on 13 Sep 2014
Thanks Geoff, that works perfectly

Sign in to comment.


Find more on Data Import and Export in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!