How to insert a number in a txt template

조회 수: 3 (최근 30일)
Homayoon
Homayoon 2015년 9월 12일
댓글: Walter Roberson 2015년 9월 13일
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

채택된 답변

Star Strider
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
Homayoon
Homayoon 2015년 9월 13일
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 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 CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by