How to create a loop function to import .dat files

조회 수: 1 (최근 30일)
Thomas
Thomas 2017년 7월 11일
댓글: Thomas 2017년 7월 11일
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