MATLAB Answers

How to fprintf with

32 ビュー (過去 30 日間)
JMP Phillips
JMP Phillips 2015 年 9 月 2 日
コメント済み: JMP Phillips 2015 年 9 月 4 日
I want to fprintf to a text file a cell with contents '\begin{table}' the problem is it doesn't work because matlab thinks \b is a control character. How to do this?
  2 件のコメント
JMP Phillips
JMP Phillips 2015 年 9 月 2 日
Thankyou, the %s\n works. If you repost as an answer I can accept it (otherwise I don't think you get any credit).

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

採用された回答

Greig
Greig 2015 年 9 月 3 日
Expanding my comment above to add in some LaTex specific requirements, here is a basic working example
% Define some data
T = [{'Header1'}, {'Header2'}, {'Header3'}; {1.234343}, {32.131234}, {85.23401}; {0.1123}, {0.12213}, {4}];
fout=fopen('Test_File.dat', 'wt');
fprintf(fout, '%s\n', '\begin{table}'); % start the table
fprintf(fout, '%s & %s & %s \\\\\n', T{1,:}); % print the header
fprintf(fout, '%2.3f & %2.3f & %2.3f \\\\\n', T{2:end,:}); % print the data
fprintf(fout, '%s', '\end{table}'); % end the table
fclose(fout)
  1 件のコメント
JMP Phillips
JMP Phillips 2015 年 9 月 4 日
Thanks for the example. I use the matlab-data-to-latex-table package, to get the correctly formatted latex table as a Nx1 cell, then it's just
for i = 1:N
fprintf(fileID, '%s\n',latex_table{i});
end
to print to file.

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

その他の回答 (2 件)

Stephen
Stephen 2015 年 9 月 2 日
編集済み: Stephen 2015 年 9 月 2 日
The easiest solution is to supply the string as an argument, and not define it in the format string itself, then you do not need to escape any characters at all because characters in argument arrays are interpreted literally:
fprintf(fid, '%s', '\begin{table}The student scored 82.3\%');
You could even do something neat like this, which provides a newline but without changing the input string:
fprintf(fid, '%s\n', '\begin{table}The student scored 82.3\%');

Walter Roberson
Walter Roberson 2015 年 9 月 2 日
If you must code the '\begin{table}' in the format specification instead of in the data like Grieg shows, then you need to use two \ for each place you want a single \ in output.
fprintf(fid, '\\begin{table}')
You also need to use %% to represent any % characters that must appear literally, such as
fprintf(fid, '\\begin{table}The student scored 82.3%%');
  2 件のコメント
JMP Phillips
JMP Phillips 2015 年 9 月 2 日
I am using this one which is the best I've found, but I had to modify it for non-numeric data: https://au.mathworks.com/matlabcentral/fileexchange/44274-converting-matlab-data-to-latex-table

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by