Kristian
Kristian

Reputation: 1239

Reading multiple .dat files into MatLab

I am having great difficulties reading a bunch of .dat files into MatLab. I have tried to Google the problem, but after one hour I still can't get my code to work. In total I have 141 .dat files. Each file consist of three lines of header information (which I do not want to include), and then a bunch of rows, each with three columns of numbers. I want to merge the rows from all the .dat files into one large matrix featuring all the rows, and three columns (since each row in all .dat files contains three numbers). This is the code I have attempted to use:

d = dir('C:\Users\Kristian\Documents\MATLAB\polygoner1\');
out = [];
N_files = numel(d);
for i = 3:N_files
    fid = fopen(d(i).name,'r');
    data = textscan(fid,'%f%f%f','HeaderLines',3);
    out = [out; data];
end

However, when I try to run the code I get the error message

??? Error using ==> textscan
Invalid file identifier.  Use fopen to generate a valid file identifier.

Error in ==> readpoly at 6
    data = textscan(fid,'%f%f%f','HeaderLines',3);

If anyone knows how I can get this to work, then I would be extremely grateful!

Upvotes: 0

Views: 736

Answers (1)

Ikaros
Ikaros

Reputation: 1048

The problem is when you use fopen, you are not giving the full path of the file

path = 'C:\Users\Kristian\Documents\MATLAB\polygoner1\'
d = dir(path);

....

%as @craigim advised it, otherwise you can use strcat
my_file = fullfile(path, {d.name}) 
for i = 3:N_files
    fid = fopen(my_file{i},'r');

    ....

    fclose(fid);
end

Upvotes: 1

Related Questions