How to read complex format data from txt file
2 views (last 30 days)
Show older comments
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
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?
Answers (1)
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
See Also
Categories
Find more on Large Files and Big Data 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!