Open multiple files in Matlab

6 views (last 30 days)
Yro
Yro on 11 Mar 2020
Commented: Ameer Hamza on 13 Mar 2020
Hi everyone, I have multiple files that I want to open using fopen. The files have a similar pattern, I have tried to use a for loop as follows, but it does not work. Any ideas how to open each file. Thanks in advance
for ii = 0:12
file = fprintf('population_%d.dat', ii); % -----> File names
generations_fid = fopen(file); % Question ???
matrix = {};
while ~feof(generations_fid)
generations = cell2mat(textscan(generations_fid, repmat('%f', 1, (3))));
if isempty(generations)
fgetl(generations_fid);
else
matrix{end+1} = generations;
end
end
end

Answers (1)

Ameer Hamza
Ameer Hamza on 11 Mar 2020
Edited: Ameer Hamza on 11 Mar 2020
Do something like the following. It will automatically all the files with extension .dat and open them one by one.
files = dir('*.dat');
for i=1:length(files)
generations_fid = fopen(files(i).name);
.... your code
fclose(generations_fid);
end
  8 Comments
Walter Roberson
Walter Roberson on 13 Mar 2020
Imagine a file that had multiple "generations:" headers. The textscan %f format would stop reading when it hit the "g" because "g" is not valid in a number. The data up to there would be returned by textscan and stored by the code. The loop would say it is not end of file so textscan would be called again. This time the "g" is the first thing in the buffer so textscan returns no data. The loop would detect the isempty and would do an fgetl(), reading in the "generations" line and throwing it away. The loop would then continue, potentially reading another block of data.
Thus what the code does is to read as much data as possible and store it, then throw away the rest of the line that stopped it from reading, and then start reading again, storing the new group separately.
The code is thus correct to initialize "matrix" in the place it does, because matrix is responsible for all the numeric data from one file, as blocks rather than put together into a single numeric matrix. The problem with the code was that it was not storing those cell arrays for each input file.
Ameer Hamza
Ameer Hamza on 13 Mar 2020
Walter, Thanks for clarifying. I wasn't fully aware of the working of the textscan.

Sign in to comment.

Categories

Find more on Data Import and Export 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!