I am using the code presented below to read a matrix and apply a semicolon (;) and newline at the end of every value.
I am having problems with the precision format specifier. Below the code block is a line from the csv output. You can see that columns 5 and 6 are formatted properly, but there are exponential values that I need rounded to 14 decimal places. Why isn't the '%f.14'on line 4 doing this? I thought it didn't use exponential notation?
function write_to_csv(filepath, decision)
csv = fopen('matrix.csv', 'a+');
for ii = 1:length(decision)
format = '%d; %f.14';
fprintf(csv, format, decision(ii));
end
fprintf(csv,'\n')
fclose(csv);
end
1; 1.032204e-03; -2.580511e-04; 1; 32190201170708; 17682101210450; 2; 7.600000e-01; -1;
Credit to MChandler for supplying the above code from question: Add a delimiter to end of each line of csv file MATLAB
解决方案
This depends on the format of the variable decision. Since you have %d before the %f.14 it will render a 1-dimensional matrix as only %d. It will completely ignore the fixed point format specifier. If your matrix decision is indeed 1-dimensional, use format = '%.14f'; as mentioned in the comments:
function write_to_csv(filepath, decision)
csv = fopen('matrix.csv', 'a+');
for ii = 1:length(decision)
format = '%.14f';
fprintf(csv, format, decision(ii));
end
fprintf(csv,'\n')
fclose(csv);
end