MATLAB: Fopen issues, not writing properly

fopenloopMATLABtext file

Hi everyone,
basename = 'cuboid';
ending = strcat('_',num2str(a),'.txt');
name = strcat(basename,ending);
fileID = fopen(name,'w');
fprintf(fileID,'%22.16f %22.16f %22.16f %22.16f %22.16f %22.16f %22.16f \r\n',transpose(grid));
fclose(fileID);
fileID = [];
fprintf('Finished %d \n',a)
I am trying to write data from a matrix to a text file called cuboid_# where pound is a number given by a for loop index, as I am trying to write many. It works for the first few hundred, but around a = 470, the script fails with the following error:
"Error using fclose Invalid file identifier. Use fopen to generate a valid file identifier.
Error in cuboid_timescan (line 56) fclose(fileID); "
The file ID is consistently positive, so I am not sure what the issue is, especially since it works for files of a lower index.
Does anyone know what the issue here is?

Best Answer

  • Lots of things wrong with your code. Just try this. Ask questions if you don't understand it.
    baseName = 'cuboid';
    a = 123;
    grid1 = rand(1, 7); % Don't use grid as a name!!!!
    baseFileName = sprintf('%s_%d.txt', baseName, a)
    fullFileName = fullfile(pwd, baseFileName)
    fileID = fopen(fullFileName, 'wt');
    fprintf(fileID,'%22.16f %22.16f %22.16f %22.16f %22.16f %22.16f %22.16f \r\n',transpose(grid1));
    fclose(fileID);
    fileID = []; % Not necessary
    fprintf('Finished writing %d.\n', a);
    winopen(fullFileName); % Open the file to look at it.