MATLAB将数据写入窗口、文本文件和二进制文件
1、第一,根据气体状态方程pres=rho*R*T计算气压值,然后将温度值T和气压值pres按照指定的格式(formatSpec)输出到命令行窗口。
启动MATLAB,新建脚本(Ctrl+N),输入如下代码:
close all; clear all; clc
rho=1.293; R=287.14; T=273.15:303.15; pres=rho*R*T;
p(1:31,1)=T; p(1:31,2)=pres;
%%%%%%% 1 input to the screen %%%%%%%
formatSpec='Temperature is %7.2f K and Pressure is %11.2f Pa\n';
for i=1:31
fprintf(formatSpec,p(i),p(i+31))
end
其中温度T赋值给数据p(31行*2列)的第1列,气压pres赋值给数据p(31行*2列)的第2列。
2、第二,保存和运行上述脚本,在命令行窗口(Command Window)得到如下结果:
Temperature is 273.15 K and Pressure is 101412.95 Pa
Temperature is 274.15 K and Pressure is 101784.22 Pa
Temperature is 275.15 K and Pressure is 102155.50 Pa
Temperature is 276.15 K and Pressure is 102526.77 Pa
Temperature is 277.15 K and Pressure is 102898.04 Pa
.
.
.
3、第三,下面将温度值T和气压值pres写入文本文件(txt),接着输入如下代码:
%%%%%%% 2 input to the text file %%%%%%%
fileID2=fopen('pressure.txt','w');
fprintf(fileID2,'%10s %10s\r\n','Teperature','Pressure');
for i=1:31
fprintf(fileID2,'%7.2f %11.2f\r\n',p(i),p(i+31));
end
其中fprintf(fileID2,'%10s %10s\r\n','Teperature','Pressure')是往文本文件pressure.txt中写入一行字符串'Teperature'和'Pressure';
fprintf(fileID2,'%7.2f %11.2f\r\n',p(i),p(i+31))是文本文件pressure.txt中写入温度值p(i)和气压值p(i+31)。数据p的前31个值是温度值,后31个值是气压值,或者说数据p的第一列是温度值,第二列是气压值。
4、第四,保存和运行上述脚本,在MATLAB路径文件夹下得到文本文件pressure.txt,打开该文件,数据写入情况如下图。
5、第五,下面将温度值T和气压值pres写入二进制文件(binary),接着输入如下代码:
%%%%%%%% 3 input to the binary file %%%%%%
fileID3=fopen('pressure.bin','w');
fwrite(fileID3,p,'single');
fclose(fileID3);
其中single表示将数据按照浮点型单精度(32比特,4字节)写入二进制文件pressure.bin.
6、第六,保存和运行上述脚本,在MATLAB路径文件夹下得到二进制文件pressure.bin,查看其属性,大小为248字节(31行*2列*4字节=248字节)。