Mosawi
Mosawi

Reputation: 197

Matlab: produce a text file containing text and numbers from a loop

I would like to produce a text file containing the following (with exact line breaks):

EXIT
POWDER DIFFRACTION (2-D)
C:\Users\themosawi\folder\file_0100.tif
EXIT
POWDER DIFFRACTION (2-D)
C:\Users\themosawi\folder\file_0101.tif
EXIT
POWDER DIFFRACTION (2-D)
C:\Users\themosawi\folder\file_0102.tif
EXIT

I wrote the following code

for i = 100:102
j = sprintf('%04d', i)
k = (['EXIT','',...
'POWDER DIFFRACTION (2-D)','',...
'C:\Users\themosawi\folder\file_' j '.tif']);
end
fid=fopen('MyFile.txt','w');
fprintf(fid, k);
fclose(fid);

But I am getting a text file with a single line containing this:

EXITPOWDER DIFFRACTION (2-D)C:

What am I doing wrong?

Upvotes: 0

Views: 59

Answers (1)

Suever
Suever

Reputation: 65430

Within your loop, you only store the last value for k. You then open the file outside of your loop and write only the last k. You should consider opening the file before the loop and then write to it within the loop (using fprintf).

% Open the file
fid = fopen('MyFile.txt', 'w');

for k = 100:102
    % Write an entry in the file for this value of k
    fprintf(fid, 'EXIT\r\nPOWDER DIFFRACTION (2-D)\r\nC:\\Users\\themosawi\\folder\\file_%04d.tif\r\n', k);
end

% Close the file
fclose(fid);

Upvotes: 1

Related Questions