Clear Filters
Clear Filters

using fprintf instead of dlmwrite to make a .txt file

6 views (last 30 days)
Hello everyone :)
I'm having a bit of a problem. As the title suggests I'm trying to use fprintf instead of dlmwrite to make a .txt file. I was asked to 'write explicit CR LF – line endings \r\n in c string formatting notation used by matlab'. However I'm not really sure what that means!
I have a few matrices that I need to put into a .txt file. I had it done using dlmwrite, however I was asked to use fprintf or sprintf instead. I've gone onto the Mathworks pages for them and read everything but I just can't wrap my head around it. Could someone help guide me in the right direction? I'm not looking for the answer, just some guidance.
My code, using dlmwrite:
dlmwrite('bathymetry.txt',AA,'delimiter',' ','precision',6);
'delimiter',' ','roffset',0,'precision',6);
'delimiter',' ','roffset',0,'precision',6);
'delimiter',' ','roffset',0,'precision',6);
'delimiter',' ','roffset',0,'precision',6);
I've also attached a picture of why I need to use the other method!
Thanks :)

Accepted Answer

Guillaume on 13 Oct 2016
Edited: Guillaume on 13 Oct 2016
Well, if all you want to do is ensure that the line endings of your files is consistently CR /LF, then the simplest thing is to add 'newline', 'pc' to all your dlmwrite calls, e.g.:
dlmwrite('bathymetry.txt',AA,'delimiter',' ','precision',6, 'newline', 'pc');
Much simpler than converting all those dlmwrite to sprintf within a loop. It will run faster as well.
There are several conventions for marking the line endings in text file. On windows CR / LF is typically used, On Linux, LF on its own is typically used. CR stands for Carriage Return, and LF for Line Feed, names coming from the time we still used typewriters. In those times, you needed to send both a carriage return command (return the carriage to the beginning of the line) and a line feed command (move the paper up a line) to start the next line.

More Answers (1)

Meghan on 13 Oct 2016
Edited: Meghan on 13 Oct 2016
Actually I figured it out. But I'll post how I did it for anyone else who doesn't know.
fprintf(fid,'%g %g %g %g\r\n',AA);
for i=1:length(Tri.nodes2);
fprintf(fid,'%g %g %g %g %g \r\n',Tri.nodes2(i,:));
fprintf(fid,'%g %g %g \r\n',CC);
for i=1:length(DD);
fprintf(fid,'%g %g %g %g \r\n',DD(i,:));

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!