我有一个文件t1.txt放在MATLAB的默认文件夹work下,内容是
学号 姓名 数学 英语 语文
20101001 Sally 88 30 77
20101002 Paul 90 80 62
20101003 Lily 73 85 53
20101004 Tom 82 74 90
20101005 Peter 96 68 87,
题目要求是按照每个人三科的平均分降序排序,然后写出到t2.txt文件中,并在写出的文件中加入平均分。下面是程序:
[a b c d e]= textread('t1.txt','%n %s %n %n %n',5);
[c d e]= textread('t1.txt','%n %n %n',5);
A=[c d e];
B=mean(A,2);
C=[a c d e B];
[D,pos]=sort(C(:,5),'descend');
C=C(pos,:);
b=b(pos,:);
fid=fopen('t2.txt','wt');
fprintf(fid,'学号 姓名 数学 英语 语文 平均分\n');
for i=1:5
r=num2str(b{i,1});
fprintf(fid,'%d %s %.1f %.1f %.1f',a(i),r,c(i),d(i),e(i),C(i,5));
fprintf(fid,'\n');
end
fclose(fid);
它老是说错误是这个:
??? Trouble reading number from file (row 1, field 1) ==> 学号 姓名 数学 英语 语文\n
Error in ==> textread at 177
[varargout{1:nlhs}]=dataread('file',varargin{:});
Error in ==> Untitled5 at 1
[a b c d e]= textread('t1.txt','%n %s %n %n %n',5);
可是我这里真的没错啊。。。
哎。。。还是不行
追答clc;clear;
fid = fopen('t1.txt');
tline=fgetl(fid);
A=zeros(4,3);
i=1;
while 1
tline=fgetl(fid);
if tline ==-1
break;
end
temp=tline(17:end);
A(i,:)=str2num(temp);
i=i+1;
end
这段代码能帮你读出里面的数据,后面的你自己应该知道怎么做。
恩,是的。