Comma separated data with text using dlmwrite
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Akzeptierte Antwort
Cedric
am 4 Aug. 2013
Bearbeitet: Cedric
am 4 Aug. 2013
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.
0 Kommentare
Weitere Antworten (1)
Sausan Khomusi
am 4 Aug. 2013
5 Kommentare
Cedric
am 4 Aug. 2013
Bearbeitet: Cedric
am 4 Aug. 2013
If I understand well your question, here is an example taking every 6th element:
>> values = 101:120 % Fake data, to illustrate.
values =
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
>> ix = 1:6:length(values) % Indices of relevant elements.
ix =
1 7 13 19
>> values_subset = values(ix)
values_subset =
101 107 113 119
Which you will probably write in a more condensed way once you understand:
>> values_subset = values(1:6:end) ;
Siehe auch
Kategorien
Mehr zu Text Files finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!