Using fprintf to print in text file

29 ビュー (過去 30 日間)
Sung Yeob Lim
Sung Yeob Lim 2019 年 9 月 22 日
コメント済み: Sung Yeob Lim 2019 年 9 月 27 日
Hi all,
I'm very very unfamiliar with MATLAB. I've been trying to write a code that can neatly organize the data that is stored in certain variables into a text file.
What I want the final product to look like is this:
Each column is stored in separate variables (e.g. nodeID=[1;2;3;4], X=[0;0;120;120], etc)
I've been trying to use frpintf function and got to where there is a breakline between the column titles and the numbers.
I'd like to know how to evenly space these numbers as shown in the picture. Currently I've been adding spaces (using ' ') via fprintf but this gives me something that looks like below:
the code i have is the following (it's embarrassing really):
here nNode = 4,
for i = 1:nNode
fprintf(txt,'\n');
fprintf(txt, '%d', nodeID(i));
fprintf(txt, ' ');
fprintf(txt, '%.2f', X(i));
fprintf(txt, ' ');
fprintf(txt, '%.2f', Y(i));
fprintf(txt, ' ');
fprintf(txt, '%.3f', fx(i));
fprintf(txt, ' ');
fprintf(txt, '%.3f', fy(i));
end
Is there a more efficient way to go about this issue?
Thanks a bunch :)
  2 件のコメント
Image Analyst
Image Analyst 2019 年 9 月 22 日
txt is the name of the file handle, right? That's probably a bad name for it since we might think it's a text string.
So you did
txt = fopen('Nodal Data.txt', 'wt');
before any of the code you're showing, right? Personally I'd use fid, fileID, or fileHandle as the handle to the file - it's a more descriptive name.
Sung Yeob Lim
Sung Yeob Lim 2019 年 9 月 22 日
編集済み: Sung Yeob Lim 2019 年 9 月 22 日
this is what i wrote
txt = fopen('output.txt','wt','n');
And thanks for the tip! I'll change it to fid :)

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

採用された回答

Athul Prakash
Athul Prakash 2019 年 9 月 25 日
編集済み: Athul Prakash 2019 年 9 月 25 日
Hey Sung,
Instead of printing a fixed number of spaces with ' ', you may set the total width of your value in the format string like this:
sprintf('%10.2f %10.2f', 120, 120) %Each value of 120 is displayed with total width 10 and precision 2.
Use '%w.2f' to set the width of the display value to 'w', which would fill in empty spaces as required.
This would align values in a column on the rightmost digit.
[I used 'w' to illustrate only. You can't use a variable this way, you will need to replace 'w' with your required number, say '%15.2f' or '%20.2f']
[sprintf and fprintf both work the same way, I used sprintf just to demonstrate]
Hope it helps!
  1 件のコメント
Sung Yeob Lim
Sung Yeob Lim 2019 年 9 月 27 日
Thank you! Now my columns look nicer :)

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by