It may have something to do with the -append option, that according to the help appends the result to the end of the file.
You are accessing the same file with two functions, fprintf and dlmwrite.
This is probably not efficient, but closing the file after every write from fprintf would work:
clear all
close all
file_name = 'aa.txt';
file = fopen(file_name, 'w');
fclose(file);
file = fopen(file_name, 'a');
M = randn(5);
for kk = 1:10
file = fopen(file_name, 'a');
fprintf(file, 'Hi\n');
fclose(file);
dlmwrite(file_name, M ,'-append', 'newline', 'pc');
file = fopen(file_name, 'a');
fprintf(file, 'Bye\n');
end
If not, just try to print the matrix with other funcion that you create and that uses the same file handler as fprintf.