How to create a loop function to import .dat files

1 次查看(过去 30 天)
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

回答(1 个)

Pratik Anand
Pratik Anand 2017-7-11
编辑:Pratik Anand 2017-7-11
>> 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 个评论
Thomas
Thomas 2017-7-11
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by