Generic code to import data from set of txt files?

조회 수: 12 (최근 30일)
Mark
Mark 2013년 12월 20일
편집: kjetil87 2013년 12월 20일
I have a set of text files that have a 1x6 vector of data in each. The names of the text files are based on timestamps and are not periodic. I'd like to be able to put some variable number N of these text files into a folder, and then have a script that will load the vector from each text file into the nth row of a data matrix in MATLAB. Is there a way to do this for variable number of arbitrarily named txt files? I imagine a code like this:
N = {a command to count the number of txt files in directory}
data=zeros(N,6)
for i = 1:N
data(i,:) = {command to load data from the ith txt file in the directory}
end
So I am trying to see if there are MATLAB commands to do this generically without having to specify specific number of txt files or their names each time I compile a set of them into the directory.
Thanks!

답변 (2개)

Paul
Paul 2013년 12월 20일
you could use the commands here:
to get the file names. Then loop over these names importing one by one.

kjetil87
kjetil87 2013년 12월 20일
편집: kjetil87 2013년 12월 20일
To find all .txt files in a directory use:
myDir = 'C:\iHaveStoredSomethingHere\'; %last backspace is important!
dirInfo = dir([myDir,'*.txt']);
filenames = {dirInfo.name};
N = numel(filenames);
data=cell(N,1); %need to use cell, you are not 100% sure all files has same lengths etc.
for i=1:N
fid = fopen([myDir,filenames{i}] );
data{i} = textscan(fid,'%s ');
fclose(fid);
end

카테고리

Help CenterFile Exchange에서 Data Import and Analysis에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by