how to read specific rows in multiple text files and store them into an matrix?
22 views (last 30 days)
Show older comments
fileNames = dir('---\C1*.txt');
Tmatrix = zeros(TraceCount,T);
for i=1:TraceCount
file2read = fileNames(i).name;
fid = fopen('file2read', 'r');
Tmatrix(i,:)= textscan(fid, '%f', -----);
fclose(fid);
end
4 Comments
Adam Danz
on 2 Jul 2018
Here's a demo using textscan which extracts rows 2,4,6 from the attached txt file that is formatted according to your description.
But try the answer below that uses fscanf() as that method may be most suitable.
fid = fopen('fakedata.txt');
t = textscan(fid, '%f');
fclose(fid);
% read lines [2,4,6]
store = t{:}([2,4,6]);
Answers (1)
OCDER
on 2 Jul 2018
Edited: OCDER
on 2 Jul 2018
Since each txt file has a single column of numbers, you could use fscanf:
FileNames = dir(fullfile(pwd, '**\C1*txt'));
FileNames = fullfile({FileNames.folder}, {FileNames.name});
GetLines = [10 100]; %want lines 10 to 100
Nums = cell(1, length(FileNames));
for j = 1:length(FileNames)
FID = fopen(FileNames{j});
fscanf(FID, '%f', GetLines(1)-1); %Skips the 1-9 lines
Nums{j} = fscanf(FID, '%f', diff(GetLines)+1); %Reads the 10-100 lines
fclose(FID);
end
Nums = horzcat(Nums{:}); %Puts it all together into a single 91xlength(FilesNames) matrix
0 Comments
See Also
Categories
Find more on Data Type Conversion 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!