How to insert a number in a txt template

3 views (last 30 days)
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

Accepted Answer

Star Strider
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
Homayoon
Homayoon on 13 Sep 2015
can you help me on this please?
Dear All,
Well I have a text that I have to fprintf it into a text file using my matlab code. But I cannot figure what the output is not what I expect. Is there anything wrong with my code?
Here is the text I need to be written in my output file:
dump_modify 1 format "%5d %5d %25.10g %25.10g %25.10g"
dump_modify 1 sort id
Here is my code:
fprintf(fid,'dump_modify 1 format "%5d %5d %25.10g %25.10g %25.10g" \n\')
fprintf(fid,'dump_modify 1 sort id\n\n')
but the output is something strange!
dump_modify 1 format "dump_modify 1 sort id
Thanks so much for helping me.
Walter Roberson
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');

Sign in to comment.

More Answers (0)

Categories

Find more on Cell Arrays 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!