How to print 1x50 array into a text file
31 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hello,
I have 1x50 array A=[0.020 0.600 49.915 0.000 0.100 0.000 30.910 51.340 30.850 .... 0.000]
and want to print them into a text file with the below format.
0.020 0.600 49.915 0.000 0.100 0.000 30.910 51.340
30.850 51.460 13.378 4.600 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000
How should I do this?
1 Commento
Jan
il 23 Mag 2019
Modificato: Jan
il 23 Mag 2019
And what exactly is the "below format"? Do you want spaces or tab stops between the numbers? Tab stops before the line breaks? A fixed number of 8 columns, or does this depend on the number of elements? A trailing linebreak or not? 10 characters per number and 3 digits after the point? Please mention the details.
Risposta accettata
Jan
il 23 Mag 2019
Maybe:
[fid, msg] = fopen(FileName, 'w');
assert(fid ~= -1, 'Cannot open file for writing: %s\n%s\n', FileName, msg);
fmt = [repmat('%10.3f', 1, 8), '\n'];
fprintf(fid, fmt, A.');
fclose(fid);
Più risposte (2)
Akira Agata
il 23 Mag 2019
How about the following?
dlmwrite('output.txt',reshape(A(1:48),8,6)','delimiter','\t');
dlmwrite('output.txt',A(49:50),'-append','delimiter','\t');
2 Commenti
Akira Agata
il 23 Mag 2019
Dear Hossein-san,
Thank you for your comment.
Sorry, I've missed your 'fprintf' tag in your original post.
Just FYI, your can save as %10.3f format by dlmwrite function, too, by:
dlmwrite('output.txt',reshape(A(1:48),8,6)','delimiter','\t','precision','%10.3f');
dlmwrite('output.txt',A(49:50),'-append','delimiter','\t','precision','%10.3f');
Raj
il 23 Mag 2019
Modificato: Raj
il 23 Mag 2019
Answer given by Akira is the optimal solution but since you have mentioned 'fprintf' as a tag, here are two ways to get what you want using 'fprintf'
fid=fopen('MyFile.txt','w'); % Open text file
fprintf(fid, '%10.3f %10.3f %10.3f %10.3f %10.3f %10.3f %10.3f %10.3f\r\n',A); % Write 8 elements in each line from A with 3 digits after decimal
fclose(fid); % Close the file
or an even weird way:
fid=fopen('MyFile.txt','w');
for i=1:numel(A)
if rem(i,8)~=0
fprintf(fid, ' %10.3f',A(1,i));
else
fprintf(fid, ' %10.3f\r\n',A(1,i));
end
end
fclose(fid);
Good luck!!
0 Commenti
Vedere anche
Categorie
Scopri di più su Environment and Settings in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!