Textscanning and exporting several text files
조회 수: 2 (최근 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!