Script help: Import several .txt files into a single data matrix
5 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(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
0 个评论
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...
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!