MATLAB: Doesn’t the carriage return (or new-line character) in fprintf work properly

MATLAB

When the '\n' character is used in the FPRINTF statement, the new-line/carriage return is sometimes ignored. In other words, the output strings will be displayed on one line even though the new-line character ('\n') is specified within the fprintf statement.

Best Answer

Some applications (e.g. Notepad, Lotus 123) do not recognize the new-line character just by itself, and require the carriage return character to be used concurrently with the new-line character. Since MATLAB's FPRINTF function does not automatically add a carriage return, the new-line character may be ignored or appear as a black box when viewed with these applications.
This only happens if you FOPEN the output file in default (binary) mode; so when opening text output files, you should explicitly open them in text mode. In text mode line separators get special treatment and this problem is taken care of. To open in text mode, add 't' to the permission string, for example 'rt' and 'wt+':
fid = fopen('test.txt','wt');
On Unix and Macintosh systems, text and binary mode are the same so this has no effect. But on PC and VMS systems this is critical.