Matlab:生成一个包含循环中文本和数字的文本文件(Matlab: produce a text file containing text and numbers from a loop)
我想生成一个包含以下内容的文本文件(带有确切的换行符):
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我写了以下代码
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);但我得到一个文本文件,其中包含一行包含:
EXITPOWDER DIFFRACTION (2-D)C:我究竟做错了什么?
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 EXITI 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?
最满意答案
在循环中,您只存储k的最后一个值。 然后在循环外打开文件,只写最后一个k 。 您应该考虑在循环之前打开文件, 然后在循环中写入它(使用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);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);更多推荐
发布评论