How to insert a number in a txt template
3 次查看(过去 30 天)
显示 更早的评论
Dear All,
I have a (50*1) matrix whose elements are random integers. Also, I have a text file template. I need to write a code in which i can call the first element of my matrix and insert than number in the specific location of my text file. Then, the output should be saved as file1.txt. For all of the 50 elements of the matrix I need to create 50 output files i.e. file1.txt to file50.txt.
The line number which my number should be inserted in is 74, and has the following format:
velocity all create 5000 mom yes dist gaussian
well, now if my random number is a 7-digits integer like 1234567, this line will change into :
velocity all create 5000 1234567 mom yes dist gaussian
and if the random number in the matrix is a 6-digits integer like 123456, the mentioned line will have to change into:
velocity all create 5000 123456 mom yes dist gaussian
As you can easily see, there are two spaces between 5000 and mom in this line. What I need is to insert my number, whatever it is, in between 5000 and mom starting from column # 34. Obviously, the line should be extended by 7 columns to the right if the integer has 7 digits, and similarly for 6-digits integers and etc.
I do appreciate if anyone can help me with this issue. It can save me mucg time.
Thanks.
Best,
HRJ
0 个评论
采纳的回答
Star Strider
2015-9-12
This should do what you want:
N = randi(1E8, 50, 1);
for k1 = 1:length(N)
fid = fopen(sprintf('file%d.txt', k1),'wt');
fprintf(fid, 'velocity all create 5000 %d mom yes dist gaussian', N(k1))
fclose(fid);
end
NOTE: I did not test this because I didn’t want to create and then have to delete all those files.
3 个评论
Walter Roberson
2015-9-13
fprintf(fid,'%s\n', 'dump_modify 1 format "%5d %5d %25.10g %25.10g %25.10g"');
fprintf(fid,'%s\n\n', 'dump_modify 1 sort id');
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!