Textscanning and exporting several text files
1 次查看(过去 30 天)
显示 更早的评论
Hi,
I'm trying to combine data from several text files (file1, file2, etc.) and export the data into one file (or matrix) after textscan loops and some basic calculation. I have only managed to export from the last loop (overwrites?). My code so far:
d = dir('*.txt');
for n=1:numel(d)
filepath=['..\matlab_testing\'];
filena=['file' num2str(n) '.txt'];
[filepath filena];
if exist([filepath filena])
fid=fopen([filepath filena],'rt');
out = [];
row = fgetl(fid);
data = textscan(fid, '%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f');
out = [out;cell2mat(data)];
end
idx1 =out(:,3) == 100;
h1 = out(idx1,:);
xlswrite('h_ka_txt.xls',h1,'klo1', 'A2'); %works, but contains data only from the last file
How to continue so that I have one matrix that contains data from all the files?
Also, is the better way to textscan than (fid, '%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f'), if file has several hundred columns?
Thank you, all the help is greatly appreciated, Liisa
0 个评论
采纳的回答
Chandra Kurniawan
2012-1-27
Hi, Liisa
Look at line
data = textscan(fid, '%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f');
Did you mean
data = textscan(row, '%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f');
And you can replace these lines
filepath=['..\matlab_testing\'];
filena=['file' num2str(n) '.txt'];
[filepath filena];
if exist([filepath filena])
fid=fopen([filepath filena],'rt');
with
fid = fopen(d(n).name,'rt');
Also at line
out = [];
should be placed outside the loop.
And about
data = textscan(row,'%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f');
out = [out; cell2mat(data)];
Can be replaced with
data = str2num(row);
out = [out; data];
So, the complete code is :
d = dir('*.txt');
out = [];
for n = 1 : numel(d)
fid = fopen(d(n).name,'rt');
row = fgetl(fid);
%data = textscan(row,'%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f');
data = str2num(row);
%out = [out; cell2mat(data)];
out = [out; data];
end
Now, just try to type out in command window and you'll get the result as 3 x 17 matrix.
I hope this helps.
0 个评论
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!