How to fprintf with
35 次查看(过去 30 天)
显示 更早的评论
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 个评论
Greig
2015-9-2
What version of MATLAB are you using? Can you give an example of what you have tried.
On 2014a, this simple example works OK....
T = {'\begin{Table}'}
fout=fopen('Test_File.dat', 'wt');
fprintf(fout, '%s\n', T{:});
And the output file contains
\begin{Table}
Simply using
fprintf(fout, '%s\n', '\begin{Table}');
Also gives the same result
采纳的回答
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)
更多回答(2 个)
Stephen23
2015-9-2
编辑:Stephen23
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\%');
0 个评论
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 个评论
Greig
2015-9-2
Since I assume they are writing a table to LaTeX, to fit the LaTeX syntax they will need to throw in an extra '\\' so that the % sign appears correctly in the final table
fprintf(fid, '\\begin{table}The student scored 82.3\\%%');
There are a couple of functions on the FileExchange for formatting MATLAB output to LaTeX. They maybe useful, but I have never tried them
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!