写入数据 使输入的数据显示在文本编辑器中
save函数可用于将矩阵中的数据写入数据文件,或附加到数据文件中。格式为:
save filename matrixvariablename –ascii
“-ascii”限定符用于创建文本或数据文件时,-ascii是一个描述性语句,意思是以字符的形式存储。使用以下方法创建一个矩阵,然后将矩阵变量的值保存到一个名为testfile.dat的数据文件中:
mymat= rand(2,3)
save testfile.dat mymat -ascii (也可以使用.txt拓展名)
②type testfile.dat
type命令可用于显示文件的内容;请注意,使用了科学符号
%%在上面的基础上继续,生成mymat2,执行save语句,会覆盖掉原来的内容
>> mymat2=rand(4,3)
mymat2 =
0.6555 0.2769 0.6948
0.1712 0.0462 0.3171
0.7060 0.0971 0.9502
0.0318 0.8235 0.0344
>> save testfile.dat mymat2 -ascii %-ascii是一个描述性语句,意思是以字符的形式存储
>> type testfile.dat
6.5547789e-01 2.7692298e-01 6.9482862e-01
1.7118669e-01 4.6171391e-02 3.1709948e-01
7.0604609e-01 9.7131781e-02 9.5022205e-01
3.1832846e-02 8.2345783e-01 3.4446081e-02
%%在上面的基础上继续,生成mymat3,在原存储基础上添加内容
>> mymat3=rand(4,3)
mymat3 =
0.4387 0.1869 0.7094
0.3816 0.4898 0.7547
0.7655 0.4456 0.2760
0.7952 0.6463 0.6797
>> save testfile.dat mymat3 -ascii -append%-ascil是一个描述性语句,意思是以字符的形式存储,append是在原存储内容的基础上添加
>> type testfile.dat
6.5547789e-01 2.7692298e-01 6.9482862e-01
1.7118669e-01 4.6171391e-02 3.1709948e-01
7.0604609e-01 9.7131781e-02 9.5022205e-01
3.1832846e-02 8.2345783e-01 3.4446081e-02
4.3874436e-01 1.8687260e-01 7.0936483e-01
3.8155846e-01 4.8976440e-01 7.5468668e-01
7.6551679e-01 4.4558620e-01 2.7602508e-01
7.9519990e-01 6.4631301e-01 6.7970268e-01
%%也可以添加不是同一列数的矩阵
>> mymat4=rand(3,4)
mymat4 =
0.6551 0.4984 0.5853 0.2551
0.1626 0.9597 0.2238 0.5060
0.1190 0.3404 0.7513 0.6991
>> save testfile.dat mymat4 -ascii -append%-ascil是一个描述性语句,意思是以字符的形式存储,append是在原存储内容的基础上添加
>> type testfile.dat
6.5547789e-01 2.7692298e-01 6.9482862e-01
1.7118669e-01 4.6171391e-02 3.1709948e-01
7.0604609e-01 9.7131781e-02 9.5022205e-01
3.1832846e-02 8.2345783e-01 3.4446081e-02
4.3874436e-01 1.8687260e-01 7.0936483e-01
3.8155846e-01 4.8976440e-01 7.5468668e-01
7.6551679e-01 4.4558620e-01 2.7602508e-01
7.9519990e-01 6.4631301e-01 6.7970268e-01
6.5509800e-01 4.9836405e-01 5.8526775e-01 2.5509512e-01
1.6261174e-01 9.5974396e-01 2.2381194e-01 5.0595705e-01
1.1899768e-01 3.4038573e-01 7.5126706e-01 6.9907672e-01
题目
Q:提示用户输入一个矩阵的行数和列数,创建一个包含这么多个行和列的随机数的矩阵,并将其写入一个文件。
A:%提示用户输入矩阵的行数和列数
r=input(‘Enter the number of rows:’);
c=input(‘Enter the number of columns:’);
%创建有上述输入行和列的矩阵,随机整数矩阵,1-100
mat=randi([1,100],[r,c]);
%将上述矩阵写入’randMat.dat’的文件中
save randMat.dat mat -ascii;
读取数据
>> load randMat.dat
>> type randMat.dat
3.6000000e+01 5.5000000e+01 7.6000000e+01 5.7000000e+01 5.4000000e+01
8.4000000e+01 9.2000000e+01 7.6000000e+01 8.0000000e+00 7.8000000e+01
5.9000000e+01 2.9000000e+01 3.9000000e+01 6.0000000e+00 9.4000000e+01
Q:在2010年的四个季度中,把XYZ公司的两个独立部门的销售额(以数十亿美元计)都存储在一个文件salesfigs.dat中;创建如图所示的图(它使用圆圈和星星作为图符号)。
A:首先,创建这个文件(只需在编辑器中键入数字,然后另存为salesfigs.dat)
将数据读入矩阵中。
然后,写一个脚本,它将这个矩阵分离成两个向量。
%先创建salesfigs.dat文件
load salesfigs.dat
asales=salesfigs(1,:);
bsales=salesfigs(2,:);
plot(asales,'ko');
hold on;
plot(bsales,'k*');
xlabel('Quarter');
ylabel('Sales (billions)');
title('XYZ Corporation Sales: 2010');
legend('Division 1','Division 2');