Search code examples
matlabfopen

Open multiple files in Matlab


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

Solution

  • You want to be using sprintf to dynamically generate the file name, not fprintf.

    file = sprintf('population_%d.dat', ii);

    It's also good practice to open your file with the required permissions. In your case, it looks like you're reading, so you should use

    generations_fid = fopen(file, 'r');