displaying matrix in .txt file (fprintf)

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?

 Réponse acceptée

Raj
Raj le 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:
Capture.JPG

Plus de réponses (2)

Stephen23
Stephen23 le 23 Mai 2019
Modifié(e) : Stephen23 le 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)
Filip Puczek
Filip Puczek le 24 Mai 2019

0 votes

Thank you very much guys. Now it looks perfect :)

Catégories

En savoir plus sur Graph and Network Algorithms dans Centre d'aide et File Exchange

Produits

Version

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by