How to properly format a data table with fprintf?

8 visualizaciones (últimos 30 días)
Kristof Lile
Kristof Lile el 21 de Sept. de 2021
Respondida: Stephen23 el 21 de Sept. de 2021
Hello, I am a bit new to MATLAB and I am having some trouble learning how to properly format using fprintf.
For example, given that
A=[1.00,2.00,3.00,4.00,5.00];
How would I use fprintf to get something that looks like this?:
Numbers 1.00 2.00 3.00 4.00 5.00
Here is what I tried, but I cannot get the "Numbers" heading correct with the values after it horizontally.
>> A=[1,2,3,4,5];
fprintf('Numbers %1.2f\n',A)
Numbers 1.00
Numbers 2.00
Numbers 3.00
Numbers 4.00
Numbers 5.00
>>
I read a bit of MATLAB's guide on fprintf, but it did not really help me understand.
Any help would be greatly appreciated.
Thanks!

Respuestas (2)

Star Strider
Star Strider el 21 de Sept. de 2021
In the numeric edit descriptors, the value to the left of the decimal is the field width (this includes all the numbers, the sign, and the decimal), or if omitted, only considers the precision to the right of the decimal, so to get the result you want, the format descirptor would have to be:
A=[1.00,2.00,3.00,4.00,5.00];
fprintf(['Numbers ' repmat('%.2f ',1,numel(A))],A)
Numbers 1.00 2.00 3.00 4.00 5.00
fprintf('\n')
There are also other variations to experiment with.
.

Stephen23
Stephen23 el 21 de Sept. de 2021
A = [1,2,3,4,5];
fprintf('Numbers%s\n',sprintf(' %1.2f',A))
Numbers 1.00 2.00 3.00 4.00 5.00

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by