How to create a loop function to import .dat files

3 views (last 30 days)
Hi all! With the help of the import selection function, I have created a function called importfile, that will import specific constraints of a matrix. I want to run this function for all of the .dat files that I have in my current folder. The files in my current folder are titled as RC451.dat, RC459.dat, RC448.dat etc...
The function looks like this...
RC449 = importfile('RC449.dat', 4, 128);
Is there any way to create a 'for' loop that will run this function for each file? Below I have provided the script that I attempted to use to solve this problem, but it didn't work.
files = dir('*.dat');
numfiles = length(files);
mydata = cell(1, numfiles);
for k = 1:numfiles
files(k) = importfile('files.dat', 4, 128);
end

Answers (1)

Pratik Anand
Pratik Anand on 11 Jul 2017
Edited: Pratik Anand on 11 Jul 2017
>> files(k) = importfile('files.dat', 4, 128);
has the issue. In your code after executing the following line :
>> files = dir('*.dat');
variable files contains the names of all the files as a struct array. Its documentation is here. Each individual struct can be accessed by providing an index into the array, for example, files(2) gives access to the second struct in files. Since importfile() requires filename as the first argument, you will need to retrieve the name of the given file from the struct, for example, files(2).name. In the given loop, variable k is already counting the index, which you can use .
A possible replacement is :
temp_value = importfile(files(k).name, 4, 128);
However, you may want to implement the changes differently.
  1 Comment
Thomas
Thomas on 11 Jul 2017
Would you have any suggestions as to how I could make the output reflect the title of the .dat file? Instead of temp_value, how could I make the output name something like RC449, RC459, etc

Sign in to comment.

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!