我有一个以下参数文件,我想在其中更改左侧的值,从gam.dat
开始直到1 1 1
(针对-tail variable, head variable, variogram type
),而不更改文件的格式。
将在循环内调用此参数文件,以便循环的每次迭代都需要更改此参数文件中的值。
从文件中读取和写入一直是我的弱点。有关如何轻松完成此任务的任何帮助?谢谢!
Parameters
**********
START OF PARAMETERS:
gam.dat -file with data
1 1 - number of variables, column numbers
-1.0e21 1.0e21 - trimming limits
gam.out -file for output
1 -grid or realization number
100 1.0 1.0 -nx, xmn, xsiz
100 1.0 1.0 -ny, ymn, ysiz
20 1.0 1.0 -nz, zmn, zsiz
4 30 -number of directions, number of h
1 0 1 -ixd(1),iyd(1),izd(1)
1 0 2 -ixd(2),iyd(2),izd(2)
1 0 3 -ixd(3),iyd(3),izd(3)
1 1 1 -ixd(4),iyd(4),izd(4)
1 -standardize sill? (0=no, 1=yes)
1 -number of gamma
1 1 1 -tail variable, head variable, gamma type
答案 0 :(得分:1)
这样的事可能会有所帮助。然后它可能不再是你正在寻找的。 p>
fid = fopen(filename as a string);
n = 1;
textline = [];
while( ~feof(fid) ) // This just runs until the end of the file is reached.
textline(n) = fgetl(fid)
// some operations you want to perform?
// You can also do anything you want to the lines here as you are reading them in.
// This will read in every line in the file as well.
n = n + 1;
end
fwrite(fid, textline); // This writes to the file and will overwrite what is already there.
// You always write to a new file if you want to though!
fclose(fid);
我建议在这里使用fgetl
的唯一原因是因为看起来根据线路或线路中的信息,您要进行特定的操作/更改。您也可以使用fread
来执行相同的操作,但是在构建矩阵后,您必须在整个矩阵上进行操作,而不是在读取数据并构建矩阵时对其进行任何修改。 / p>
希望有所帮助!
基于以下评论的更完整示例。
fid = fopen('gam.txt');
n = 1;
textline = {};
while( ~feof(fid) ) % This just runs until the end of the file is reached.
textline(n,1) = {fgetl(fid)}
% some operations you want to perform?
% You can also do anything you want to the lines here as you are reading them in.
% This will read in every line in the file as well.
if ( n == 5 ) % This is just an operation that will adjust line number 5.
temp = cell2mat(textline(n));
textline(n,1) = {['newfile.name', temp(regexp(temp, '\s', 'once'):end)]};
end
n = n + 1;
end
fclose(fid)
fid = fopen('gam2.txt', 'w') % this file has to already be created.
for(n = 1:length(textline))
fwrite(fid, cell2mat(textline(n));
end
fclose(fid)