Vertical alignment of input using fprintf

3 vues (au cours des 30 derniers jours)
Zhi Wei Ku
Zhi Wei Ku le 22 Mai 2020
Modifié(e) : Stephen23 le 22 Mai 2020
I am using fprintf to present my output vertically.
>> for j = 1 : length( y )
fprintf( '%s%8.2f%8.2f\n',x{j}, y(j),z(j) )
end
Butane 1859.59 371.92
Oxygen 4095.45 767.90
Nitrogen gas13490.4913490.49
Maleic anhydride 0.00 1757.00
Acetic acid 0.00 15.37
Acrylic acid 0.00 18.44
Carbon monoxide 0.00 412.25
Carbon dioxide 0.00 647.74
Water 0.00 1964.93
Total19445.5319446.04
However, they way i want to present the output in this way
Butane 1859.59 371.92
Oxygen 4095.45 767.90
Nitrogen gas 13490.49 13490.49
Maleic anhydride 0.00 1757.00
Acetic acid 0.00 15.37
Acrylic acid 0.00 18.44
Carbon monoxide 0.00 412.25
Carbon dioxide 0.00 647.74
Water 0.00 1964.93
Total 19445.53 19446.04
What is the additional command I haved to added?
Thanks in advance.

Réponses (1)

Stephen23
Stephen23 le 22 Mai 2020
Modifié(e) : Stephen23 le 22 Mai 2020
>> x = {'Butane','Oxygen','Nitrogen gas','Maleic anhydride','Acetic acid','Acrylic acid','Carbon monoxide','Carbon dioxide','Water','Total'};
>> y = [1859.59,4095.45,13490.49,0.00,0.00,0.00,0.00,0.00,0.00,19445.53];
>> z = [371.92,767.90,13490.49,1757.00,15.37,18.44,412.25,647.74,1964.93,19446.04];
In the following examples I provided the fprintf input as a comma-separated list generated from a cell array, of course you can use a loop if you prefer.
Method 1: set the fprintf fieldwidth:
>> c = [x;num2cell(y);num2cell(z)];
>> fprintf('%-20s %8.2f %8.2f\n',c{:})
Butane 1859.59 371.92
Oxygen 4095.45 767.90
Nitrogen gas 13490.49 13490.49
Maleic anhydride 0.00 1757.00
Acetic acid 0.00 15.37
Acrylic acid 0.00 18.44
Carbon monoxide 0.00 412.25
Carbon dioxide 0.00 647.74
Water 0.00 1964.93
Total 19445.53 19446.04
Method 2: use char to fit all words:
>> c = num2cell(char(x),2).';
>> c(2,:) = num2cell(y);
>> c(3,:) = num2cell(z);
>> fprintf('%s %8.2f %8.2f\n',c{:})
Butane 1859.59 371.92
Oxygen 4095.45 767.90
Nitrogen gas 13490.49 13490.49
Maleic anhydride 0.00 1757.00
Acetic acid 0.00 15.37
Acrylic acid 0.00 18.44
Carbon monoxide 0.00 412.25
Carbon dioxide 0.00 647.74
Water 0.00 1964.93
Total 19445.53 19446.04
Method 3: no fprintf:
>> c = char(x);
>> c(:,end+1) = 32;
>> c = [c,num2str(y(:))];
>> c(:,end+1) = 32;
>> c = [c,num2str(z(:))];
>> c
c =
Butane 1859.59 371.92
Oxygen 4095.45 767.9
Nitrogen gas 13490.49 13490.49
Maleic anhydride 0 1757
Acetic acid 0 15.37
Acrylic acid 0 18.44
Carbon monoxide 0 412.25
Carbon dioxide 0 647.74
Water 0 1964.93
Total 19445.53 19446.04
  1 commentaire
Zhi Wei Ku
Zhi Wei Ku le 22 Mai 2020
It works! Thank you so much.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Thermal Analysis dans Help Center et File Exchange

Produits


Version

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by