0
votes

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!

1
What is formatSpec defined for? - Matthias W.
@MatthiasW. It's automatically defined by MATLAB to extract the values according to the format of the .dat file - jquery_stack
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
@jquery_stack - it was rather meant as a hint as you don't seem to be using it. - Matthias W.

1 Answers

0
votes

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