Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write string as it is to a file in Matlab

Tags:

latex

matlab

In a matlab script, I'm generating a latex table. A part of that table for example looks likes this.

\multirow{2}{*}{\textbf{b1}}
&
2 & 3 & 10092 & 10763 & 103390 & 2797 & 2929 & 3008 & 5\% & 8\% \\
& 4 & 2 & 20184 & 10763 & 74508 & 1830 & 1970 & 2029 & 8\% & 11\% \\

This string is saved in variable str. Now when I try to write str to a file by using the following code.

f = fopen( 'report\results.tex', 'w' );
fprintf( f, str );
fclose(f);

I get the following warning.

Warning: Invalid escape sequence appears in format string. 
See help sprintf for valid escape sequences.

That is probably due to many backslash characters in my string, which is used as escape sequence. Now how can I print this string to a file as it is.

like image 204
pythonic Avatar asked Jan 27 '26 07:01

pythonic


1 Answers

escape the backslashes and percent signs:

str = strrep(str,'\','\\');
str = strrep(str,'%','%%');

If it's just text your printing, this'll be fine.

Minimal working example:

str = '2 & 3 & 10092 & 10763 & 103390 & 2797 & 2929 & 3008 & 5\% & 8\% \\'
str = strrep(str,'\','\\');
str = strrep(str,'%','%%');
f=fopen('testing123.txt','w');
fprintf(f,str);
fclose(f);

and the file reads:

2 & 3 & 10092 & 10763 & 103390 & 2797 & 2929 & 3008 & 5\% & 8\% \\

OR as Ben A. suggests, use fwrite:

fwrite(f,str)

and I think

fprintf(f,'%s',str)

will also do the trick, and it's best to also include a newline:

fprintf(f,'%s\n',str)
like image 200
Gunther Struyf Avatar answered Jan 30 '26 00:01

Gunther Struyf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!