MATLAB Answers


Why does the text file does not show me lines printed on next lines even when i used '\n' while printing the data in Matlab?

Asked by sachin narain on 15 Apr 2019
Latest activity Edited by Stephen Cobeldick on 15 Apr 2019
I have a text file which i have created which has some data in it . I use '\n' to print each line on the next line using a for loop in the code .
I did this because i wanted to use 'textscan' later to create a cell array with this so that i can work on this file on Matlab.
BUt when i open the file in the directory , all the lines are printed one after the other , but in Matlab it shows the lines are well printed line after line .
I am attaching the text file i created and how it is showing on Matlab and when i open normally from the directory outisde Matlab.
Any help will be appreciated.I am attaching the code with it .Thank you.


Sign in to comment.


1 Answer

Answer by Stephen Cobeldick on 15 Apr 2019
Edited by Stephen Cobeldick on 15 Apr 2019
 Accepted Answer

You should fopen the file in TEXT mode:
fid = fopen(....'wt')
% ^ TEXT mode!
Or alternatively stop using retrograde Windows applications like Notepad.
"Why does the text file does not show me lines printed on next lines..."
Because you opened the file in BINARY mode which prints exactly the character that you requested (i.e. \n) but on Windows a new text line is indicated with two characters \r\n, which therefore your file does not contain and so your file is not shown on multiple lines. The simplest solution is to fopen the file in TEXT mode, which automatically makes this conversion for you.
This topic has been discussed thousands of times on this forum: search for "fopen newline".


Thak you for the repsonse , but will the appending command work if i dont put '+a' because as i said while printing in the file , i am using a for,loop .
Thank youa again
You can use the TEXT mode while reading, writing, or appending: just add the t character, e.g. 'at+', exactly as the fopen help describes.

Sign in to comment.