Error while labeling the two column matrix (column) with header

6 次查看(过去 30 天)
I used the fprintf function to put header on the output matrix. column 1 should consist of temperature ranging from 100 to 500 with an increment of 50 with a header title of T(K), and column 2 has the k values found through the formula and the header title of K(1/min). My code is pasted below. However, when I run the code the output is not what I actually want. I have also posted what output I get when I run my code.
% code
Q = 8000;
R = 1.987;
k0 = 1200;
Temp = [100:50:500];
k = k0.*exp(-Q./(R.*Temp));
Data = [Temp; k]';
fileID = fopen('Reactionrates.txt', 'w');
fprintf(fileID, '%6s %12s\n', 'T(K)', 'k(1/min)');
fprintf(fileID, '%u %12.2e\n', Data);
type Reactionrates.txt
The output:
e
T(K) k(1/min)
100 1.50e+02
200 2.50e+02
300 3.50e+02
400 4.50e+02
500 3.92e-15
2.643777e-09 2.17e-06
1.216207e-04 1.78e-03
1.211554e-02 5.10e-02
1.561454e-01 3.82e-01

回答(1 个)

Geoff Hayes
Geoff Hayes 2015-2-16
编辑:Geoff Hayes 2015-2-16
Bharti - from fprintf, this function applies the format to all elements of the input arrays in column order. So in your example,
fprintf(fileID, '%u %12.2e\n', Data);
assumes that all columns of Data are to be written as two elements, an unsigned integer and a floating point number (in exponential format). So this is expecting that your matrix has only two rows and multiple columns. This is not the case for your Data since there are nine rows with two columns.
What you need to do is just transpose Data in the fprintf call so that it becomes a 2x9 matrix. If you do
fprintf('%u %12.2e\n', Data');
(note the apostrophe appended to Data so that it is transposed) we see that the data written to file is now the expected
100 3.92e-15
150 2.64e-09
200 2.17e-06
250 1.22e-04
300 1.78e-03
350 1.21e-02
400 5.10e-02
450 1.56e-01
500 3.82e-01

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by