I am having trouble reading a txt file
Show older comments
I have txt file with data formated below but Im only get the first line .
index: 0 int_time: 1718984569904518 us int_diff: 0 us min: 167 us max: 167 us
index: 1 int_time: 1718984569904682 us int_diff: 164 us min: 164 us max: 167 us
index: 1 int_time: 1718984569904682 us int_diff: 164 us min: 164 us max: 167 us
here is the code im using utilising textscan
fid=fopen('Desktop\data.txt','rt');
data=textscan(fid,'%[index: 0 int_time:] %u64 %[us_int_diff: ] %s %s %s %s %s %s %s %s')
fclose(fid);
1 Comment
Image Analyst
on 23 Jun 2024
Don't force us create data.txt just to help you. Make it easy for us to help you. If you have any more questions, then please attach your data with the paperclip icon after you read this:
Accepted Answer
More Answers (1)
In
%data=textscan(fid,'%[index: 0 int_time:] %u64 %[us_int_diff: ] %s %s %s %s %s %s %s %s')
you're forcing a match on a 0 in "index: 0 int_time:" but only the first record matches that pattern; the remaining two records have a "1", not "0".
Try
fmt='%[index: ] %d %[int_time:] %u64 %[us_int_diff: ] %s %s %s %s %s %s %s %s';
Let's test...
txt=[
'index: 0 int_time: 1718984569904518 us int_diff: 0 us min: 167 us max: 167 us';
'index: 1 int_time: 1718984569904682 us int_diff: 164 us min: 164 us max: 167 us';
'index: 1 int_time: 1718984569904682 us int_diff: 164 us min: 164 us max: 167 us'];
for i=1:size(txt,1)
data{i,1}=textscan(txt(i,:),fmt);
end
data{:}
This is pretty messy mishmash of cells and nested cells; I'd probably at least convert the numeric fields all with %d for the time stamp data. It wouldn't be too hard then to turn the other nested cells into a cellstr containing the string for only one level of dereferencing.
The alternative you might explore would be readtable; your release won't have all the bells and whistles the current does, but it was several years past initial release by then so should be pretty robust. It is a handy container for mixed data types.
fmt='%*[index: ] %d %*[int_time:] %u64 %*[us_int_diff: ]%d %*[us min: ]%d %*[us max: ]%d %*[us]';
for i=1:size(txt,1)
data{i,1}=textscan(txt(i,:),fmt,'collectoutput',0);
end
data=vertcat(data{:})
data{:,2}
whos ans
tD=cell2table(data,'VariableNames',{'Index','Time','Diff','Min','Max'})
2 Comments
Garykalan
on 23 Jun 2024
dpb
on 24 Jun 2024
"...i was able to use the cell2mat function and everything is perfect..."
Are you sure? Be careful; I think you'll find that turned everything to double and you'll not have the correct value for the Time U64 field data. I got bit by that in one of my examples earlier...
However, if this did solve your problem, please go ahead and Accept the answer so it is apparent if nothing else.
Categories
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!