How to read complex format data from txt file

2 views (last 30 days)
I have a txt file that I want to read into Matlab. Data format is like below:
term2 2015-07-31-15_58_25_612 [0.9934343, 0.3423043, 0.2343433, 0.2342323]
term0 2015-07-31-15_58_25_620 [12]
term3 2015-07-31-15_58_25_625 [2.3333, 3.4444, 4.5555]
...
How can I read these data in the following way?
name = [term2 term0 term3] or namenum = [2 0 3]
time = ["2015-07-31-15_58_25_612" "2015-07-31-15_58_25_620" "2015-07-31-15_58_25_625"]
data = {[0.9934343, 0.3423043, 0.2343433, 0.2342323], [12], [2.3333, 3.4444, 4.5555]}
I tried to use textscan(), but for the data part I cannot specify the length because they are different. Then how can I read it? My Matlab version is R2012b.
Thanks a lot in advance if anyone could help!
  2 Comments
Jan
Jan on 3 Aug 2015
Please note, that "time = [2015-07-31-15_58_25_612 ..." cannot be a valid Matlab syntax. What type is wanted? A cell string?
Hongwei Xu
Hongwei Xu on 3 Aug 2015
Edited: Hongwei Xu on 3 Aug 2015
@Jan Simon Thank you very much for your reminding! Yes, each time as a string is OK. Time format is not that critical for me. The more important part is the name and data.

Sign in to comment.

Answers (1)

Jan
Jan on 3 Aug 2015
Edited: Jan on 3 Aug 2015
fid = fopen(FileName, 'r');
if fid == -1, error('Cannot open %s for reading.', FileName); end
maxLines = 1000; % Determine this smartly, better to big, use the file size?
name = cell(1, maxLines);
time = cell(1, maxLines);
data = cell(1, maxLines);
k = 0;
ready = false;
while ~ready
s = fgetl(fid);
if ischar(s)
Space = strfind(s, ' ');
name{k} = s(1:Space(1)-1);
time{k} = s(Space(1)+1:Space(2)-1);
iniBrak = strfind(s, '[') + 1;
finBrak = strfind(s, ']') - 1;
data{k} = sscanf(s(iniBrak:finBrak), '%f,').';
else
ready = false;
end
end
fclose(fid);
  1 Comment
Hongwei Xu
Hongwei Xu on 4 Aug 2015
Edited: Hongwei Xu on 4 Aug 2015
Thanks a lot for your answer! But when I run it, it tends to stuck in while loop...I don't know why... But now I got another answer which works well. For someone who will meet this problem later on:
%%// read file
fid = fopen('text.txt','r') ;
M = textscan( fid , 'term%d %f-%f-%f-%f_%f_%f_%f %*c %[^]] %*[^\n]' ) ;
fclose(fid) ;
%%// dispatch data
name = M{1,1} ;
time_vec = cell2mat( M(1,2:7) ) ;
time_ms = M{1,8} ./ (24*3600*1000) ; %// take care of the millisecond separatly as they are not handled by "datenum"
time = datenum( time_vec ) + time_ms ;
data = cellfun( @(s) textscan(s,'%f',Inf,'Delimiter',',') , M{1,end} ) ;
timeformat = datestr(time,'yyyy-mm-dd-HH:MM:SS.FFF');

Sign in to comment.

Categories

Find more on Large Files and Big Data in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!