假设要读取的文本文件为test.txt,文件内容分别如下:
1 2 3
4 5 6
7 8 9
A 1 2 3
B 4 5 6
C 7 8 9
读取纯数据文件
>> I = load('test.txt')
I =
1 2 3
4 5 6
7 8 9
读取文本和数据混合文件
方法一:importdata
>> I = importdata('test.txt')
I =
data: [3x3 double]
textdata: {3x1 cell}
rowheaders: {3x1 cell}
>> I.data
ans =
1 2 3
4 5 6
7 8 9
>> I.textdata
ans =
'A'
'B'
'C'
>> I.rowheaders
ans =
'A'
'B'
'C'
方法二:textscan
>> fid = fopen('test.txt');
>> C = textscan(fid,'%s %d %d %d');
>> C{1}
ans =
'A'
'B'
'C'
>> C{2}
ans =
1
4
7
>> C{3}
ans =
2
5
8
>> C{4}
ans =
3
6
9
输出矩阵到文本文件
function mat2txt(M)
% 输出矩阵到txt文件
[m,n] = size(M);
fid = fopen('D:\matlab\DIP\qxy\data.txt','wt');
for i = 1 : m
for j = 1 : n
if j == n
fprintf(fid,'%4.3f\n',M(i,j));
else
fprintf(fid,'%4.3f\t',M(i,j));
end
end
end
fclose(fid);