import and sorting text file to matlab
7 views (last 30 days)
Show older comments
hi all.
I have these hundreds text files with some data i should analyze
each file has date column time column, ID column and value column.
i would like to create a structure that contains text file name and ID as fields and then fill it with the respectvie times and values. i wpould like to create a general code that can be used in every future situation, because i'm going to get more and more of this text files to analyze.
7 Comments
Guillaume
on 13 Mar 2019
Edited: Guillaume
on 13 Mar 2019
What does "each ID has different rows" mean?
In your example file, each ID, except ID 0, is only present on one or two rows. ID 0 must have a special meaning since it's repeated so often.
Importing your file is trivial
t = mergevars(readtable('example.txt'), 1:3);
t.Properties.VariableNames = {'Date', 'Time', 'ID', 'something'};
t.Date = datetime(t.Date)
Sorting by ID and time is also trivial:
sortrows(t, {'ID', 'Time'})
I'm really struggling to understand what needs to be done afterwards.
Accepted Answer
Guillaume
on 13 Mar 2019
- Import all the text files
folder = 'c:\somewhere\somefolder';
filelist = {'fileA', 'fileB', ...}; %obtained however you want. e.g with dir
alldata = cell(size(filelist));
for fileidx = 1:numel(filelist)
%load file
filedata = readtable(fullfile(folder, filelist{fileidx});
%optionally, tidy up the table:
filedata = mergevars(filedata, 1:3);
filedata.Properties.VariableNames = {'Date', 'Time', 'ID', 'something'};
filedata.Date = datetime(filedata.Date);
%store in cell array
alldata{fileidx} = filedata;
end
%once everything is loaded, merge it all in one table
alldata = vertcat(alldata{:});
%sort by time
alldata = sortrows(alldata, 'Time');
- put in a structure. Not needed if all you want to plot per ID
- plot each ID in one graph (I assume it's column 4 (which I called something) against time).
%create figure, axes, and tell matlab to plot all on the same graph
figure;
axes;
hold on;
%plot something vs time for each unique ID.
rowfun(@plot, alldata, 'GroupingVariables', 'ID', 'InputVariables', {'Time', 'something'});
14 Comments
Guillaume
on 18 Mar 2019
I'm unclear how a cycle is defined. In any case, you probably need to add another variable to the table which would define which cycle the row belongs to. Then, in the plot function, you can split the data per cycle (using e.g. splitapply).
More Answers (0)
See Also
Categories
Find more on Data Type Identification 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!

