MATLAB: Are the values I write into a file are not the same as what I read from it

file readingfile writing

I use dlmwrite to write a matrix into a .txt file. If I then use dlmread to take these values from the file and compare this matrix with the original matrix, the values are not exactly the same, i.e., the accuracy of the floating digits is lost. Is there a way to exactly store the matrix values? Thanks in advance.

Best Answer

Use fprintf and fscanf :
x = 0:.1:1;
A = [x; exp(x)];
% write to file
fileID = fopen('exp.txt','w');
fprintf(fileID,'%6s %12s\n','x','exp(x)');
fprintf(fileID,'%6.2f %12.8f\n',A);
fclose(fileID);
% read the file
fid = fopen('exp.txt');
A = fscanf(fid, '%g %g', [2 inf]);
fclose(fid);