Open multiple files in Matlab

6 次查看(过去 30 天)
Yro
Yro 2020-3-11
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

回答(1 个)

Ameer Hamza
Ameer Hamza 2020-3-11
编辑:Ameer Hamza 2020-3-11
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 个评论
Walter Roberson
Walter Roberson 2020-3-13
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 2020-3-13
Walter, Thanks for clarifying. I wasn't fully aware of the working of the textscan.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Import and Export 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by