Script help: Import several .txt files into a single data matrix
이전 댓글 표시
Hi there,
I have limited knowledge on scripting but know that loops are very powerful tools that will save me days of time.
I currently require a script that can take a 300*1 (300 lines in one column) of text from a plain .txt file and can upload it into an array that has 168 columns, one for each file, forming a 300*168 array. The files must be in order (currently named #_meants.txt, but the numbers are not sequential) when uploaded. Could anyone point me in the right direction?
Many Thanks
답변 (2개)
Michael Haderlein
2014년 7월 28일
First, you need to get the file names:
files=dir('*_meants.txt');
If necessary, you order them by
[~,ind]=sort({files.name});
files=files(ind);
If possible, you can initialize your matrix:
values=zeros(300,length(files));
Then, you indeed need a loop going through the files:
for cnt=1:length(files)
values(:,cnt)=dlmread(files(cnt).name);
end
dpb
2014년 7월 28일
d=dir('*.txt');
a=zeros(300,length(d)); % use given known size; if unknown read first outside loop
for i=1:length(d)
a(:,1)=importdata(d(i).name);
end
If the returned alphanumeric order isn't as needed, couple of choices --
a) sort the directory names as wanted, or
b) create a secondary file that has the list of names in desired order and traverse it instead of the directory.
for more options but I'm terribly fond of the dir solution if at all possible--it's just so much cleaner...
카테고리
도움말 센터 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!