0

I have both a main code and a function that imports data from a .dat file and I'd like to import a lot of cases and therefore, I have created several directories to structure the files.

Here is the relevant part of the function I'm using:

function [time_,cm,cd_,cl,clf1,clr] = importcd2(filename, startRow, endRow)

formatSpec = '%7s%33s%24s%24s%24s%s%[^\n\r]';

%% Open the text file.
fileID = fopen(filename,'r');

textscan(fileID, '%[^\n\r]', startRow(1)-1, 'ReturnOnError', false);

And then, when I want to call the function from the main code, I use:

[a,~,b,~,~,~] = importvar('/folder1/folder2/folder3/folder4/folder5/file1.dat', 1, inf);

In which a and b are the variables I want to export from the .dat file. What I'd like to do is change the function so that fopen can open a whole path and not just the ID of the file (file1.dat), because I prefer to have some directories rather than 30 .dat files or more in the same directory. Is it possible? My question is different to How can I load 100 files with similar names and/or string in just one step in MATLAB?

Thanks in advance!

Community
  • 1
  • 1
jquery_stack
  • 261
  • 4
  • 17
  • Possible duplicate of [How can I load 100 files with similar names and/or string in just one step in MATLAB?](http://stackoverflow.com/questions/15366374/how-can-i-load-100-files-with-similar-names-and-or-string-in-just-one-step-in-ma) – GameOfThrows Jul 11 '16 at 08:43
  • What is `formatSpec` defined for? – Matthias W. Jul 11 '16 at 08:46
  • @MatthiasW. It's automatically defined by MATLAB to extract the values according to the format of the .dat file – jquery_stack Jul 11 '16 at 09:30
  • I'm confused what the issue is. `fopen` can open files on an absolute path and it looks like you're passing it an absolute path... – Suever Jul 11 '16 at 12:28
  • @jquery_stack - it was rather meant as a hint as you don't seem to be using it. – Matthias W. Jul 11 '16 at 14:08

1 Answers1

0

You can use the dir command to obtain all .dat file in the folder, then use for loop to go over all of them

function [time_,cm,cd_,cl,clf1,clr] = importcd2(dirname, startRow, endRow)
DatFiles = dir([dirname filesep '*.dat']);

for k=1:numel(DatFiles)
  fileID = fopen(DatFiles(k).Name,'r');
  ...
end
ThP
  • 2,312
  • 4
  • 19
  • 25