1. 高级文件的I/O操作
高级:针对不同的数据格式文件,提供不同的文件I/O函数,有现成函数共使用
低级:使用文件标识符访问任何类型数据文件,需要较复杂的编程
1. 读写MAT或ASCII文件
保存工作空间中的变量
双精度、二进制的matlab格式文件 .mat,具有可移植性
分文两部分:文件头部及数据
使用save函数进行保存
>> str1 = 'dafei';
>> str2 = 'dafei2';
>> str3 = 'dafei3';
% *为通配符
>> save strs str*
>> whos -file strs
Name Size Bytes Class Attributes
str1 1x5 10 char
str2 1x6 12 char
str3 1x6 12 char
保存结构体
>> S.a = [1 2 3];
>> S.b = 'Hello';
>> S.c = {'abs', 9};
>> S
S =
包含以下字段的 struct:
a: [1 2 3]
b: 'Hello'
c: {'abs' [9]}
% 将结构体整体保存
>> save s1 S
>> whos -file s1
Name Size Bytes Class Attributes
S 1x1 760 struct
%将结构体每个字段保存为独立变量
>> save('s2', '-struct','S')
>> whos -file s2
Name Size Bytes Class Attributes
a 1x3 24 double
b 1x5 10 char
c 1x2 222 cell
% 保存结构体中的某一字段
>> save('s3', '-struct', 'S','b')
>> whos -file s3
Name Size Bytes Class Attributes
b 1x5 10 char
扩展已存在的MAT文件,使用-append
>> str4 = 'meao';
>> save('strs','str4','-append')
>> whos -file strs
Name Size Bytes Class Attributes
str1 1x5 10 char
str2 1x6 12 char
str3 1x6 12 char
str4 1x4 8 char
如果不使用-append 会导致同名
输出数据默认采用二进制的MAT格式,若要使用ASCII格式要在后面加上 -ascii
从MAT文件中加载数据到工作空间使用load 函数
2. 读写TXT文件
[A, B, C] = textread('filename','format')
界定符的意思是 将元素存储在文件中使用什么方法隔开
3. 读写EXCEL文件
type = xlsfinfo('filename') 检查是否能被xlsread读取
>> xlswrite('newfile',[1 2 3 4 5])
>> type = xlsfinfo('newfile')
type =
'Microsoft Excel Spreadsheet'
>> xlsread('newfile')
ans =
1 2 3 4 5
% 添加至指定工作表
>> xlswrite('a1',[1 2 3; 4 5 6],3,'D2:F3')
4. 读写图像文件
读写函数文件的函数:imwrite、imread、imfinfo
将图像数据写到图片文件中用imwrite,从figure图像直接生成图像文件用函数print和saveas
print(h,‘format’,filename)
print函数输出图像大小与页面设置有关,用printpreview设置