how to read specific rows in multiple text files and store them into an matrix?
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
Paolo
on 2 Jul 2018
Can you attach a sample text file?
js rathore
on 2 Jul 2018
What error are you getting? Is there perhaps a line missing in your code?
TraceCount = numel(fileNames)
And what value is T? You can attach the file with the paperclip button.
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)
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
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!