Writing string and numerical values to same line in .txt file

6 ビュー (過去 30 日間)
Andreas Burheim Volden
Andreas Burheim Volden 2016 年 4 月 2 日
コメント済み: dpb 2016 年 4 月 2 日
Hi! I need to write data from matlab workspace to a .txt file. This is not the problem. However, writing a string followed by a numerical value on the same line I've not managed to solve.
The attached file(txt-fil) depict the current .txt file with the faulty line highlited. The below code produces said file, including the faulty line, which is caused by the code entry "...'Nsecs='... and the entry below "....'Amodl='... The two code lines needs altering, but I don't know how. The end result should look like the second attachment(txt-fil_2), where Nsecs and Amodl is stacked with their corresponding numerical values.
filename = 'modell_septic.txt';
fid = fopen(filename,'w+');
if fid ~= -1
fprintf(fid, [oppirom 'Modellfil for SEPTIC' '\r\n']);
fprintf(fid, [oppirom 'Nsecs=' ' ' '%f' 1 '\r\n']);
fprintf(fid, [oppirom 'Amodl=' ' ' 200 '\r\n']);
fprintf(fid,'%f %f %f %f \r\n',mat);
fclose(fid);
Any help or ideas are appreciated. Thanks!

採用された回答

dpb
dpb 2016 年 4 月 2 日
secs=1; % define as variables; hardly worth the effort as fixed strings...
modl=200;
...
fprintf(fid,'%10s=%5d\n','Nsecs',1);
fprintf(fid,'%10s=%5d\n','Amodl',200);
...
Use the 't' optional flag in the fopen call to force the OS-dependent \n sequence automatically. The old Notepad is almost the only still-extant app that doesn't handle it gracefully...
fid = fopen(filename,'wt+');
I suggest first trying w/o it and with only '\n' and see if you do have an issue; if so, then use the 't' as shown...
  2 件のコメント
Andreas Burheim Volden
Andreas Burheim Volden 2016 年 4 月 2 日
Thank you!
dpb
dpb 2016 年 4 月 2 日
No problem, you were mixing up format strings and outputs; format is always first then the outputs trail...
And, of course, I really intended
fprintf(fid,'%10s=%5d\n','Nsecs',secs);
fprintf(fid,'%10s=%5d\n','Amodl',modl);
...
with the variables in the locations for the constants, of course...

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by