How to insert a number in a txt template
2 views (last 30 days)
Show older comments
Homayoon
on 12 Sep 2015
Commented: Walter Roberson
on 13 Sep 2015
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 Comments
Accepted Answer
Star Strider
on 12 Sep 2015
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 Comments
Walter Roberson
on 13 Sep 2015
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');
More Answers (0)
See Also
Categories
Find more on Workspace Variables and MAT-Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!