Textscanning and exporting several text files

4 views (last 30 days)
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

Accepted Answer

Chandra Kurniawan
Chandra Kurniawan on 27 Jan 2012
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.

More Answers (1)

Liisa
Liisa on 30 Jan 2012
Thank you, that was very helpful and did solve my problem.

Community Treasure Hunt

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

Start Hunting!