Matlab 不使用单元格替换txt文件中的N行
有没有一种更快的方法可以在不使用单元格的情况下将文件的第三行替换为另一行 我用过这段代码,但它会减慢我的程序,尤其是我的txt文件由1000多行组成Matlab 不使用单元格替换txt文件中的N行,matlab,file,fopen,Matlab,File,Fopen,有没有一种更快的方法可以在不使用单元格的情况下将文件的第三行替换为另一行 我用过这段代码,但它会减慢我的程序,尤其是我的txt文件由1000多行组成 % Read txt into cell A fid7 = fopen([handles.filenameproba],'r'); i = 1; tline = fgetl(fid7); A{i} = tline; while ischar(tline) i = i+1; tl
% Read txt into cell A
fid7 = fopen([handles.filenameproba],'r');
i = 1;
tline = fgetl(fid7);
A{i} = tline;
while ischar(tline)
i = i+1;
tline = fgetl(fid7);
A{i} = tline;
end
fclose(fid7);
% Change cell A
newval =...
A{3} = sprintf('StartExperiment:%s',num2str(newval);
% Write cell A into txt
fid7 = fopen([handles.filenameproba], 'w');
for i = 1:numel(A)
if A{i+1} == -1
fprintf(fid7,'%s', A{i});
break
else
fprintf(fid7,'%s\n', A{i});
end
end
fclose(fid7);
谢谢 如果性能是您最关心的问题,请尝试这种方法,看看是否更快-
f=importdata(handles.filenameproba,'')
f(3)={sprintf('StartExperiment:%s',num2str(newval))}
%%// Save the modified text file
fid1 = fopen(handles.filenameproba,'w');
for k = 1:numel(f)
fprintf(fid1,'%s\n',f{k});
end
fclose(fid1);
细胞不是你的问题。你的问题是一次读写一行。此外,在每次迭代中都要重新调整单元格数组的大小 对于下面的问题,我创建了一个包含10000行的测试文件
fileId = fopen('test.txt', 'w');
for i = 1:10000
fprintf(fileId, 'This is the %dth line.\n', i);
end
fclose(fileId);
我正在调用您的方法ranellMethod
>> timeit(@ranellMethod)
ans =
0.5160
更好的方法是限制必须执行的读/写操作的数量。假设您的文件足够小,您可以立即将整个内容读入内存。执行您的操作,并立即写入所有内容
function entireFileMethod()
fileName = 'test.txt';
fileId = fopen(fileName, 'r');
try
text = fread(fileId, '*char')'; %'
catch Me
fclose(fileId);
Me.rethrow();
end
fclose(fileId);
newLineInds = find(text == char(10));
newLine = sprintf('This is the new line. %1.*f', randi(10), rand);
newText = [text(1:newLineInds(2)), newLine, text(newLineInds(3):end)];
fileId = fopen(fileName, 'w');
try
fprintf(fileId, '%s', newText);
catch Me
fclose(fileId);
Me.rethrow();
end
fclose(fileId);
end
此函数有一个读取操作和一个写入操作:
>> timeit(@entireFileMethod)
ans =
0.0043
请参阅Matlab 中有关文件IO的更多详细信息。我认为使用TeXSCAN读取文件,用换行符作为定界符将比FGETL快得多,您也可以考虑用Python做这件事应该相当容易。