fprintf function and how to use it.

1 次查看(过去 30 天)
I am trying to use the fprintf function to print data as columns with headers in my command window. I have written the following code:
A = 100: 10: 250;
B = A*exp(4);
Data = [A', B'];
fprintf('A Ae^4 \n'); %(there are extra spaces here, but they are not visible)
fprintf('%u %u \n', [Data]');
When I run this code, it prints out the following:
A Ae^4
100 5.459815e+03
110 6.005797e+03
120 6.551778e+03
130 7.097760e+03
140 7.643741e+03
150 8.189723e+03
160 8.735704e+03
170 9.281686e+03
180 9.827667e+03
190 1.037365e+04
200 1.091963e+04
210 1.146561e+04
220 1.201159e+04
230 1.255757e+04
240 1.310356e+04
250 1.364954e+04
I am able to make my data print in two columns. However, I am having two issues with this function. To center the headers above the columns, I have to enter several spaces in my header string. Is there any way I can do this same thing with my formatting rules and avoid adding the spaces that make my string unnecessarily long.
Also, I was able to use the %u formatting rule in my string to format my first column as integers. When i use %f or %e, the column prints with decimals, or in scientific notation. I want to print my second column as integers as well. However, when i use the same formatting rule as I did for the first column, the data does not print out as integers. I am not able to understand why this occurs and therefore I have no idea how to fix it.
Any help is much appreciated! Thanks in advance!

采纳的回答

dpb
dpb 2015-2-14
Unfortunately, there is no format spec for "center in column", only left- and right-adjust. Thus, "yes, Virginia" you do have to count spaces to center a header in a column. The generic way is to use the quantity fix((fieldWidth-length(headerString))/2) to compute the count for blanks in building the header string.
To print floating point values as integers w/o a decimal use the specific formatting --
>> fprintf('%0.f\n',1000*pi)
3142
>>
This uses minimum field width; use a specific field width too to control the column.
>> fprintf('%8.0f\n',1000*pi)
3142
>>

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by