MATLAB: Save text files without an empty line in the end

formattext file

For some reason I need to save a matrix to a .txt file without an extra blank line in the end. For example, when I save [1;2;3] to a text file, the file will have an empty forth row, which I want to get rid of. I've tried 'save', 'dlmwrite', 'fprintf',…but none of them worked.

Best Answer

Use fprintf with newline \n for all but the last entry in x, which is written separately without \n:
x = [1;2;3];
fid = fopen('foo.txt', 'w');
fprintf(fid, '%f\n', x(1:end-1))
fprintf(fid, '%f', x(end))
fclose(fid)