MATLAB: How to write a matrix to a text file with special delimiters

MATLAB

I want to write a matrix to a text file with double-space delimiters. How can I accomplish this in MATLAB?

Best Answer

The double-space delimiters are not standard delimiters, and are not supported in high-level I/O functions such as "dlmwrite":
or "writematrix" (introduced in R2019a):
To write a matrix to a file with special delimiters, you may use the low-level I/O function "fprintf":
Here is a code example showing how to use "fprinf" to accomplish double-space delimiters:
file = 'demo.dat'; % file name
A = reshape(1:9, 3, 3); % matrix to be written to the file
precision = '%.5f'; % desired precision for values in A (for possible values of this parameter, see https://www.mathworks.com/help/matlab/ref/fprintf.html#btf8xsy-1_sep_shared-formatSpec)
delimiter = ' ';
line_terminator = '\n';
write_general_matrix(file, A, precision, delimiter, line_terminator);
function write_general_matrix(file, matrix, precision, delimiter, line_terminator)
format = [create_fmt(precision, delimiter, size(matrix, 2)) line_terminator];
fid = fopen(file, 'w');
fprintf(fid, format, matrix');
fclose(fid);
end
function s = create_fmt(prec, dlm, n_fmt)
s = prec;
for i = 1:2*(n_fmt-1)
if mod(i, 2) == 1
s = [s dlm];
else
s = [s prec];
end
end
end
The example above is quite generic. One can customize the code to his/her own needs by changing the values of "file" / "A" / "precision" / "delimiter" / "line_terminator".