MATLAB: Comma separated data with text using dlmwrite

commadlmwrite

Hello,
I am trying to achieve this string in a .txt file.
SPCD,1,1,3,1.9628e-05
and not this S,P,C,D,1,1,3,1,.,9,6,2,8,e,-,0,5
I have the following data in MATLAB:
n=12;
node_num=linspace(1,n,n)';
A = [1.96276396551253e-05,NaN,1.96298099346691e-05,1.96279640136501e-05;1.96276396551253e-05,NaN,1.96298099346691e-05,1.96279640136501e-05;1.96276396551253e-05,NaN,1.96298099346691e-05,1.96279640136501e-05;]
SPC = reshape(A,n,1);
for j = 1:n
R = {char('SPCD'), num2str(1), num2str(j), num2str(3), num2str(SPC(j))};
dlmwrite('try2.txt', R,'precision', '%.10f','newline', 'pc','-append');
end
I hope this makes sense and you can help. Thank you in advance. Sausan

Best Answer

Try with the following instead of DLMWRITE.
fid = fopen('try3.txt', 'w') ; % Opens file for writing.
for j = 1:n
fprintf(fid, 'SPCD,1,%d,3,%.10f\r\n', j, SPC(j)) ;
end
fclose(fid) ; % Closes file.
There is an issue with DLMWRITE which wants to "convert to matrix" its data argument. This is, in your case, what creates this array of comma-separated characters. Also, calling an I/O function which opens/closes a file from within a loop is not efficient; a better solution would be to call it once only with a cell array that contains all the data, which you cannot do because of the issue that I just mentioned.
Note that the format that you are using in the example is not the format (%.10f) specified in the call to DLMWRITE, so you might want to update the call to FPRINTF using a format like %.4e for example.