displaying matrix in .txt file (fprintf)
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Filip Puczek
am 23 Mai 2019
Beantwortet: Filip Puczek
am 24 Mai 2019
Hello.
I have matrix with complex numbers with different numbers of digits. I want to print them to the file but they are not aligned.
|1.00+0.00i 1.00+0.00i 1.00+0.00i 1.00+0.00i|
|0.00+0.00i -49.00+4.00i -49.00-4.00i -52.00+0.00i|
|0.00+0.00i -2417.00-0.00i -2417.00+0.00i -2392.00+0.00i|
|0.00+0.00i -117649.00-64.00i -117649.00+64.00i -117676.00+0.00i|
I need something like this:
|1.00+0.00i 1.00+0.00i 1.00+0.00i 1.00+0.00i|
|0.00+0.00i -49.00+4.00i -49.00-4.00i -52.00+0.00i|
|0.00+0.00i -2417.00-0.00i -2417.00+0.00i -2392.00+0.00i|
|0.00+0.00i -117649.00-64.00i -117649.00+64.00i -117676.00+0.00i|
This is code that I print it into file
for k=1:n
fprintf(fileID,' |%.2f%+.2fi %.2f%+.2fi %.2f%+.2fi %.2f%+.2fi|\r\n',[real(A(k,:));imag(A(k,:))]);
end
fprintf(fileID, '\r\n\r\n\r\n');
Is there any way to make this matrix more aligned?
0 Kommentare
Akzeptierte Antwort
Raj
am 23 Mai 2019
Just tweaked you code itself a little bit:
fileID=fopen('MyFile.txt','w'); % Open text file for writing
for k=1:3
fprintf(fileID,' |%.2f%+.2fi %10.2f%+.2fi %10.2f%+.2fi %10.2f%+.2fi|\r\n',[real(A(k,:));imag(A(k,:))]);
end
fprintf(fileID,' |%.2f%+.2fi %10.2f%+.2fi %10.2f%+.2fi %10.2f%+.2fi|\r\n',[real(A(4,:));imag(A(4,:))]);
fprintf(fileID, '\r\n\r\n\r\n');
fclose(fileID); % Close the file
Gives:
0 Kommentare
Weitere Antworten (2)
Stephen23
am 23 Mai 2019
Bearbeitet: Stephen23
am 23 Mai 2019
No loop required:
mat = [1,1,1,1;0,-49+4i,-49-4i,-52;0,-2417,-2417,-2392;0,-117649-64i,-117649+64i,-117676];
fmt = ' |%.2f%+.2fi %21.2f%+.2fi %21.2f%+.2fi %21.2f%+.2fi|\n';
fprintf(fmt,permute(cat(3,real(mat),imag(mat)),[3,2,1]))
Giving:
|1.00+0.00i 1.00+0.00i 1.00+0.00i 1.00+0.00i|
|0.00+0.00i -49.00+4.00i -49.00-4.00i -52.00+0.00i|
|0.00+0.00i -2417.00+0.00i -2417.00+0.00i -2392.00+0.00i|
|0.00+0.00i -117649.00-64.00i -117649.00+64.00i -117676.00+0.00i|
Note that if you want to perfectly align all columns and the number of digits of the imaginary part is non-constant (like with your example data) then you will need to create the substrings first, padd/trim them to some length, and then fprint them.
Note that if you open the file in text mode you can simplify your format definitions by just using the newline, e.g.:
fid = fopen(..., 'wt'); % text mode!
fprintf(fid,'... \n') % \r is automatically added! (on Windows)
fclose(fid)
0 Kommentare
Siehe auch
Kategorien
Mehr zu Characters and Strings 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!