📄 matlab使用.txt
字号:
clc;clear;
fid = fopen('exp.txt', 'r');
fid_n=fopen('ex.dat','w');
while ~feof(fid)
tline=fgetl(fid);
if ~isempty(tline)
if double(tline(1))>=48 && double(tline(1))<=57 %数值开始
a=strread(tline);
a(3:4)=[];
fprintf(fid_n,'%f %f\n',a);
clear a;
elseif double(tline(1))==67 %字母C开始
[b1,b2,b3,b4]=strread(tline,'%s %s %s %s');
b=[b1{1},' ',b2{1}];
fprintf(fid_n,'%s\n',b);
clear b b1 b2 b3 b4;
else
fprintf(fid_n,'%s\n',tline);
end
else
fprintf(fid_n,'%s\n',tline);
end
end
fclose(fid);
fclose(fid_n);
. load data.txt和A=load(‘data.txt’)的区别请参阅精华贴:[原创]写给学习 matlab 的新手们4. 请根据读写需要来打开文件,即根据你的需要来指定 fopen 的 permission 属性为读或写。如果只用 a 进行写入,就不能用 fread 读取。此时应该写完关闭文件,然后用 r 打开读取,或者直接用 a+ 进行同时读写操作。否则,会产生莫名其妙的问题!以下代码是一个错误的例子:
[Copy to clipboard] [ - ]
CODE:filename='e.dat';
fid=fopen(filename,'a');
if fid<0
error('fopen error');
end
s=[1 2 3 4;5 6 7 8];
fwrite(fid,s,'float32')
[dd ll]=fread(fid,inf,'float32');%把t中的数据全部读出,即s矩阵。
fclose(fid);
A = rand(3,2);
[filename,pathname] = uiputfile({'*.bin';'*.dat';'*.*'},'Save as');
fid = fopen([pathname,filename],'w');
if fid~=-1
fwrite(fid,A,'float32');
if(fclose(fid)==-1)
error('Can not close the file!');
end
else
error('Can not open the file!');
end
[filename,pathname] = uigetfile({'*.bin';'*.dat';'*.*'},'Read from');
fidr = fopen([pathname,filename],'r');
if fidr~=-1
B = fread(fidr,'float32');
B = reshape(B,size(A));
if(fclose(fidr)==-1)
error('Can not close the file!');
end
else
error('Can not open the file!');
end
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -