MATLAB: Won’t \n give me a new line

fidformatfprintfnext line

I tried as below, and I expected it will give me:
//+
Point(10) = {0.77258 0.54961 0.56139 0.67184};
However, it gives me:
//+\nPoint(10) = {0.77258 0.54961 0.56139 0.67184};
And the code I wrote is:
for i_file = 1:10
point = rand(1,4);
fid = fopen('structure_test','wt');
fprintf(fid,'%s\n%s',['//+\nPoint(',num2str(i_file),') = {',num2str(point),'};']);
fid = fclose(fid);
end

Best Answer

Because all characters in the input strings are interpreted literally.
With fprintf and sprintf only the format strings can contain special characters (e.g. '\n') that will be interpreted in some special way. For the all of the other input arguments, all characters are literal.
fprintf('%s\n','\n')
special ^^ ^^ literal
Note that in MATLAB all char vectors are literal, so defining this:
vec = 'abc\ndef'
does not define a string with a newline (like in Python), it simply defines the char vector 'abc\ndef'. It is only inside the format string of sprintf and fprintf (and some other functions) where you can use special characters and expect them to be interpreted. Read the function help to know which functions support this.