Matlab:生成一个包含循环中文本和数字的文本文件(Matlab: produce a text file containing text and numbers from a loop)

编程入门 行业动态 更新时间:2024-10-26 11:19:21
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 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?

最满意答案

在循环中,您只存储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);

更多推荐

本文发布于:2023-07-17 10:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1142804.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本文件   数字   Matlab   文本和   produce

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!