how to read specific rows in multiple text files and store them into an matrix?

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

my text files are having only one column each (with floating point values). i want to read 10 to 100 rows from each file and store them into Tmatrix. its showing error.pls help
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.
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]);

Sign in to comment.

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

Asked:

on 2 Jul 2018

Commented:

on 2 Jul 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!